【问题标题】:Click on 'OK' button of message box using WINAPI in c#在c#中使用WINAPI单击消息框的“确定”按钮
【发布时间】:2013-02-19 16:12:47
【问题描述】:

我正在尝试使用 winapi 在 C# windows 窗体的消息框上单击“确定”按钮。下面是我正在处理的代码。

private const int WM_CLOSE = 16;
private const int BN_CLICKED = 245;

[DllImport("user32.dll", CharSet=CharSet.Auto)]
        public static extern int SendMessage(int hWnd, int msg, int wParam, IntPtr lParam);

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

//this works
hwnd = FindWindow(null, "Message");
if(hwnd!=0)
      SendMessage(hwnd, WM_CLOSE, 0, IntPtr.Zero);

//this doesn't work.
hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero, "Button", "ok");
SendMessage((int)hwndChild, BN_CLICKED, 0, IntPtr.Zero);

虽然我在hwndChild 中得到了一个值,但它无法识别BN_CLICKED。 我不确定我错过了什么。有什么帮助吗?

我正在尝试关闭另一个应用程序的消息框按钮,这就是我正在做的事情。但是,我仍然缺少一些东西。

IntPtr hwndChild = IntPtr.Zero;
hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero,' '"Button", "OK");
SendMessage((int)hwndChild, WM_COMMAND, (BN_CLICKED '<<16) | IDOK, hwndChild);

【问题讨论】:

  • 既然你使用的是C#,你也可以使用System.Windows.Automation命名空间。这是pushes the "7" button in Calculator 的示例。只需将“计算器”更改为“消息”,将“7”更改为“确定”即可。

标签: c# winapi messagebox


【解决方案1】:

BN_CLICKED 不是消息。您需要发送一条 WM_COMMAND 消息,其中包含BN_CLICKED 通知和wParam 中的按钮ID 和lParam 中的按钮句柄。

按钮的父窗口收到此通知码 通过 WM_COMMAND 消息。

private const uint WM_COMMAND = 0x0111;
private const int BN_CLICKED = 245;
private const int IDOK = 1;

[DllImport("user32.dll", CharSet=CharSet.Auto)]
        public static extern int SendMessage(IntPtr hWnd, uint msg, int wParam, IntPtr lParam);

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

SendMessage(hwndChild, WM_COMMAND, (BN_CLICKED << 16) | IDOK, hwndChild);

【讨论】:

  • 你能给我举个例子吗?我对此并不精通。以及 WM_CLOSE 如何与发送消息一起使用。
  • @Virus:因为WM_CLOSE 是一条消息,就像WM_COMMAND 一样。正如我所指出的,BN_CLICKED 不是消息。请看示例。
【解决方案2】:

Finallu,这对我有用。 第一次单击可能会激活窗口,第二次单击可能会单击按钮。

SendMessage(btnHandle, WM_LBUTTONDOWN, 0, 0);
SendMessage(btnHandle, WM_LBUTTONUP, 0, 0);
SendMessage(btnHandle, WM_LBUTTONDOWN, 0, 0);
SendMessage(btnHandle, WM_LBUTTONUP, 0, 0);

【讨论】:

  • 感谢我在单击对话框内的按钮时遇到问题。您单击两次的解决方案对我有所帮助。正如你所说的第一次点击激活窗口和第二次发送消息点击。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-10
  • 1970-01-01
相关资源
最近更新 更多