Get cursor position with respect to the control - C# - c#

I want to get the mouse position with respect to the control in which mouse pointer is present. That means when I place the cursor to the starting point (Top-Left corner) of control it should give (0,0). I am using the following code:
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
this.Text = Convert.ToString(Cursor.Position.X + ":" + Cursor.Position.Y);
}
But this gives the position with respect to the screen not to the control.
Code sample will be appreciated.

Use Control.PointToClient to convert a point from screen-relative coords to control-relative coords. If you need to go the other way, use PointToScreen.

You can directly use the Location property of the MouseEventArgs argument passed to your event-handler.
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
Text = e.Location.X + ":" + e.Location.Y;
}

The following will give you mouse coordinates relative to your control. For example, this results in (0,0) if mouse is over top left corner of the control:
var coordinates = yourControl.PointToClient(Cursor.Position);

One can use following methods for getting the relative from absolute and absolute from relative coordinates:
Point Control.PointToClient(Point point);
Point Control.PointToScreen(Point point);

Cursor.Position return Point on Screen, but Control.PointToClient(Cursor.Position) returns point on control (e.g. control -> panel). In your case, you have e.Locate which return point on control.

private void panel1_MouseMove(object sender, MouseEventArgs e)
{
Text = panel1.PointToClient(Cursor.Position).ToString();
}

Simply subtract from the cursor position the Left and Top coordinates of the control:
this.Text = Convert.ToString(
Cursor.Position.X - this.Left + ":" +
Cursor.Position.Y - this.Top);

I use MouseLocation and PointToClient to check. And then use it in a timer!
bool IsMouseHover(Control c, Control container)
{
Point p = Control.MousePosition;
Point p1 = c.PointToClient(p);
Point p2 = container.PointToClient(p);
if (c.DisplayRectangle.Contains(p1) && container.DisplayRectangle.Contains(p2))
{
return true;
}
return false;
}

private void lienzo_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
{
Point coordenadas = new Point();
coordenadas = Mouse.GetPosition(lienzo);
string msg = "Coordenadas mouse :" + coordenadas.X + "," + coordenadas.Y;
MessageBoxResult resultado;
string titulo = "Informacion";
MessageBoxButton botones = MessageBoxButton.OK;
MessageBoxImage icono = MessageBoxImage.Information;
resultado = MessageBox.Show(msg, titulo, botones, icono);
}
Where "lienzo" is my canvas panel

Snippet code as following:
private void Control_MouseMove(object sender, MouseEventArgs e)
{
var btn = sender as Button;
var point = e.Location;
point.X += btn.Location.X;
point.Y += btn.Location.Y;
Control findTarget = btn.Parent.GetChildAtPoint(point, GetChildAtPointSkip.Invisible) as Button;
if (findTarget != null)
{
// TO DO
}
}
Where the button is one of many buttons in a hosting panel.

Create af standard Project C# WinForms
Place 2 Textboxes named X and Y, and a Timer object from the toolbox to the Design page
Press [F7] and replace all code with below.
using System;
using System.Windows.Forms;
namespace MousePos
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Start();
}
private void Form1_MouseCaptureChanged(object sender, EventArgs e)
{
X.Text = MousePosition.X.ToString();
Y.Text = MousePosition.Y.ToString();
}
}
}
Set Timer.Tick action to "Form1_MouseCaptureChanged"
[F5] Run - and now you have an MosusePos app.

Related

How can I click on drawn points and make a external window opening?

I want to click on points that I drew.
It would be also cool if a window would popup and I could do something with that. But the general thing i want to do is clicking on a drawn point. I want to make it work, that i can click on the map on points that I drew.
Example image:
public partial class Form1 : Form
{
Graphics g;
Pen p;
Point cursor;
int k = 0;
Point[] points = new Point[50];
public Form1()
{
InitializeComponent();
g = pbxkarte.CreateGraphics();
p = new Pen(Color.DeepSkyBlue, 3);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Pbxkarte_Click(object sender, EventArgs e)
{
if (drawmodecbx.Checked == true)
{
g.DrawEllipse(p, cursor.X - 10, cursor.Y - 10, 20, 20);
points[k++] = new Point(cursor.X, cursor.Y);
lbxDrawnPoints.Items.Add("X:" + cursor.X + "Y:" + cursor.Y);
}
}
private void Pbxkarte_MouseMove(object sender, MouseEventArgs e)
{
cursor = this.PointToClient(Cursor.Position);
xydisplay.Text = "X:" + cursor.X + "Y:" + cursor.Y;
}
}
}
Example code:
Two class level variables and a helper function:
List<Point> dots = new List<Point>();
int dotSize = 12;
Rectangle fromPoint(Point pt, int size)
{
return new Rectangle(pt.X - size/ 2, pt.Y - size / 2, size, size);
}
The mouseclick (as opposed to the click event) contains the location:
private void Pbxkarte_MouseClick(object sender, MouseEventArgs e)
{
if (!dots.Contains(e.Location))
{
dots.Add(e.Location);
Pbxkarte.Invalidate(); // show the dots
}
}
You could add code to remove dots or change the properties, esp. if you create a dot class. - If you want to avoid overlapping dots you can to use code like the one in the mousemove to detect this. But. Don't repeat the code! Instead factor out a boolOrPoint IsDotAt(Point) function you can use both times!!
In the mousemove I only show the hit state. You do your thing..
private void Pbxkarte_MouseMove(object sender, MouseEventArgs e)
{
bool hit = false;
foreach (var dot in dots)
{
using (GraphicsPath gp = new GraphicsPath())
{
gp.AddEllipse(fromPoint(dot, dotSize));
if (gp.IsVisible(e.Location))
{
hit = true; break;
}
}
}
Cursor = hit ? Cursors.Hand : Cursors.Default;
}
All dot in the list must get shown every time anything changes, both in the list or in the system.:
private void Pbxkarte_Paint(object sender, PaintEventArgs e)
{
foreach (var dot in dots)
{
using (GraphicsPath gp = new GraphicsPath())
{
gp.AddEllipse(fromPoint(dot, dotSize));
e.Graphics.FillPath(Brushes.Red, gp);
}
}
}
If you want more properties, like texts or colors do create a class dot and use a List<dot> !

Position of curson in clickevent

I want to fetch the position of Control in which click event is performed
for this I have tried following code
Xpos = Cursor.Position.X;
Ypos = Cursor.Position.Y;
but this is giving current position of cursor. then I tried following code
MouseEventArgs m = (MouseEventArgs)e;
Xpos=m.X;
Ypos=m.Y;
but this position is not with respect to whole screen.
How I can get position of control in which click event is performed?
edit
As the link provided for duplicate ,,,,It provides position of point where click action is performed,,,,It does not provide the position of control in which click is performed.
If your project is in WindowsFormApplicaiton then
If your control is button like in screen shot
Then you can access its location wrt to its primary screen also and form screen also
Below is the code
private void button1_Click(object sender, EventArgs e)
{
//This code gives you the location of button1 wrt your primary working screen
Point location = this.PointToScreen(button1.Location);
int x1 = location.X;
int y1 = location.Y;
MessageBox.Show($"X: {x1}, Y: {y1}");
//This code gives you the location of button1 wrt your forms upper-left corner
Point relativeLoc = new Point(location.X - this.Location.X, location.Y - this.Location.Y);
int x2 = relativeLoc.X;
int y2 = relativeLoc.Y;
MessageBox.Show($"X: {x2}, Y: {y2}");
//This code gives you the location of button1 wrt your forms client area
Point relativeLoc1 = new Point(button1.Location.X, button1.Location.Y);
int x3 = relativeLoc1.X;
int y3 = relativeLoc1.Y;
MessageBox.Show($"X: {x3}, Y: {y3}");
}
In above code I used this, you can use any forms object instead as your need
Edit:
If you don't know where your control will be clicked then you have to register one event for all of your controls inside forms like
In below code i used MouseHover event but you can used any event as your need
First of all register MouseHover event for all of your controls inside Form1_Load like
private void Form1_Load(object sender, EventArgs e)
{
foreach (Control c in this.Controls)
c.MouseHover += myMouseHoverEvent;
}
Then your custom MouseHover event is
private void myMouseHoverEvent(object sender, EventArgs e)
{
Control control = sender as Control;
int x = control.Location.X;
int y = control.Location.Y;
MessageBox.Show($"X: {x}, Y: {y}");
}
Try once may it help you
Can you try this? It should return what you're expecting (Left Top Point of the control you click).
XAML:
<TextBlock Text="Sample" Width="100" Height="50"
MouseLeftButtonDown="TextBlock_MouseLeftButtonDown"/>
XAML.cs
private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var control = sender as FrameworkElement;
var positionToScreen = control.PointToScreen(new Point(0, 0));
}
This code should solve your problem if you let this event handler handle the MouseClick event of all the controls you are interested in.
If you want to include the position inside the clicked control. Then add the position included in the mouse event args (Se comment in code).
private void control_MouseClick(object sender, MouseEventArgs e)
{
Control control = sender as Control;
int posX = control.Location.X;
int posY = control.Location.Y;
//Add e.X respectivly e.Y if you want to add the mouse position within the control that generated the event.
while (control.Parent != null)
{
control = control.Parent;
posX += control.Location.X;
posY += control.Location.Y;
}
((Label)sender).Text = "X: " + posX + " Y: " + posY;
}

Setting location of runtime controls

I have added a listBox containing a list and a toolStrip in my application. These are used to select control to added runtime in a panel. (I have added an image. The toolStrip and listBox are on the left and right side respectively.) Now what I do with these controls is,
1 - I select an item from toolStrip or listBox
2 - A runtime control is made and shown on the form
3 - On Mouse_Up event, the control is set on the Panel (If it is in the panel.)
Now the question is, as shown in the image, the runtime control is not at the tip of the cursor. I want these runtime controls on the tip of the cursor.
Below is the Image.
EDIT: Below is the code.:
private void listBox_MouseDown(object sender, MouseEventArgs e)
{
this.globalLabel1 = new Label();
this.globalLabel1.Text = this.listBox.SelectedItem.ToString() + " : ";
//other label properties like, tag, name, events, font etc.
}
private void listBox_MouseMove(object sender, MouseEventArgs e)
{
if (this.globalLabel1 != null)
{
this.globalLabel1.Left = System.Windows.Forms.Cursor.Position.X
- this.Location.X;
this.globalLabel1.Top = System.Windows.Forms.Cursor.Position.Y
- this.Location.Y;
this.globalLabel1.Show();
this.lPanel.SendToBack();
}
}
private void listBox_MouseUp(object sender, MouseEventArgs e)
{
this.globalLabel1.Parent = this.lPanel;
this.globalLabel1.Anchor = AnchorStyles.Top | AnchorStyles.Left;
this.globalLabel1.Left = Cursor.Position.X
- /*Cursor.Size.Height -*/ this.lPanel.Location.X
- this.Location.X;
this.globalLabel1.Top = Cursor.Position.Y
- /*Cursor.Size.Width -*/ this.lPanel.Location.Y
- this.Location.Y;
}
Thanks.
You have to set the Location of your runtime added control relatively to the parent, you can use the method PointToClient like this:
private void listBox_MouseUp(object sender, MouseEventArgs e) {
globalLabel1.Parent = lPanel;
globalLabel1.Anchor = AnchorStyles.Top | AnchorStyles.Left;
globalLabel1.Location = lPanel.PointToClient(Cursor.Position);
}
i). I don't know why are you not using Panel_MoveUP event, Because you wan to place it on panel.
ii). At Panel_moveUp you have to make little bit position change to cursor position by Hit and trail method, I not sure about this why is this difference coming so.
private void listBox1_MouseDown(object sender, MouseEventArgs e)
{
this.globalLabel1 = new Label();
this.globalLabel1.Text = this.listBox1.SelectedItem.ToString() + " : ";
//other label properties like, tag, name, events, font etc.
}
//////////////////////////USE PANEL_MOVEUP EVENT//////////////
private void lPanel_MouseMove(object sender, MouseEventArgs e)
{
if (this.globalLabel1 != null)
{
this.globalLabel1.Left = System.Windows.Forms.Cursor.Position.X-50 // Change
- this.Location.X;
this.globalLabel1.Top = System.Windows.Forms.Cursor.Position.Y-100 //Change
- this.Location.Y;
this.globalLabel1.Show();
this.lPanel.SendToBack();
this.lPanel.Controls.Add(globalLabel1);
}
}

Show my current cursor position as a current line and current column?

I am working on Windows Forms application that uses a RichtextBox, Menustrip and many more controls.
I have done some work but can't get it to work. When my mouse cursor moves in RichTextBox I want to change change the position automatically, like that on simple notepad.
My bit coding is....
I want it so when my mouse cursor moves it changes the dynamic position on my status bar
private void sizeToolStripMenuItem_Click(object sender, EventArgs e)
{
int line = richTextBox1.GetLineFromCharIndex(richTextBox1.SelectionStart);
int column = richTextBox1.SelectionStart - richTextBox1.GetFirstCharIndexFromLine(line);
toolStripStatusLabel5.Text ="Line"+" "+ line.ToString();
toolStripStatusLabel6.Text = " Column" + " " + line.ToString();
toolStripStatusLabel3.Text= Cursor.Position.ToString(); // where is my mouse cursor at this Time like that x and y cordinate 330,334
}
show your line every time when press the enter key.
code is mention below:::----
private void Key_Down(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
int line = richTextBox1.GetLineFromCharIndex(richTextBox1.SelectionStart);
int column = richTextBox1.SelectionStart - richTextBox1.GetFirstCharIndexFromLine(line);
toolStripStatusLabel5.Text = "Line" + " " + line.ToString();
toolStripStatusLabel6.Text = " Column" + " " + column.ToString();
toolStripStatusLabel3.Text = Cursor.Position.ToString(); // where is my mouse cursor at this Time like that x and y cordinate 330,334
Update();
}
}
If you want to update position automatically, you should use MouseMove event from richtextbox instead. While you are moving your mouse it is always updating. Also, "MouseEventArgs e" from MouseMove call can give you the cursor position inside the richtextbox.
You could subscribe to the RichTextBox MouseMove event to update the ToolStrip label with the current mouse position
Example:
private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
{
toolStripStatusLabel3.Text = string.Format("X={0}, Y={1}", e.X, e.Y);
}
Or if you want it to show the position reletive to the RichTextBox you can use the Location from the MouseEventArgs, this will return the position inside the RichTextBox (topleft of textbox = 0,0)
private void richTextBox1_MouseMove(object sender, MouseEventArgs e)
{
toolStripStatusLabel3.Text = string.Format("X={0}, Y={1}", e.Location.X, e.Location.Y);
}
I have done with the help of StackoverFlow and sweetly user(programmer).
Thanks for reply. My code is
private void richTextBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
int line = richTextBox1.GetLineFromCharIndex(richTextBox1.SelectionStart);
int column = richTextBox1.SelectionStart - richTextBox1.GetFirstCharIndexFromLine(line);
toolStripStatusLabel5.Text = "Line" + " " + line.ToString();
toolStripStatusLabel6.Text = " Column" + " " + line.ToString();
toolStripStatusLabel3.Text = Cursor.Position.ToString(); // where is my mouse cursor at this Time like that x and y cordinate 330,334
Update();
}
}

Text under mouse cursor on PictureBox

I have a problem with displaying the text under the mouse cursor on Picture Box.
I want to dynamically display the mouse coordinates under the cursor.
I'm trying to display text by label and change the label's position when a "MouseMove" event happens.
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
label1.Location = new Point(e.X + 10, e.Y + 10);
}
But, I think, it is a bad solution...
And although it works it hides other output when we move the cursor
Thanks a lot!
Thanks for Thomas's advice, here code to display mouse coordinate under cursor:
ToolTip tt = new ToolTip();
tt.SetToolTip(pic, " ");
tt.ShowAlways = true;
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
tt.ToolTipTitle = e.X + " " + e.Y;
}

Categories

Resources