How to detect mouse clicks without listening to any mouse events defined in framework controls?

谁说胖子不能爱 提交于 2019-12-23 17:17:48

问题


Is it possible to detect mouse clicks without listening to any mouse events defined in framework controls?

I mean, I don't want to write code like :

  control.MouseLeftButtonDown += this.HandleMouseLeftButtonDown;

Yet I want to know if user clicks on the screen or not. Is it possible in C# (WPF or Silverlight)?


回答1:


You can register a class handler in a static constructor you your main window, for example:

static MainWindow() {
    EventManager.RegisterClassHandler(typeof (MainWindow),
                                      Mouse.MouseDownEvent,
                                      new MouseButtonEventHandler(OnGlobaMouseDown));
}

It will be a global handler for all MouseDown events.




回答2:


You could use the Win32 API and detect the mouse message WM_MOUSE, something like this:

http://support.microsoft.com/kb/318804

or this example, showing use of the global mouse message WM_MOUSE_LL:

http://www.codeproject.com/KB/cs/globalhook.aspx




回答3:


This is done by capturing the mouse. Which forces any mouse event to be directed to you, even if it moves outside of the window. Mouse.Capture() method.




回答4:


If you need to handle mouse events of all your application, the best way is to subscribe to InputManager events.




回答5:


"I mean, I don't want to write code like :

control.MouseLeftButtonDown += this.HandleMouseLeftButtonDown;"

You could always use:

if (Mouse.LeftButton == MouseButtonState.Pressed)
{
     ...
}

You will need to include this though.

using System.Windows.Input;

This works for me in wpf.



来源:https://stackoverflow.com/questions/4861433/how-to-detect-mouse-clicks-without-listening-to-any-mouse-events-defined-in-fram

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!