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

8

我有一个需要向其他应用程序的按钮发送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个回答

6

尝试将窗口文本设置为null,而是查找任何按钮:

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

接下来,您可以使用第二个参数和新的调用几次以获取下一个按钮句柄。

同时,您能否尝试检查 Marshal.GetLastWin32Error 以查看错误结果是什么?


嗨,Brian,除非我误解了你的问题,否则我认为类名总是必须是一个字符串,不是吗? - Mike
嗨,布莱恩,好的,请试一下,但是还是没有反应 :-) - Mike
嗨,Brian,p.MainWindowHandle 是有效的。我是这样捕获应用程序标题的:button1.text = p.MainWindowTitle。是的,我尝试过 "&Send" 和 "Send" 两种方式。 - Mike
Marshal.GetLastWin32Error返回什么?另外,我已经更改了我的答案,请再尝试一下我建议的方法。 - Brian R. Bondy
我捕获了GetLastWin32Error,它显示为0。MessageBox.Show(Marshal.GetLastWin32Error().ToString()); - Mike

4

试试这个:

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

2
你可以像这样做:

你可以像这样做:

//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);
        }
    }
}

这应该可以解决问题。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接