从另一个应用程序获取Button句柄

时间:2010-09-23 01:10:28

标签: c# winapi sendmessage

我有一个程序需要将BM_CLICK消息发送到另一个应用程序按钮。 我可以获得父窗口句柄但是当我尝试获取按钮句柄时如果总是返回0

我从Spy ++获得了按钮标题名称和按钮类型似乎没错,但我知道我一定有错。下面是我的代码

 public const Int BM_CLICK = 0x00F5;

 [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SendMessage(IntPtr hwnd, uint Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);



private void button1_Click(object sender, EventArgs e)
{
    Process[] processes = Process.GetProcessesByName("QSXer");

    foreach (Process p in processes)
    {
        ////the Button's Caption is "Send" and it is a "Button".  
        IntPtr ButtonHandle = FindWindowEx(p.MainWindowHandle, IntPtr.Zero, "Button", "Send");
       //ButtonHandle is always zero thats where I think the problem is 
    SendMessage(ButtonHandle, BM_CLICK, IntPtr.Zero, IntPtr.Zero);

    }

}

间谍屏幕截图

alt text

4 个答案:

答案 0 :(得分:5)

尝试为窗口文本传递null,而是尝试查找任何按钮:

IntPtr ButtonHandle = FindWindowEx(p.MainWindowHandle, IntPtr.Zero, "Button", null);

之后你可以使用第二个参数和一个新的调用来让下一个按钮处理几次。

您还可以尝试检查Marshal.GetLastWin32Error以查看错误结果是什么吗?

答案 1 :(得分:2)

试试这个:

IntPtr ButtonHandle = FindWindowEx(p.MainWindowHandle, IntPtr.Zero, null, "Send");

答案 2 :(得分:1)

你可以这样做:

//Program finds a window and looks for button in window and clicks it

HWND buttonHandle = 0;

BOOL CALLBACK GetButtonHandle(HWND handle, LPARAM)
{
    char label[100];
    int size = GetWindowTextA(handle, label, sizeof(label));
    if (strcmp(label, "Send") == 0) // your button name
    {
        buttonHandle = handle;
        cout << "button id is: " << handle << endl;
        return false;
    }
    return true;
}

int main()

{
    HWND windowHandle = FindWindowA(NULL, "**Your Window Name**");

    if (windowHandle == NULL)
    {
        cout << "app isn't open." << endl;
    }

    else
    {
        cout << "app is open :) " << endl;
        cout << "ID is: " << windowHandle << endl;
        SetForegroundWindow(windowHandle);
        BOOL ret = EnumChildWindows(windowHandle, GetButtonHandle, 0); //find the button
        cout << buttonHandle << endl;
        if (buttonHandle != 0)
        {
            LRESULT res = SendMessage(buttonHandle, BM_CLICK, 0, 0);
        }
    }
}

这应该可以解决问题。

答案 3 :(得分:0)

尝试将项目构建为x86。我尝试成功了!