开发者

Dynamic Object Drawing Based on User Click

I am using Windows Forms in C#, and I would like to make a function that does the following:

When the user clicks on the form, "something" will be drawn in the location that the user clicked.

开发者_StackOverflowI have two questions:

1) Is there a best practice/recommended way of doing this? Right now I am using the Windows EventHandler that fires when the mouse is clicked, getting the cursor's location, and then drawing the object in that location.

2) When I draw the object in the location of "Cursor.Position," it is actually drawn significantly further away than where the actual cursor is located. (It draws it down and to the left.) Is there some type of transformation that must be done on Cursor.Position to get the screen coordinates?

Below I have demonstrated some simplified sample code. You see that I register the form with the "Click" EventHandler. Then, when the EventHandler fires, I call a function that simply draws a label on the form.

Thanks in advance for your help.

MyForm myForm = new myForm();
myForm.Click += new System.EventHandler(this.MyForm_Click);

_

private void MyForm_Click(object sender, EventArgs e)
{
    Point p = Cursor.Position;    // Does this get the correct position?
    DrawObject(p);
}

private void DrawObject(Point p)
{
    Label l = new Label()
    l.Size = new System.Drawing.Size(300, 300);
    l.Text = "New Label";
    l.Location = p;
    this.Controls.Add(l);
}


Instead of using Cursor.Position, you should subscribe to the MouseClick event. This will provide you location information in the handler itself.

Cursor.Position will give you coordinates in screen coordinates. If you want to use it, you'll need to use PointToClient to map it to your form's coordinate space.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜