【问题标题】:Convert C# P/Invoke code to Python ctypes?将 C# P/Invoke 代码转换为 Python ctypes?
【发布时间】:2012-11-09 01:29:15
【问题描述】:

我在使用 ctypes 将此 C# 代码转换为 python 时遇到问题。此代码用于隐藏 Windows 7 启动球。这是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);

我必须定义

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

还是直接使用?抱歉,我是使用 python ctypes 的新手。

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

【问题讨论】:

  • 您是否考虑过使用IronPython,它可以更方便地访问.NET 框架?

标签: python windows-7 ctypes


【解决方案1】:

看到您看到的错误消息会很有帮助。但是,这几乎可以肯定是因为您需要使用user32.FindWindowExW(或user32.FindWindowExA,如果您真的想要ASCII,非Unicode 版本)而不是直接使用FindWindowEx。您还需要为所有四个参数指定 argtypes。

这是来自docs 的原型:

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

那么这个呢?

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

您还可以按照您链接到的 C# 代码执行 FindWindow(而不是 FindWindowEx):

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

【讨论】:

  • 另请注意:是的,除非它是一个仅采用 int 的函数,否则您需要像这样显式定义 restype/argtypes。否则它将无法在具有指针类型的 32 位和 64 位代码之间正常工作。另请参阅my post about this here
  • 感谢@Ben Hoyt 提供示例代码。但是我怎样才能让 FindWindowEx 接受 (IntPtr)0xC017?将使用哪些 wintypes 或 ctypes?
  • 哦,我明白了:FindWindowEx() 对第三个参数有一个非常奇怪的双重用途——它可以是字符串或 int。我猜在这种情况下你会使用ctypes.cast(0xC017, wintypes.LPCWSTR)。如果您经常将它与整数一起使用,请使用大小正确的整数而不是 LPCWSTR 来定义 argtype。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-06
  • 2014-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多