gpt4 book ai didi

C# SendMessage 点击按钮

转载 作者:行者123 更新时间:2023-11-30 22:04:56 26 4
gpt4 key购买 nike

我试图理解 SendMessage 函数,这是我的实际代码:

[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

[DllImport("user32.dll")]
private static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);

static void Main(string[] args)
{
Process test = Process.GetProcessesByName("calc")[0];
IntPtr hwndChild = FindWindowEx(test.MainWindowHandle, IntPtr.Zero, "Button", "2");
SendMessage(hwndChild, 245, IntPtr.Zero, IntPtr.Zero);
Console.ReadKey();
}

很简单,我只想点击计算按钮 2,但我没有成功。

最佳答案

当您调用 winapi 函数时,错误检查绝不是可选的。它是一个 C api,它不会抛出异常来让您远离麻烦。你必须自己做。正确的代码如下所示:

    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter,
string className, string windowTitle);

...
IntPtr hwndChild = FindWindowEx(test.MainWindowHandle, IntPtr.Zero, "Button", "2");
if (hwndChild == IntPtr.Zero) throw new System.ComponentModel.Win32Exception();

现在您知道为什么您的程序无法运行了。接下来您要做的是启动 Spy++ 实用程序并查看计算器窗口。您会发现您必须进行更多 FindWindowEx() 调用才能深入到嵌套按钮。

请考虑使用 UI 自动化库来执行此操作。

关于C# SendMessage 点击按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24724582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com