c# - How to handle Windows API LPTSTR output as a formal parameter output -
i'm trying determine classname of window calling getclassname()
on hwnd
receive findwindowbycaption()
. it's not working; see classname garbage characters (specifically, 4 question marks , strange non-alphanumeric character). getclassname()
, far understand it, writes data caller's buffer.
here's code:
[dllimport("user32.dll", setlasterror = true)] static extern system.intptr findwindow(string lpclassname, string lpwindowname); [dllimport("user32.dll", entrypoint = "findwindow", setlasterror = true)] static extern system.intptr findwindowbycaption(system.intptr zeroonly, string lpwindowname); [dllimport("user32.dll")] static extern int getclassname(system.intptr hwnd, [param: marshalas(unmanagedtype.lptstr)] system.text.stringbuilder lpclassname, int nmaxcount); ... system.intptr hwndmywindow = findwindowbycaption(system.intptr.zero, "my window"); if (hwndmywindow != null) { system.console.writeline("hwndmywindow = {0}", hwndmywindow); system.text.stringbuilder lpclassname = new system.text.stringbuilder(256); lpclassname.length = lpclassname.capacity - 2; int len = getclassname(hwndmywindow, lpclassname, lpclassname.length - 2); lpclassname.length = len; // set length actual length of classname system.console.writeline("hwndmywindow = {0}, classname = {1}", hwndmywindow, lpclassname.tostring()); } else { system.console.writeline("no such window."); }
what doing wrong? lpclassname
param of getclassname()
output... expected getclassname()
write classname stringbuilder
, it's not working right.
[param: marshalas(unmanagedtype.lptstr)]
lptstr not mean think does. way wrote these declarations, unmanagedtype.lpstr can work. or better yet, omit attribute, not necessary @ all, pinvoke marshaller understands stringbuilder.
you invoking 1990s these declarations, using "ansi" versions of these winapi functions. default [dllimport] unfortunately. not make sense use them, nobody runs windows 98 anymore. windows unicode operating system @ heart, write declarations match:
[dllimport("user32.dll", setlasterror = true, charset = charset.auto)] static extern system.intptr findwindow(string lpclassname, string lpwindowname); [dllimport("user32.dll", setlasterror = true, charset = charset.auto)] static extern int getclassname(system.intptr hwnd, stringbuilder lpclassname, int nmaxcount);
findwindowbycaption() bit cute, don't, pass null
1st argument. note have bug in error handling, findwindow fails intptr.zero, not null. , don't ignore error handling getclassname(). make loud bang throwing system.componentmodel.win32exception.
Comments
Post a Comment