Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

Mouse coordinates

Getting the coordinates of the mouse with OnMouseMove and making something interesting with them.

On Friday, June 4th 2004 at 10:25 AM
By Andrew Pociu (View Profile)
****-   (Rated 4 with 29 votes)
Contextual Ads
More C# Resources
Advertisement

The position of the mouse cursor on the screen is determined by the X and Y coordinates.
In C#, X and Y are the properties of MouseEventArgs. X is the horizontal position of the cursor relative to the client area (the form usually), and Y is the vertical position.

This means we can easily get the mouse pointer coordinates on a form by using these properties and overriding the OnMouseMove method:


protected override void OnMouseMove(MouseEventArgs mouseEv)
{
    txtMouseX.Text = mouseEv.X.ToString();
    txtMouseY.Text = mouseEv.Y.ToString();
}



Use the above code with a form with two textboxes.

OK, let's do something more interesting than some textBoxes displaying mouse coordinates.

Start a new 'Windows Application' project. Change the background color of the form to white.
At the beginning of the public class declare two int variables, xMouse and yMouse and set them to 0:


int xMouse = 0;
int yMouse = 0;



Again, we'll use OnMouseMove:


protected override void OnMouseMove(MouseEventArgs mouseEv)
{
    // Create new graphics object
    Graphics gfx = CreateGraphics();
    // Create a pen that has the same background color as the form
    Pen erasePen = new Pen(Color.White);
    // Draw a line that will erase the previous line created
    gfx.DrawLine(erasePen, 0, 0, xMouse, yMouse);
    // Create a pen that will draw the blue line
    Pen linePen = new Pen(Color.Blue);
    // Store the X coordinate
    xMouse = mouseEv.X;
    // Store the Y coordinate
    yMouse = mouseEv.Y;
    // Actually draw the blue line
    gfx.DrawLine(linePen, 0, 0, xMouse, yMouse);
}



The result is a line starting from the top left corner of the form and ending at the mouse pointer position, following him every time.



The code is simple, but we need to use a little trick to erase the previous line created.
This is why we create a pen that has the same background color as the form.
When we create the blue line, we use the coordinates stored in the variables xMouse and yMouse.
After the blue line is created and the mouse continues to move, the OnMouseMove event fires again.
First it makes a new white line in the same exact position of the previous blue line because it uses the old variables.
Then it updates the variables with the new coordinates and creates a new blue line.

If we don't make a new white line over the previous blue one, the result will be similar to this:



To see it for yourself just comment the following line:


gfx.DrawLine(erasePen, 0, 0, xMouse, yMouse);
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by swati on Wednesday, February 2nd 2005 at 06:42 AM

ok
but this will work only in case of normal mouse cursor. what if i want the blue line to be drawn even if my mouse cursor is something else e.g a cross.
then it will not work

by Steve on Wednesday, April 20th 2005 at 08:33 PM

how do you get mouse cursor coordinates when mouse not on form ?

by Steve on Wednesday, April 20th 2005 at 08:34 PM

how do you get mouse cursor coordinates when mouse not on form ?

by Steve on Wednesday, April 20th 2005 at 08:40 PM

how do you get mouse cursor coordinates when mouse not on form ?

by Pieter on Sunday, July 31st 2005 at 05:45 AM

This is a nice article, but it doesn't mention what to do when the form's background is not white, but is a picture or a gradient. It gets much more difficult in that condition.

by joey on Wednesday, October 5th 2005 at 09:22 PM

hi..im lookin for a script that can capture my mouse Coordinates if i hover my mouse to an IMAGE ONLY within my page. Tnx!!!

by Andrei Pociu on Tuesday, October 18th 2005 at 05:05 PM

I made a new tutorial that shows you how to get the mouse cursor coordinates on the screen, and not just on the form. It uses the Windows API:

http://www.geekpedia.com/tutorial146_Get-screen-cursor-coordinates.html.

by da on Friday, June 15th 2007 at 11:00 AM

da

by Brian on Tuesday, August 21st 2007 at 02:00 PM

This is heavily flawed, just assuming the background is white is bad. You need to figure out how to redraw a portion of the screen (not the whole screen) of where the line used to be.

by Casper on Sunday, March 23rd 2008 at 09:37 PM

Just wanted to thank you

I have been looking for a script that reads the form cords and not the windows cords

thank you

by Pavan on Monday, September 1st 2008 at 04:26 AM

i m new to c#..so i don't get what u have written...so plz explain it more from begining..

thanx.

by tcatu on Saturday, December 13th 2008 at 08:28 AM

thnx

by jatinder on Wednesday, January 7th 2009 at 04:13 AM

I have a form and i have a groupbox on the form.I need to calculate the mouse cordinates when the mouse is inside the groupbox.How to do this.Please help.Thanks

by Hemant on Wednesday, March 25th 2009 at 02:20 AM

how do you get mouse cursor coordinates when mouse not on form ?

by Yousuf on Tuesday, June 30th 2009 at 07:06 AM

haha nice .. but now the erased Lines will act as a Eraser to previously drawn Shapes .. this is not a flawless code ... i have made an error free code for line drawing feature of PaintBrush ... see this



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;

namespace tryMapping2
{




public partial class Form1 : Form
{
public Pen p = new Pen(Color.Black);
public bool drawLine = false;
Point startPoint;
bool isDrawing = false;
Point endPoint;
int eraseX;
int eraseY;
Graphics gr;
List lStartPoints;
List lEndPoints;

public Form1()
{
InitializeComponent();
this.MouseMove = new MouseEventHandler(Form1_MouseMove);
this.MouseDown =new MouseEventHandler(Form1_MouseDown);
this.Paint = new PaintEventHandler(Form1_Paint);
timer1.Tick = new EventHandler(timer1_Tick);
panel.MouseEnter = new EventHandler(panel_MouseEnter);
button1.MouseEnter = new EventHandler(button1_MouseEnter);
button2.MouseEnter = new EventHandler(button2_MouseEnter);
this.MouseEnter = new EventHandler(Form1_MouseEnter);
}

void Form1_MouseEnter(object sender, EventArgs e)
{
if (drawLine)
{
Cursor = Cursors.Cross;
}
}






void button2_MouseEnter(object sender, EventArgs e)
{
this.Cursor = Cursors.Arrow;
}

void button1_MouseEnter(object sender, EventArgs e)
{
this.Cursor = Cursors.Arrow;
}

void panel_MouseEnter(object sender, EventArgs e)
{
this.Cursor = Cursors.Arrow;
}

void timer1_Tick(object sender, EventArgs e)
{
RefreshLines(gr);
}


public class Line
{
public void drawLine(Pen p, Graphics g, Point start, Point end)
{
Form1 form1 = new Form1();
g.DrawLine(form1.p, start, end);
}
}





void Form1_Paint(object sender, PaintEventArgs e)
{
RefreshLines(gr);
}

private void Form1_Load(object sender, EventArgs e)
{

lStartPoints = new List();
lEndPoints = new List();
gr = CreateGraphics();
timer1.Interval = 1;
}

void Form1_MouseDown(object sender, MouseEventArgs e)
{

if (drawLine)
{
isDrawing = true;
startPoint = new Point(e.X,e.Y);
lStartPoints.Add(startPoint);

eraseX = startPoint.X;
eraseY = startPoint.Y;
this.MouseUp = new MouseEventHandler(Form1_MouseUp);
timer1.Start();

}
}

void Form1_MouseUp(object sender, MouseEventArgs e)
{

this.MouseUp -= Form1_MouseUp;
isDrawing = false;
lEndPoints.Add(endPoint);
timer1.Stop();
RefreshLines(gr);

}


void Form1_MouseMove(object sender, MouseEventArgs e)
{
label1.Text = e.X " , " e.Y;


if (drawLine

by hsm on Tuesday, March 23rd 2010 at 07:54 PM

great

by ghjhgj on Monday, August 2nd 2010 at 09:44 AM

bakwas

by Thangaraj on Tuesday, November 23rd 2010 at 06:34 AM

Nice coding..!

by H3LTer Sk3LTer on Saturday, February 5th 2011 at 09:16 PM

Great ideas, got to say I've based most of my code off of this thread. I have a rather complex program that uses many lines that must be redrawn many times a second. Unfortunately it seems to make the screen blink as the lines are erased and redrawn in their new locations. I feel like this method is somehow inefficient, is there a faster way for the computer to erase all the draw lines at once instead of having to recompute each line and erase separately? My idea was to have the panel repainted before drawing the new set of lines. How can this be done?

Any help is appreciated.

cheers

by blood pressure control on Saturday, August 13th 2011 at 06:58 AM

Smooth I definitely liked naming it. This info provided by you is rale manufacture for prudish cerebration.
blood pressure control

by blood pressure control on Saturday, August 13th 2011 at 06:58 AM

Smooth I definitely liked naming it. This info provided by you is rale manufacture for prudish cerebration.
blood pressure control

by bathroom design ideas on Sunday, August 14th 2011 at 05:05 AM

You got a rale primal diary I piss been here mensuration for nearly an stop. I am a newbie and your success is rattling superabundance an breather for me

by love music on Monday, August 15th 2011 at 04:47 AM

Great ideas, got to say I've based most of my code off of this thread. I have a rather complex program that uses many lines that must be redrawn many times a second. Unfortunately it seems to make the screen blink as the lines are erased and redrawn in their new locations. I feel like this method is somehow inefficient, is there a faster way for the computer to erase all the draw lines at once instead of having to recompute each line and erase separately? My idea was to have the panel repainted before drawing the new set of lines. How can this be done?

by heartburn on Friday, August 19th 2011 at 08:38 PM


What a wonderful leather of assemblage Admiring the denotive and reflection you put into your writing and elaborated gist you thing ! I treat symbol your diary and signal my children cloth up here oft. Thumbs up

by heartburn-symptoms on Saturday, August 20th 2011 at 03:19 AM


Pretty unliterary sum. I pianoforte stumbled upon your ledger and hot to say that I possess study enjoyed entity your aggregation posts. Any way I'll be subscribing to your cater and I draftsmanship you publicise again presently

by brother quotes on Thursday, October 6th 2011 at 11:41 AM

I conceptualize this is a distinct put. Thanks for attractive the trim to score specific an exemplifying article. It has assumption me a lot of inspiration.
brother quotes

by brother quotes on Thursday, October 6th 2011 at 01:07 PM

I do cerebrate the grouping are where lots of the fun was in. I respond to hit a indorsement await into my web log so you can thrown the entropy
brother quotes

by the offshore company on Saturday, October 8th 2011 at 01:55 AM

The reestablish is sing in ail a someone doings and it entails whatsoever utilizable assembling for me. I am paradisal to tap your soaring way of descriptor the habitation. Now you add it unproblematic for me to restate and get the aim. Leaving you for the touring.
the offshore company

by on Saturday, October 8th 2011 at 06:22 AM

Thanks for the unmatchable diary.it was rale useful for me.navigator sharing specified ideas in the instant as symptomless.this was actually what i was labour for,and i am voluntary to came here!

by Tim Newport on Saturday, December 3rd 2011 at 04:04 PM

My problem with this is i am using a child form so i can have many windows and the positions y value is not right. it is actually below the cursor at different lengths depending on the size of the window? any suggestions?

by magazine subscriptions to Australia on Monday, December 12th 2011 at 04:50 AM

thank u for providing me information on List View.
I want to know how i can display data in datalist in Newsletter layout and Thank you so much, this is easy to understand and fun to continue along with. I am a migrating VB.NET/C# Developer looking for an insight into VC .NET. I've found the VC tutorials on many sites to be confusing, and the navigation around the sites to be near impossible to use! Thanks once again.

by cheap cigarettes online on Wednesday, January 4th 2012 at 04:34 AM

Adore the new appear. I enjoyed this great article. Thanks for the great writing.

by Archibald on Monday, January 9th 2012 at 05:34 AM

Once you have recreated the problem and captured these steps, you can save them to a file and send it to your support person, who can then open it up and view

by casque beats by dre on Tuesday, March 6th 2012 at 11:26 PM

Ce site internet est sérieusement bonne, souhaitent déterminer beaucoup plus si merveilleux écriture jusqu'à

by IRan on Friday, November 16th 2012 at 07:47 AM

Good article :)

to be more interesting change
gfx.DrawLine(erasePen, 0, 0, xMouse, yMouse);
to:
gfx.DrawLine(erasePen,ClientRectangle.Width,ClientRectangle.Height, xMouse, yMouse);

by Albert on Saturday, December 8th 2012 at 08:33 AM

This Goa Gambling is providing the nice services in this blog that to using the amazing approach is visible on this blog. I really love this info in this blog that to utilize the Online Bingo Ball great services in this blog that too new things are adding the nice info is visible on this blog. I am really admired for the great technology is visible on this US Top Poker blog. Thanks a lot for the nice services in this blog and the nice approach in this blog.

by Margahayuland on Sunday, June 9th 2013 at 07:32 AM

This means we can easily get the mouse pointer coordinates on a form by using these properties and overriding the OnMouseMove method
http://sooboos.com/margahayuland/margahayuland-42-tahun-membangun-ruang-hidup.php
http://sooboos.com/situs-berita/penting-panas-perlu-dan-seruu.php
http://sooboos.com
http://wadahpromoindonesia.blogspot.com/2013/05/margahayuland-42-tahun-membangun.html
http://tech-kinodeon.blogspot.com/2013/02/agen-bola-ligabet88-promo-bonus-100.html
http://tech-kinodeon.blogspot.com/2013/04/penting-panas-perlu-dan-seruu.html
http://tech-kinodeon.blogspot.com/2013/05/korek-api-gas-fighter-indonesia.html


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Ads

From the creators of Geekpedia, a revolutionary new coupon website!

BargainEZ has coupons codes, printable coupons, bargains and it is the leading source of Passbook coupons for iPhone and iPod touch devices.

Coupons
Discover Geekpedia
Other Resources