Windows Application - SPLessons

Win App Mouse Events

Home > Lesson > Chapter 24
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Win App Mouse Events

Windows Application Mouse Events

shape Description

If one want to know the location of the mouse and whether the button is clicked or not, then should be familiar with Mouse Events. Mouse Events are used to know the details of the mouse. When the user interacts with the system through mouse, then the mouse events are raised. Each mouse event requires an object called sender and MouseEventArgs as arguments.

shape Steps

To see the mouse events follow the below steps.

shape Step 1

Create new windows application. Click on the form1 which is the default one. Then, properties of the form will be displayed in the properties window. Click on the Events Symbol as shown in the below figure. Then, that's going to bring the events window.

shape Step 2

See the Mouse events as shown in the above figure. Now, click on the white space beside the MouseDown, MouseUp and MouseMove events to raise the events. Then, the properties window will looks as shown in the below figure.

shape Step 3

Form1.cs will get the events and the code generates as shown in the below. [csharp] private void Form1_MouseDown(object sender, MouseEventArgs e) { } private void Form1_MouseUp(object sender, MouseEventArgs e) { } private void Form1_MouseMove(object sender, MouseEventArgs e) { } [/csharp]

shape Step 4

Now, write the code as shown in below. [csharp] using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication26 { public partial class Form1 : Form { Boolean draw; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void Form1_MouseDown(object sender, MouseEventArgs e) { draw = true; } private void Form1_MouseMove(object sender, MouseEventArgs e) { if(draw==true) { using(Graphics paint=CreateGraphics()) { paint.FillRectangle(new SolidBrush(Color.Blue),e.X,e.Y,4,4); } } else { using (Graphics paint = CreateGraphics()) { paint.FillEllipse(new SolidBrush(Color.Blue), e.X, e.Y, 4, 4); } } } private void Form1_MouseUp(object sender, MouseEventArgs e) { draw = false; } } } [/csharp]

shape Step 5

Press f5 to run the application. If one move the mouse, then it will draw as shown in the below figure. Here MouseUp event is raised.

shape Step 6

If one click on the mouse and move the mouse. Then it will draw as shown in the below figure. Here MouseDown event is raised.