Click here to Skip to main content
15,119,514 members
Articles / Programming Languages / C#
Article
Posted 2 Jun 2005

Stats

159K views
3.2K downloads
59 bookmarked

Mouse Events

Rate me:
Please Sign up or sign in to vote.
4.66/5 (21 votes)
2 Jun 20052 min read
A helper class to expand on the mouse events provided by the Control class.

Sample Image - mouseEventDemo.png

Introduction

I was recently implementing some right-click functionality for a TreeView, and I got to thinking, how many times have I handled the MouseUp event and tested for Buttons.Right because there isn't a RightClick event in the Control class? So I've written a mouse event helper class that lets you connect directly to these specific events:

C#
public event EventHandler LeftClick;
public event EventHandler LeftDoubleClick;
public event EventHandler MiddleDoubleClick;
public event EventHandler RightDoubleClick;
public event EventHandler MiddleClick;
public event EventHandler RightClick;
public event MouseEventHandler LeftMouseDown;
public event MouseEventHandler LeftMouseUp;
public event MouseEventHandler MiddleMouseDown;
public event MouseEventHandler MiddleMouseUp;
public event MouseEventHandler RightMouseDown;
public event MouseEventHandler RightMouseUp;
public event MouseEventHandler WheelForward;
public event MouseEventHandler WheelBackward;

Implementation

The implementation is trivial. The MouseHelper class hooks the following control events:

C#
protected virtual void Initialize()
{
  control.Click+=new EventHandler(OnClick);
  control.DoubleClick+=new EventHandler(OnDoubleClick);
  control.MouseDown+=new MouseEventHandler(OnMouseDown);
  control.MouseUp+=new MouseEventHandler(OnMouseUp);
  control.MouseWheel+=new MouseEventHandler(OnMouseWheel);
}

A typical handler looks like this:

C#
private void OnClick(object sender, EventArgs e)
{
  switch(lastButton)
  {
    case MouseButtons.Left:
      if (LeftClick != null)
      {
        LeftClick(sender, e);
      }
      break;

    case MouseButtons.Middle:
      if (MiddleClick != null)
      {
        MiddleClick(sender, e);
      }
      break;

    case MouseButtons.Right:
      if (RightClick != null)
      {
        RightClick(sender, e);
      }
      break;
  }
}

You will note that this isn't intended to handle situations where more than one mouse button is being held down at a time.

Wheel Movement

One thing that's odd is that, for wheel movement, the documentation says that:

A positive value indicates that the wheel was rotated forward, away from the user; a negative value indicates that the wheel was rotated backward, towards the user.

However, if I push the wheel away from me, what I think would mean forward, the program actually says I'm moving the wheel backwards.

Usage

To use the MouseHelper class:

  • Instantiate the class and pass into the constructor the control for which you wish to trap mouse events.
  • Assign the control to the MouseHelper's Control property.
  • Use the MouseHelper's AddControl method.

You can add more than one control to the same mouse helper, which lets you combine mouse events from different controls into a single handler.

You should note that in the typical usage, you would use a unique MouseHelper instance for every Control class that you need to capture mouse events for. This is a drawback, but I wanted to keep the class simple. An alternative would be to have a static factory method that returns a MouseHandler instance for the specific control you want to extend. And possibly, an even more interesting implementation would be to have MouseHandler implement IExtenderProvider. Those may be future additions.

Conclusion

That's it! It's really simple, and now I have a helper class that takes care of the drudgery of writing over and over again the same "is the right button clicked" code. And my other motivation for writing this is because there was no way to handle right clicks declaratively. For example, I'd like to do something like this:

XML
<TreeView RightClick="PopupMenu"/>

without writing a custom handler. Now I can!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Marc Clifton
Architect Interacx
United States United States
Blog: https://marcclifton.wordpress.com/
Home Page: http://www.marcclifton.com
Research: http://www.higherorderprogramming.com/
GitHub: https://github.com/cliftonm

All my life I have been passionate about architecture / software design, as this is the cornerstone to a maintainable and extensible application. As such, I have enjoyed exploring some crazy ideas and discovering that they are not so crazy after all. I also love writing about my ideas and seeing the community response. As a consultant, I've enjoyed working in a wide range of industries such as aerospace, boatyard management, remote sensing, emergency services / data management, and casino operations. I've done a variety of pro-bono work non-profit organizations related to nature conservancy, drug recovery and women's health.

Comments and Discussions

 
Generalapp to record Test case and record mouse movement and keyboard clicks Pin
Member 117448536-Jun-15 21:31
MemberMember 117448536-Jun-15 21:31 
GeneralMy vote of 4 Pin
Arash3agel24-Sep-11 22:19
MemberArash3agel24-Sep-11 22:19 
GeneralMy vote of 5 Pin
Just_Michel27-Mar-11 21:41
MemberJust_Michel27-Mar-11 21:41 
GeneralVery nice... and brief usage note. Pin
dsuilmann6-Oct-09 9:37
Memberdsuilmann6-Oct-09 9:37 
GeneralGreat article! I am going to bookmark it. Pin
DrABELL16-Sep-09 16:39
professionalDrABELL16-Sep-09 16:39 
QuestionMouseHelper for Web.UI.Forms Pin
alvarog0123-Feb-09 22:17
Memberalvarog0123-Feb-09 22:17 
GeneralMe too! Pin
PIEBALDconsult13-Jun-08 16:24
professionalPIEBALDconsult13-Jun-08 16:24 
QuestionIs there has MouseMoveStop? Pin
Andy Lang12-Jul-07 5:26
MemberAndy Lang12-Jul-07 5:26 
QuestionWheel click ? Pin
Christian Graus28-Sep-06 0:21
protectorChristian Graus28-Sep-06 0:21 
AnswerRe: Wheel click ? Pin
Marc Clifton28-Sep-06 2:00
mvaMarc Clifton28-Sep-06 2:00 
GeneralRe: Wheel click ? Pin
Christian Graus28-Sep-06 2:10
protectorChristian Graus28-Sep-06 2:10 
Questionproblem with listview columnheader Pin
rm_pkt17-Jan-06 20:19
Memberrm_pkt17-Jan-06 20:19 
QuestionMultiple Controls to same MouseHelper? Pin
Doncp8-Dec-05 11:27
MemberDoncp8-Dec-05 11:27 
AnswerRe: Multiple Controls to same MouseHelper? Pin
Marc Clifton8-Dec-05 12:14
mvaMarc Clifton8-Dec-05 12:14 
QuestionListBox not supported? Pin
Doncp7-Dec-05 11:38
MemberDoncp7-Dec-05 11:38 
AnswerRe: ListBox not supported? Pin
Marc Clifton7-Dec-05 12:49
mvaMarc Clifton7-Dec-05 12:49 
GeneralRe: ListBox not supported? Pin
Doncp8-Dec-05 5:48
MemberDoncp8-Dec-05 5:48 
GeneralRe: ListBox not supported? Pin
Marc Clifton8-Dec-05 5:56
mvaMarc Clifton8-Dec-05 5:56 
Generalpersonally... Pin
Almighty Bob21-Jun-05 5:24
MemberAlmighty Bob21-Jun-05 5:24 
GeneralSuggestion Pin
Maximilian Hänel6-Jun-05 23:59
MemberMaximilian Hänel6-Jun-05 23:59 
Hi Marc,

I suggest that the control instance should be either passed in the Ctor of MouseHelper (and making the MouseHelper.Control property readonly) or the Control property should be modified to something like that:
public Control Control
{
	get {return control;}
	set
	{
		if(value==control)
			return;

		if(null!=control)
			Terminate();

		control=value;

		if(null!=control)
			Initialize();
	}
}
protected virtual void Terminate()
{
	control.Click-=new EventHandler(OnClick);
	control.DoubleClick-=new EventHandler(OnDoubleClick);
	control.MouseDown-=new MouseEventHandler(OnMouseDown);
	control.MouseUp-=new MouseEventHandler(OnMouseUp);
	control.MouseWheel-=new MouseEventHandler(OnMouseWheel);
}


"All languages allow you to write crap code, VB just makes it easier (IMO)."
Michael P Butler

GeneralAnother Great Article Pin
SHaroz3-Jun-05 18:41
MemberSHaroz3-Jun-05 18:41 
GeneralGreat idea! Pin
Robert Rohde2-Jun-05 12:52
MemberRobert Rohde2-Jun-05 12:52 
GeneralRe: Great idea! Pin
Marc Clifton2-Jun-05 13:08
mvaMarc Clifton2-Jun-05 13:08 
GeneralThe file is missing. Pin
yuren19782-Jun-05 10:49
Memberyuren19782-Jun-05 10:49 
GeneralRe: The file is missing. Pin
Marc Clifton2-Jun-05 11:29
mvaMarc Clifton2-Jun-05 11:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.