Search code examples
c#.netcoordinatesmouseclick-eventonmouseclick

How to add a label apon mouse click on the same spot in C#?


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 !

alt text


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);
    }