MFC: How to i convert DWORD and BYTE to LPCTSTR in order to display in MessageBox

6.7k Views Asked by At

I'm using VS2005 with "using Unicode Character Set" option

typedef unsigned char       BYTE;  
typedef unsigned long       DWORD;

BYTE       m_bGeraet[0xFF];
DWORD      m_dwAdresse[0xFF];

How do i make the code work?

MessageBox (m_bGeraet[0], _T("Display Content"));  
MessageBox (m_dwAdresse[0], _T("Display Content"));  
3

There are 3 best solutions below

0
On

If it's essential that BYTE is 1-byte then you have to (optionally) convert your byte strings to wide strings using mbstowcs.

0
On

It looks like you might need some help with the C language itself, and I recommend you find a beginner's book on C that is not about Windows programming.

MessageBox() only displays C-style strings which are arrays of type char which contain a character with ASCII value 0. This zero character is the NUL character, and such strings are said to be "NUL-terminated" or "Zero-terminated." Only the characters prior to the NUL are displayed when the string is printed, or copied when the string is concatenated. However, if there is no NUL character in the array, then the string is not properly terminated and an attempt to display it could lead to a crash, or to "garbage" being displayed, as in: "Can I have a beer?#BT&I10)aaX?.

The szTitle and szText arguments to MessageBox() expect char * which are pointers to this type of string.

If you attempt to pass a BYTE instead of a char *, the value of the BYTE will be mistakenly treated as an address. MessageBox() will attempt to access memory at the value "specified" by the BYTE and an Access Violation will occur.

One solution to this problem is to allocate a buffer of type char and use snprintf_s to transcribe your data values to string representations.

For example:

char output_buffer[1024];

snprintf_s(output_buffer, dimensionof(output_buffer), "Geraet = 0x%02X", m_bGeraet[i]);
MessageBox(hwnd_parent, output_buffer, "Message from me:", MB_OK);

Would display a MessageBox with a message reading something like "Geraet = 0x35".

0
On
//easy way for bytes is to do this

CString sTemp;

sTemp.Format("my byte = %d", bySomeVal);

MessageBox(sTemp);

//for a DWORD try

sTemp.Format("Dword is %lu", dwSomeVal);

MessageBox(sTemp);

if you using MessageBox, i would suggest soetming like AfxMessageBox...