简体   繁体   中英

C# Cursor Position not in right place in forms

I'm trying to create a square that is located where the user clicks. I have pSize, pX, and pY as variables to represent the location and size of the square. But when I click on the form, the square is at least 70 pixels of in X and Y coordinates where the mouse clicked. I did (this is in the form click function):

pX = Cursor.Position.X;
pY = Cursor.Position.Y;

Graphics g = this.CreateGraphics();
SolidBrush brush = new SolidBrush(Color.Black);

g.FillRectangle(brush, pX, pY, pSize, pSize);

Here is a picture of what is happening:

The screenshot doesn't show my cursor but it is in the top left corner. I also noticed that every time I start the program, the amount the square is offset changes so this time it's relatively distant while next time it could be only about 25 pixels away in both axes.

Could someone tell me what I am doing wrong and/or what I can do about it? Thanks.

You're currently getting the Cursor position. Which is relative to the screen , which is why it is a different offset when you move the form around.

To get the position relative to your Form you need to use the Mouse Click position (sounds similar which is how this tricks people).

You need to make sure your Click event raises a MouseEventHandler:

this.MouseClick += new System.Windows.Forms.MouseEventHandler(this.DrawSquare);

Then you need to get the coordintaes from the event handler:

    private void DrawSquare(object sender, MouseEventArgs e)
    {
        int pX = e.X;
        int pY = e.Y;

        int pSize = 10;
        Graphics g = this.CreateGraphics();
        SolidBrush brush = new SolidBrush(Color.Black);

        g.FillRectangle(brush, pX, pY, pSize, pSize);
    }

I think you don't need the cursor position, but the click position instead. Try this:

    private void Form2_MouseClick(object sender, MouseEventArgs e)
    {
        int pX = e.X;
        int pY = e.Y;

        Graphics g = this.CreateGraphics();
        SolidBrush brush = new SolidBrush(Color.Black);

        g.FillRectangle(brush, pX, pY, 10, 10);//Size just for testing purposes
    }

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