拦截 WPF 应用程序的每一次鼠标点击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13232714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Intercept every mouse click to WPF application
提问by nmarler
I'm looking to intercept every mouse click in my WPF application. Seems this should be easy with the command routing mechanism, but sorry I'm not finding anything.
我希望在我的 WPF 应用程序中拦截每一次鼠标点击。使用命令路由机制似乎这应该很容易,但很抱歉我没有找到任何东西。
My application implements several security levels, and has the requirement to automatically revert to the most restrictive level if no one interacts with (clicks) the application in x minutes. My plan is to add a timer that expires after x minutes and adjusts the security level. Each mouse click into the application will reset the timer.
我的应用程序实现了多个安全级别,并且要求在 x 分钟内没有人与(单击)应用程序交互时自动恢复到最严格的级别。我的计划是添加一个在 x 分钟后到期的计时器并调整安全级别。每次鼠标点击应用程序都会重置计时器。
回答by Louis Kottmann
You can register a class handler:
您可以注册一个类处理程序:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
EventManager.RegisterClassHandler(typeof(Window), Window.PreviewMouseDownEvent, new MouseButtonEventHandler(OnPreviewMouseDown));
base.OnStartup(e);
}
static void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
Trace.WriteLine("Clicked!!");
}
}
This will handle any PreviewMouseDownevent on any Window created in the application.
这将处理PreviewMouseDown在应用程序中创建的任何窗口上的任何事件。
回答by Anders Arpi
<Window .... PreviewMouseDown="Window_PreviewMouseDown_1">
</Window>
This should work for you.
这应该对你有用。
This fires even if other MouseDownevents fire for components that it contains.
即使其他MouseDown事件为其包含的组件触发,这也会触发。
As per Clemens suggestion in the comments, PreviewMouseDownis a better choice than MouseDown, as that makes sure you can't stop the event bubbling from happening in a different event.
根据评论中的 Clemens 建议,PreviewMouseDown是比 更好的选择MouseDown,因为这可以确保您无法阻止事件冒泡发生在不同的事件中。
回答by Kir
You have a few options:
您有几个选择:
Low level mouse hook: http://filipandersson.multiply.com/journal/item/7?&show_interstitial=1&u=%2Fjournal%2Fitem
低级鼠标钩子:http: //filipandersson.multiply.com/journal/item/7?&show_interstitial=1&u=%2Fjournal%2Fitem
WPF Solution (I'd check to see if this does what you need first): WPF. Catch last window click anywhere
WPF 解决方案(我会先检查这是否满足您的需求): WPF。捕捉最后一个窗口点击任意位置

