Getting the Value from PWSTR #181
-
I'm not familiar with Win32 APIs at all, but I'm trying to get window names for all active windows and I think my issue is in dealing with PWSTR.
is some example code, windowNameChars is never populated even when GetWindowTextLength returns a value, so I know there is a window title. Do I need to initialize PWSTR with a char* first? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 14 replies
-
You have to initialize the public void GetAllWindowsInfo()
{
bool windowReturn = PInvoke.EnumWindows(
(HWND handle, LPARAM customParam) =>
{
int bufferSize = PInvoke.GetWindowTextLength(handle) + 1;
unsafe
{
fixed (char* windowNameChars = new char[bufferSize])
{
if (PInvoke.GetWindowText(handle, windowNameChars, bufferSize) == 0)
{
int errorCode = Marshal.GetLastWin32Error();
if (errorCode != 0)
{
throw new Win32Exception(errorCode);
}
return true;
}
string windowName = new string(windowNameChars);
this.logger.WriteLine(windowName);
}
return true;
}
},
(LPARAM)0);
}
} |
Beta Was this translation helpful? Give feedback.
-
If your goal is to simplify code, there should be another way (look at the end of my comment). Pinning should still occur just like fixed statement, but I'm not sure if it is safe (better to wait for @AArnott confirmation).
It's a slightly modified version of a sample I found here. I'm also wondering why the fixed statement. EDITThis code, although could look easier and cleaner, it has some risks well explained in #181 (reply in thread). It should be avoided unless someone has no problem to write additional code to handle the two points illustrated from @jnm2. The recommended way is the sample posted from @AArnott |
Beta Was this translation helpful? Give feedback.
-
Thanks for reminding this important rule. Maximum allowed length for a Window caption is 256 chars which is rarely filled. It should be safe to go straightly on stack. |
Beta Was this translation helpful? Give feedback.
-
From what is stated here, when compiled in Release mode, all assertion statements are removed unless some optimizations are disabled and this will inevitably affect performance. I really need to take the habit to use assertions when playing with Debug builds. I always believed that I had to manually remove them for the release build, but given that the compiler will do everything for me, I have no excuses. Do you have some library to recommend? The one from
Ohh... You mean that
Yes, I would say this is the main goal of
Thanks guys. So, If I'm not wrong this should be the right approach: |
Beta Was this translation helpful? Give feedback.
You have to initialize the
PWSTR
to actually point to a character buffer, otherwise you effectively pass in NULL.But if you forget the PWSTR part and just use
char*
, it gets a bit simpler. This works, with added error checking: