我需要在用C#创建的表单上画一条线. [英] I need to draw a line on the form created in c#.

查看:74
本文介绍了我需要在用C#创建的表单上画一条线.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

先生您好,

我希望我可以使用mouse.How在窗体上画一条线.请帮助

hello sir,

i want that i could draw a line on the form by using mouse.How could it be done.please help

推荐答案

我想向其中添加一些细节和修正Simon提供的代码.

例如,将以下代码添加到表单的构造函数中:

I want to add some detail and a fix to the code provided by Simon.

For example, add the following code to the form''s constructor:

this.Paint += (sender, eventArgs) => {
    using (Pen pen = Pen(Color.FromArgb(255, 255, 0, 0))) {
        eventArgs.Graphics.DrawLine(pen, startX, startY, endX, endY);
    } //calls Pen.Dispose here, even if exception was thrown
};



注意使用"语句.无论是否引发异常,它都用于保证pen的处置.此构造是一种语法糖,严格等同于将pen的创建与finally部分中的处理操作一起放置在try-finally块下.

或者,您可以重新使用pen和其他资源.在这种情况下,您应该以表单的构造函数创建它们并放置在Form.Dispose中,请参见 http ://msdn.microsoft.com/zh-CN/library/aw58wzka.aspx [ ^ ].

您需要在调用之前初始化几何参数startX, startY, endX, endY.如果您需要更改线的位置,请填写表格字段.要更改线的位置,您需要更改这些字段的值.现在,如何触发重新绘制图片?您需要导致将事件WM_PAINT发送到表单.这是使用Form.Invalidate(继承自Control.Invalidate)完成的.您可以使用带有参数(RectangleRegion)的Invalidate来提高性能,以使场景的仅一部分无效.

—SA



Pay attention for the "using" statement. It''s used to guarantee disposal of pen, no matter if exception was thrown or not. This construct is a syntactic sugar and is strictly equivalent to placing creation of the pen under try-finally block with disposal operation in the finally part.

Alternatively, you can re-use the pen and other resources. In this case, you should created them in the form''s constructor and dispose in Form.Dispose, see http://msdn.microsoft.com/en-us/library/aw58wzka.aspx[^].

You need to initialize geometric parameters startX, startY, endX, endY prior to the call. If you ever need to change the position of the line, make the form fields. To change the position of line, you need to change the values of those fields. Now, how to trigger re-drawing of the picture? You need to cause sending the event WM_PAINT to the form. This is done using Form.Invalidate (inherited from Control.Invalidate. You can improve performance using Invalidate with parameters (Rectangle or Region) to invalidate just some part of the scene.

—SA


处理Forms Paint事件,然后可以像这样绘制:
Handle the Forms Paint event and then you can draw like so:
Pen pen = new Pen(Color.FromArgb(255, 255, 0, 0));
e.Graphics.DrawLine(pen, _startX, _startY, _endX, _endY);


那就是画线部分.现在,您只需要跟踪鼠标的MouseDown,MouseUp,MouseMove事件即可帮助您解决此问题.


That''s the draw a line part. Now you just need to track the mouse the MouseDown, MouseUp, MouseMove event might help you with that.


这篇关于我需要在用C#创建的表单上画一条线.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆