问题描述
我正在写一个C#自动化工具。
I'm writing a C# automation tool.
由于微软UI自动化不提供模拟右键单击或提高上下文菜单的任何方式,我用 SendMessage函数
来做到这一点吧。我宁可不使用 SendInput
,因为我不想必须抓住重点。
Since Microsoft UI Automation doesn't provide any way of simulating right-clicks or raising context menus, I'm using SendMessage
to do this instead. I'd rather not use SendInput
because I don't want to have to grab focus.
当我称之为 SendMessage函数
,但是,它崩溃的目标应用程序。
When I call SendMessage
, however, it crashes the target app.
下面是我的code:
[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));
}
任何想法,我做错了吗?
Any idea what I'm doing wrong?
推荐答案
你的类型的混合起来。您使用 SendMessage函数
,这需要一个窗口消息(按照惯例被命名为 WM _
...),但你传递给它的意思为 SendInput
A MOUSEINPUT.dwFlags
值(被命名为 MOUSEEVENTF _
...)。你基本上是路过的乱码。
You're mixing up your types. You're using SendMessage
, which takes a window message (which by convention are named WM_
...), but you're passing it a MOUSEINPUT.dwFlags
value that's meant for SendInput
(which are named MOUSEEVENTF_
...). You're basically passing gibberish.
你的code实际上做的是发送的数值为8的窗口消息(在窗口消息,手段 WM_KILLFOCUS
),其次是一个窗口为0x10 == 16消息( WM_CLOSE
)。它是很可能导致您的问题是后者 - 你告诉窗口关闭。我不知道为什么它会崩溃,但肯定会退出。
What your code is actually doing is sending a window message whose numeric value is 8 (which, in window messages, means WM_KILLFOCUS
), followed by a window message of 0x10 == 16 (WM_CLOSE
). It's the latter that's likely causing you problems -- you're telling the window to close. I'm not sure why it would crash, but it would certainly exit.
如果你使用 SendMessage函数
,你需要将它传递窗口消息( WM _
,例如 WM_RBUTTONDOWN
和 WM_RBUTTONUP
)。
If you're using SendMessage
, you need to pass it window messages (WM_
, for example WM_RBUTTONDOWN
and WM_RBUTTONUP
).
这篇关于SendMessage函数来模拟右键单击崩溃的目标应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!