• Home
  • Blog
  • Demos
  • About
  • ------------------
  • Articles
  • Csharp(59)
    • controls (4)
    • methods (5)
    • tutorials (50)
  • Html(1)
    • tutorials (1)
  • Java(10)
    • mobile (10)
  • Javascript(5)
    • tutorials (5)
  • Linux(3)
    • tutorial (3)
  • Math(10)
    • tutorials (10)
  • Php(15)
    • functions (1)
    • mysql (6)
    • tutorials (8)
  • Sql(23)
    • tutorials (23)
  • Vba(1)
    • tutorials (1)

How to use the MouseEventArg e

Written: 2010-02-05 06:55:54
Mood: Stupid
Subject: programming
Right,

I felt that I should write this down, so here goes:

When using a winform you often come into contact with EventArgs, often by using a control, it might look something like this:

private void txtMain_MouseClick(object sender, MouseEventArgs e)
{
}


I felt that I should try to use the MouseEventArgs object so I looked up what I could do with it. It turns out, alot.

The MouseEventArg object holds some very cool properties such as what button was pushed and when.

If you check the 'e'.object you can see what it offers:

Looking at our MouseEventArg object

There are some quite useful properties here such as the Button property that will tell us what button was presser, or the Location property that will tell us exactly where it was pressed (the X and Y property does the same).

We can make a small application using the MouseEventArg to display some information about our users mouse:

using System;
using System.Windows.Forms;

namespace MouseApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void txtMain_MouseClick(object sender, MouseEventArgs e)
{
string whatButton = "";
string location = "";
string x = "";
string y = "";

switch (e.Button)
{
case MouseButtons.Left:
whatButton = "left";
break;

case MouseButtons.Right:
whatButton = "right";
break;

case MouseButtons.Middle:
whatButton = "middle";
break;
}

location = e.Location.ToString();
x = e.X.ToString();
y = e.Y.ToString();

txtMain.Clear();
txtMain.Text += "You pressed the " + whatButton + " button" + Environment.NewLine;
txtMain.Text += Environment.NewLine;
txtMain.Text += "Location: " + location + Environment.NewLine;
txtMain.Text += Environment.NewLine;
txtMain.Text += "X: " + x + Environment.NewLine;
txtMain.Text += "Y: " + y;

}

}
}


Using the MouseEventArg we can first check what button was pushed. We switch the Button property to get what button was pushed and save it in string form.

Then we make a check for where the mouse was hovering during the click event. We do it with both the Location property and the X and Y properties.

The outcome is a little application that looks like this:

An application displaying the MouseEventArg event