简体   繁体   English

即使屏幕高度和宽度正确,C#Winforms也无法在屏幕中间进行绘制

[英]C# winforms unable to paint in middle of screen, even with the correct screen height and width

I'm trying to write a program, that will place a crosshair in the middle of the screen on a transparent background, however the crosshair will always be drawn at an offset even though the coordinates where it's placed is right. 我正在尝试编写一个程序,将十字准线放置在透明背景下的屏幕中间,但是,即使放置的坐标正确,十字准线也总是以偏移量绘制。

The method which draws the crosshair: 绘制十字准线的方法:

public void drawSquareCrosshair(Graphics gfx, Color color) {
        SolidBrush lightChrosshairColor = new SolidBrush(color);
        SolidBrush transparentColor = new SolidBrush(Color.Fuchsia);

        // Crosshair Bounds
        int width = 20;
        int height = 20;
        int x = (SystemInformation.VirtualScreen.Width / 2)- (width / 2);
        int y = (SystemInformation.VirtualScreen.Height / 2) - (height / 2);


        Console.WriteLine("X: " + x);
        Console.WriteLine("Y: " + y);

        gfx.FillRectangle(lightChrosshairColor, x, y, width, height);
    }

The logic is, that the width of the screen is divided by two, and minussed by the width of the crosshair divided by two. 逻辑是,屏幕的宽度除以2,然后减去十字准线的宽度除以2。 The same goes for the height. 高度也一样。 I've set the graphics object to create graphics on a panel which is anchored on all sides within the form, yet the panels height and width is still 1920x1080, just as the form is. 我已经设置了图形对象,以在固定在表单内所有面上的面板上创建图形,但是面板的高度和宽度仍为1920x1080,与表单一样。 The way I've set the form to get maximized is by using form.FormBorderStyle = FormBorderStyle.None; 我将表单设置为最大化的方式是使用form.FormBorderStyle = FormBorderStyle.None; and form.WindowState = FormWindowState.Maximized; form.WindowState = FormWindowState.Maximized;

However that doesn't seem to be the case, as the crosshair is still placed at the coordinates that would resemble the middle of the screen (X: 960, Y: 540 on a 1920x1080 screen). 但是,情况似乎并非如此,因为十字准线仍放置在类似于屏幕中间的坐标上(在1920x1080屏幕上为X:960,Y:540)。 I created a desktop background which as a crosshair in the middle of the screen in photoshop (The image is also 1920x1080). 我在photoshop屏幕中间创建了一个十字形的桌面背景(图像也是1920x1080)。 Here's how it looks: The square is the crosshair painted by my application, the red cross is the wallpaper 外观如下: 正方形是我的应用程序绘制的十字准线,红色十字是墙纸

Has anyone run into this problem before? 有人遇到过这个问题吗?

This can be fixed by replacing SystemInformation.VirtualScreen with ClientRectangle , see the below code. 可以通过将SystemInformation.VirtualScreen替换为ClientRectangle来解决此问题,请参见以下代码。 ClientRectangle returns the bounds of the drawable are of the window. ClientRectangle返回窗口的可绘制区域的边界。

        int x = (ClientRectangle.Width / 2) - (width / 2);
        int y = (ClientRectangle.Height / 2) - (height / 2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM