wstring to char* problem

Does anyone know why I get only 1st char of title and not full title?

I need to convert that title to char * becauseI want to use it with lua_pushlstring to return that string to my lua script

here's lua_pushlstring documentation: http://pgl.yoyo.org/luai/i/lua_pushlstring

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
static int GetActiveWindowTitle()
{
    wstring title;
    HWND handle = GetForegroundWindow();
	int len = GetWindowTextLengthW( handle )+1;
    wchar_t * omgtitle = new wchar_t[len];
	GetWindowTextW(handle,omgtitle,len);
	title += omgtitle;
	char *a=new char[title.size()+1];
	a[title.size()]=0;
	memcpy(a,title.c_str(),title.size());
	MessageBoxA(0,a,"Found",0);
	delete omgtitle;
	return 1;
}
You are doing a VERY BAD THING: You call GetWindowTextW() but you then use MessageBoxA()? Why not use MessageBoxW()? Is this to learn how to convert between ANSI and Unicode?
yea i am trying to learn that. I read wcstombs but still dont get it.. Why does title.c_str() hold only first char and whole sting? can anybody tell this? and how I could fix it.
Do you know the difference between the ANSI char set and the UNICODE char set?

ANSI chars are a single byte
UNICODE (well, UTF-16 UNICODE wchar_ts) are 2 byte

For the normal letters, the UNICODE chars are the same as the ANSI char + an extra 0 byte

for example, the UNICODE string for "Hello" is

{'H', '\0', 'e', '\0', 'l', '\0', 'l', '\0', 'o', '\0', '\0', '\0'}

So if you cast or, as you have done, copy this string into a char buffer, it looks like a series of short null terminated ANSI strings:

1
2
3
4
5
6
{'H', '\0'}
{'e', '\0'}
{'l', '\0'}
{'l', '\0'}
{'o', '\0'}
{'\0','\0'}


(Some UNICODE strings use both bytes and would have probably looked like a single string of random chars (including control char).)

You cannot just copy UNICODE to ANSI or vice versa. You must convert using either wcstombs or WideCharToMultiByte. As you care working with WIN32 calls already, I would user the latter here.

Andy
Last edited on
Topic archived. No new replies allowed.