Lun*_*ore 5 c# crash winapi automation
我正在编写一个C#自动化工具.
由于Microsoft UI Automation不提供任何模拟右键单击或提升上下文菜单的方法,我正在使用SendMessage此方法.我宁愿不使用,SendInput因为我不想抓住焦点.
SendMessage但是,当我打电话时,它会崩溃目标应用程序.
这是我的代码:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
public void RightClick<T>(T element) where T: AutomationElementWrapper
{
const int MOUSEEVENTF_RIGHTDOWN = 0x0008; /* right button down */
const int MOUSEEVENTF_RIGHTUP = 0x0010; /* right button up */
var point = element.Element.GetClickablePoint();
var processId = element.Element.GetCurrentPropertyValue(AutomationElement.ProcessIdProperty);
var window = AutomationElement.RootElement.FindFirst(
TreeScope.Children,
new PropertyCondition(AutomationElement.ProcessIdProperty,
processId));
var handle = window.Current.NativeWindowHandle;
var x = point.X;
var y = point.Y;
var value = ((int)x)<<16 + (int)y;
SendMessage(new IntPtr(handle), MOUSEEVENTF_RIGHTDOWN, IntPtr.Zero, new IntPtr(value));
SendMessage(new IntPtr(handle), MOUSEEVENTF_RIGHTUP, IntPtr.Zero, new IntPtr(value));
}
Run Code Online (Sandbox Code Playgroud)
知道我做错了什么吗?
你混淆了你的类型。您正在使用SendMessage,它接受一个窗口消息(按照惯例,其名称为WM_...),但您向它传递了一个MOUSEINPUT.dwFlags专用值SendInput(其名称为MOUSEEVENTF_...)。你基本上是在胡言乱语。
您的代码实际上所做的是发送一条数值为 8 的窗口消息(在窗口消息中,这意味着WM_KILLFOCUS),然后发送一条 0x10 == 16 ( WM_CLOSE) 的窗口消息。后者可能会给你带来问题——你告诉窗口关闭。我不确定为什么它会崩溃,但它肯定会退出。
如果您使用的是SendMessage,则需要向其传递窗口消息(WM_例如WM_RBUTTONDOWN和WM_RBUTTONUP)。