Search code examples
c#formscoordinatesmouse-coordinates

c# Form location from mouse click


I have a PictureBox which when I click on it I would like to open a Form with a legend. It should spawn on the mouse click location. I am using Windows Forms .NET 4.5.2.

I have tried this:

    private void previewPictureBox_Click(object sender, EventArgs e)
    {
        MouseEventArgs mouseEvent = (MouseEventArgs)e;
        if (mouseEvent.Button == MouseButtons.Right)
        {
            Point mouseLocation = new Point(mouseEvent.X, mouseEvent.Y);
            JobViewerLegendForm legend = new JobViewerLegendForm();
            legend.StartPosition = FormStartPosition.Manual;
            legend.Location = mouseLocation;
            legend.Show();
        }
    }

This spawns the form in the wrong place since the mouse is relative to the PictureBox and the form location is relative to the screen (and not even the screen where the form is located). Any idea on how to place the form where the mouse is?


Solution

  • Try converting into screen coordinates with PointToScreen()

    private void previewPictureBox_Click(object sender, EventArgs e)
    {
        MouseEventArgs mouseEvent = (MouseEventArgs)e;
        if (mouseEvent.Button == MouseButtons.Right)
        {
            Point mouseLocation = new Point(mouseEvent.X, mouseEvent.Y);
            mouseLocation = this.PointToScreen(mouseLocation);
            JobViewerLegendForm legend = new JobViewerLegendForm();
            legend.StartPosition = FormStartPosition.Manual;
            legend.Location = mouseLocation;
            legend.Show();
        }
    }