unice
unice

Reputation: 2842

Convert C# P/Invoke code to Python ctypes?

I'm having problem converting this C# code to python using ctypes. This code is for hiding windows 7 start orb. Here's the link.

[DllImport("user32.dll")]
private static extern IntPtr FindWindowEx(
       IntPtr parentHwnd,
       IntPtr childAfterHwnd,
       IntPtr className,
       string windowText);

IntPtr hwndOrb = FindWindowEx(IntPtr.Zero, IntPtr.Zero, (IntPtr)0xC017, null);

do i have to define

FindWindow = ctypes.windll.user32.FindWindowEx
FindWindow.restype = wintypes.HWND
FindWindow.argtypes = [
    wintypes.HWND, ##hWnd
    wintypes.HWND, ##hWnd
]

Or just use it directly? Sorry I'm new in using python ctypes.

hWnd = win32gui.FindWindowEx (win32gui.GetDesktopWindow(),
None,0xC017 ,None)

Upvotes: 1

Views: 1528

Answers (1)

Ben Hoyt
Ben Hoyt

Reputation: 11044

It'd be helpful to have the error message you're seeing. However, this is almost certainly because you need to use user32.FindWindowExW (or user32.FindWindowExA if you really want the ASCII, non-Unicode version) rather than straight FindWindowEx. You also need to specify argtypes for all four parameters.

Here's the prototype from the docs:

HWND WINAPI FindWindowEx(
  _In_opt_  HWND hwndParent,
  _In_opt_  HWND hwndChildAfter,
  _In_opt_  LPCTSTR lpszClass,
  _In_opt_  LPCTSTR lpszWindow
);

So what about this?

FindWindowEx = ctypes.windll.user32.FindWindowExW
FindWindowEx.argtypes = [
    wintypes.HWND,
    wintypes.HWND,
    wintypes.LPCWSTR,
    wintypes.LPCWSTR,
]
FindWindowEx.restype = wintypes.HWND

You can also do FindWindow (rather than FindWindowEx) as per the C# code you linked to:

>>> FindWindow = ctypes.windll.user32.FindWindowW
>>> FindWindow.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR]
>>> FindWindow.restype = wintypes.HWND
>>> FindWindow('Shell_TrayWnd', '')
65670L

Upvotes: 2

Related Questions