【发布时间】:2019-07-27 14:37:00
【问题描述】:
我正在尝试关闭特定的MessageBox,如果它基于标题和文本显示。当MessageBox 没有图标时,我可以使用它。
IntPtr handle = FindWindowByCaption(IntPtr.Zero, "Caption");
if (handle == IntPtr.Zero)
return;
//Get the Text window handle
IntPtr txtHandle = FindWindowEx(handle, IntPtr.Zero, "Static", null);
int len = GetWindowTextLength(txtHandle);
//Get the text
StringBuilder sb = new StringBuilder(len + 1);
GetWindowText(txtHandle, sb, len + 1);
//close the messagebox
if (sb.ToString() == "Original message")
{
SendMessage(new HandleRef(null, handle), WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
当MessageBox 显示为没有图标时,上面的代码可以正常工作,如下所示。
MessageBox.Show("Original message", "Caption");
但是,如果它包含如下图标(来自MessageBoxIcon),则它不起作用; GetWindowTextLength 返回 0 并且没有任何反应。
MessageBox.Show("Original message", "Caption", MessageBoxButtons.OK, MessageBoxIcon.Information);
我最好的猜测是FindWindowEx 的第三和/或第四个参数需要更改,但我不确定要传递什么。或者也许第二个参数需要更改以跳过图标?我不太确定。
【问题讨论】:
-
如果您愿意尝试 UI 自动化,Automation.AddAutomationEventHandler 和 WindowPattern.WindowOpenedEvent 会在 MessageBox 以任何方式打开(或关闭)时通知您。
-
@Jimi 我还需要看看刚刚打开的
MessageBox是否是我正在寻找的那个。我不想关闭所有MessageBox。只是带有我正在寻找的消息的那个。为此,我似乎仍然需要使用 FindWindow。 -
UI 自动化在事件处理程序参数中返回引发事件的元素。
Element.Current对象具有识别 MessageBox 所需的所有属性。例如,在这种情况下,Element.Current.Name将是 "Caption" 。 -
@Jimi,但我怎样才能得到消息框的文本。 “标题”缩小了一些范围,但对于我的目的来说太笼统了。我需要检查消息的具体文本。这适用于我的代码,除非我在消息框中显示图标。
-
当事件处理程序返回引发事件的元素(您的消息框)时,您只需要找到具有您知道的属性的子元素。例如,要查找具有您在此处显示的文本 (
Original message) 的元素,则应为[Element].FindAll(TreeScope.Children, New PropertyCondition(AutomationElement.NameProperty, "Original message"));。如果返回的集合为空,则没有找到匹配的元素。不是你的 MessageBox。
标签: c# user32 findwindowex