Reputation: 275
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
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
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
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