Reputation: 14953
How to place the cursor Exact center of the screen in C# ?
without Resolution independent (it can be 1024X768 or 1600X900)
Upvotes: 6
Views: 13352
Reputation: 22906
Start by getting the Screen instance of interest. If you only ever want the main monitor then simply ask for the PrimaryScreen instance. If however you want the monitor that currently contains the mouse pointer then use the FromPoint static method.
// Main monitor
Screen s = Screen.PrimaryScreen;
// Monitor that contains the mouse pointer
Screen s = Screen.FromPoint(Cursor.Position);
To get the raw monitor bounds then just use the Bounds instance property. But if you want the working area of the monitor, the area that is left over after allocating space for the task bar and widgets then use the WorkingArea instance property.
// Raw bounds of the monitor (i.e. actual pixel resolution)
Rectangle b = s.Bounds;
// Working area after subtracting task bar/widget area etc...
Rectangle b = s.WorkingArea;
Finally position the mouse in the center of the calculated bounds.
// On multi monitor systems the top left will not necessarily be 0,0
Cursor.Position = new Point(b.Left + b.Width / 2,
b.Top + b.Height / 2);
Upvotes: 7
Reputation: 29659
Try
var r = Screen.PrimaryScreen.Bounds;
System.Windows.Forms.Cursor.Position = new Point(r.Bottom/2,r.Right/2);
Upvotes: 1
Reputation: 86718
How about this, assuming you have only 1 monitor:
Cursor.Position = new Point(Screen.PrimaryScreen.Bounds.Width / 2,
Screen.PrimaryScreen.Bounds.Height / 2);
Upvotes: 13