简体   繁体   中英

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. 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. The way I've set the form to get maximized is by using form.FormBorderStyle = FormBorderStyle.None; and 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). I created a desktop background which as a crosshair in the middle of the screen in photoshop (The image is also 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. ClientRectangle returns the bounds of the drawable are of the window.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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