我试图理解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();
}


很简单,我只想单击calc按钮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# - C#SendMessage单击按钮,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24724582/

10-11 02:14
查看更多