Live Chat Icon For mobile
Live Chat Icon

How can I determine if a mouse button is pressed and moving over my form

Platform: WinForms| Category: Mouse Handling

Catch the form’s MouseMove event which is called when the mouse moves over the form. To determine if a button is pressed during the move, check the event arg’s Button property. The code below draw’s a line on the form as the mouse moves over it. The line is red when the left button is pressed, white when the right button is pressed and blue when no button is pressed.

private Point _point = new Point(-1, -1);
....
private void InitializeComponent()
{
	// 
	// Form1
	// 
	this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
	this.ClientSize = new System.Drawing.Size(292, 273);
	this.Name = 'Form1';
	this.Text = 'Form1';
	this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseMove);
}
....
private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
	if(_point.X	== -1)
		_point = new Point(e.X, e.Y);

	Color c;
	if(e.Button == MouseButtons.Left)
		c = Color.Red;
	else if(e.Button == MouseButtons.Right)
		c = Color.White;
	else if(e.Button == MouseButtons.None)
		c = Color.Blue;
	else
		c = this.BackColor;

	Point p = new Point(e.X,e.Y);
	Graphics g = Graphics.FromHwnd(this.Handle);
	Pen pen = new Pen(c,1);
	g.DrawLine(pen,_point,p);
	_point = p;
	pen.Dispose();
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.