user3200169
user3200169

Reputation: 275

How do i StartPosition of the form from the current mouse cursor position?

I have this line:

StartPosition = FormStartPosition.Manual;

In my program each time i click on a button its showing the new form. But its not good i want that the form position to be each time where the mouse cursor is. How can i do it ?

Upvotes: 1

Views: 4339

Answers (3)

jacobian
jacobian

Reputation: 141

        var form = new Form1();
        form.StartPosition = FormStartPosition.Manual;
        form.Left = Cursor.Position.X;
        form.Top = Cursor.Position.Y;

        var width= Screen.PrimaryScreen.Bounds.Width;
        var height = Screen.PrimaryScreen.Bounds.Width;

        if (form.Left + form.Width > width)
        {
            form.Left = width - form.Width;
        }

        if (form.Top+form.Height>height)
        {
            form.Top = height - form.Height;
        }

Upvotes: 0

Sinatr
Sinatr

Reputation: 22008

I'd go with constructor overloads, but otherwise it is the same as John Woo answer.

public Form1()
{
    InitializeComponent();
    // mandatory, could be set in the designer
    StartPosition = FormStartPosition.Manual;
}

public Form1(int x, int y):
    this()
{
    this.Left = x;
    this.Top = y;
}

public Form1(Point location):
    this()
{
    this.Location = location;
}

and use it from another form event (because of this to set parent):

var form = new Form1(Cursor.Position);
form.ShowDialog(this);

Upvotes: 1

John Woo
John Woo

Reputation: 263893

put this at form_Load() event

var _point = new System.Drawing.Point(Cursor.Position.X, Cursor.Position.Y);
Top = _point.Y;
Left = _point.X;

Upvotes: 5

Related Questions