How to add a label apon mouse click on the same spot in C#?
-
26-09-2019 - |
Question
my program has a picturebox, and I want, apon a mouse click, or on ContextMenuStrip choice, to make something appear at the same spot of the click.
as seen in the picture, i would like to add some kind of a note on the specific clicked date area (probably add a user control)
How do i go at it ? how can i send the click cordinates (x,y) and make something appear at these same coordinates ?
Thanks !
Solution
I would create a class which would provide menu items and capture x,y coordinates to have them ready when the item is clicked. Or you can capture these coordinates in an anonymous delegate.
Something like this:
public Form1()
{
InitializeComponent();
MouseClick += new MouseEventHandler(Form1_MouseClick);
}
private void Form1_MouseClick (object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
ContextMenuStrip ctxMenu = new ContextMenuStrip();
// following line creates an anonymous delegate
// and captures the "e" MouseEventArgs from
// this method
ctxMenu.Items.Add(new ToolStripMenuItem(
"Insert info", null, (s, args) => InsertInfoPoint(e.Location)));
ctxMenu.Show(this, e.Location);
}
}
private void InsertInfoPoint(Point location)
{
// insert actual "info point"
Label lbl = new Label()
{
Text = "new label",
BorderStyle = BorderStyle.FixedSingle,
Left = location.X, Top = location.Y
};
this.Controls.Add(lbl);
}
OTHER TIPS
An sample code for your requirement, In my below code i am adding button control on mouse click. You can modify the code as per ur need.
int xValue=0, yValue=0;
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
xValue = e.X;
yValue = e.Y;
Button btn = new Button();
btn.Name = "Sample Button";
this.Controls.Add(btn);
btn.Location = new Point(xValue, yValue);
}
you can use either tool tip or use mousemove event. this event will provide you current xy postion of mouse and then you can show your content by either visible true/false at that place or take a label and set its text and then set its xy position according to xy of mouse. and then on mouseleave event move that label to off screen or hide