我在使用 pywin32
扩展的 FindWindow
上遇到了麻烦。
简单的 C 代码:
int main()
{
HWND h = FindWindow(NULL, TEXT("SomeApp"));
if (h != INVALID_HANDLE_VALUE)
SetForegroundWindow(h);
return 0;
}
效果很好。与 python 相同:
import win32gui
h = win32gui.FindWindow(None, "SomeApp")
if h:
win32gui.SetForegroundWindow(h)
else:
print "SomeApp not found"
失败,未找到 SomeApp。我建议文本编码可能会在这里引起麻烦,但在文档中找不到任何有关如何指定文本的信息。
更新: 我在其他机器上测试过代码,没有发现任何问题。所以,我的第一台机器上的配置应该是不正确的。如果发现问题,我会更新我的调查结果。
最佳答案
在 C 代码中,您正在检查 h != INVALID_HANDLE_VALUE
,在 Python 中检查 h != None
。 INVALID_HANDLE_VALUE
不是 0
/null
/None
。
Python 通过 win32file
导入定义 win32file.INVALID_HANDLE_VALUE
。
此外,除了打印“SomeApp not found”之外,您还可以执行以下操作:
gle = win32api.GetLastError()
err = win32api.FormatMessage(gle)[:-2]
print 'SomeApp not found: LastError=%d - %s' % (gle, err)
如果 FindWindow
由于某种原因合理地失败(或者“成功”,如果有效),这应该为您提供有关失败的更多详细信息。
关于python - 查找窗口失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12857300/