如何放置光标精确的屏幕中心

Gal*_*ali 5 c# winforms

如何将光标放在C#的屏幕中心?

没有独立分辨率(可以是1024X768或1600X900)

Gab*_*abe 12

假设您只有一台显示器,那怎么样:

Cursor.Position = new Point(Screen.PrimaryScreen.Bounds.Width / 2,
                            Screen.PrimaryScreen.Bounds.Height / 2);
Run Code Online (Sandbox Code Playgroud)


Phi*_*ght 7

首先获取感兴趣的Screen实例.如果您只想要主监视器,那么只需要请求PrimaryScreen实例.但是,如果您想要当前包含鼠标指针的监视器,请使用FromPoint静态方法.

    // Main monitor
    Screen s = Screen.PrimaryScreen;

    // Monitor that contains the mouse pointer
    Screen s = Screen.FromPoint(Cursor.Position);
Run Code Online (Sandbox Code Playgroud)

要获取原始监视器边界,请使用Bounds实例属性.但是,如果您需要监视器的工作区域,在为任务栏和窗口小部件分配空间后剩下的区域,则使用WorkingArea实例属性.

    // 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;
Run Code Online (Sandbox Code Playgroud)

最后将鼠标放在计算边界的中心.

    // 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);
Run Code Online (Sandbox Code Playgroud)