问题
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