实际上,您的 Control 是可见的,但具有Size of Empty。您看到的线不是在控件上绘制的线,而是在您的表单上绘制的,这就是您认为您的线可见的原因。您想创建具有任意方向的线。我认为这有点难,你必须Rectangle
根据你的线方向和水平线所形成的角度来计算你的线(其中一个边是你的线粗)。如果你能计算出来Rectangle
,你必须使用该Region
属性来使你的线控件完全适合它Rectangle
。类似的东西yourLine.Region = new Region(calculatedRectangle);
。对于这种复杂性,许多 UI 库只是支持Horizontal line
,Vertical line
因为我们可以计算它们的Rectangle
很容易,并且它们比其他类型的线更频繁地使用。这是水平线的代码,我没有时间根据需要深入编写全功能线,但您可能想自己尝试一下:
public class Line : Control
{
Color lineColor = Color.Red;
public Color LineColor {
get { return lineColor;}
set {
lineColor = value;
BackColor = value;
}
}
public Line(){
Height = 1;//Default thickness
Width = 100;//Default length
BackColor = lineColor;
}
//for the case you want to draw yourself, add code in this method
protected override void OnPaint(PaintEventArgs e){
base.OnPaint(e);
//your code
}
}
//use it
Line line = new Line(){Left = 50, Top = 50};
line.MouseEnter += new EventHandler(line_MouseEnter);
如果你想在你的表格上画线,我认为你的线实际上是一个存储线信息(粗细、长度、起点、终点)的结构。所以你不需要它来继承Control
和注册MouseEnter
,你必须MouseMove
为你的表单添加事件处理程序,而不是你的行。但是,您的线路Rectangle
会有所帮助。同样,你仍然需要计算你的 line Rectangle
,正如我之前所说的,这并不容易。为了演示它,我只是Rectangle
以一种简单的方式计算你的线(将起点和终点的 X 都增加 1):
//Your control has Size of Empty in this example, it just stores information of your line and is used to register the MouseMove event handler with the Form when its Parent is changed (to Form).
public class Line : Control
{
public Point start { get; set; }
public Point end { get; set; }
public Pen pen = new Pen(Color.Red);
protected override void OnParentChanged(EventArgs e){
if(Parent != null){
Parent.MouseMove -= MouseMoveParent;
Parent.MouseMove += MouseMoveParent;
}
}
private void MouseMoveParent(object sender, MouseEventArgs e){
//the line Rectangle is specified by 4 points
//I said that this is just for demonstrative purpose because to calculate
//the exact 4 points (of the line Rectangle), you have to add much more code.
Point p1 = start;
Point p2 = new Point(p1.X + 1, p1.Y);
Point p3 = new Point(end.X + 1, end.Y);
Point p4 = end;
System.Drawing.Drawing2D.GraphicsPath gp = new System.Drawing.Drawing2D.GraphicsPath();
gp.AddPolygon(new Point[]{p1,p2,p3,p4});
Region lineRegion = new Region(gp);
if(lineRegion.IsVisible(e.Location)){
MessageBox.Show("Hello World");
}
}
}
public partial class Form1 : Form
{
public Line line = new Line() { start = new Point(50, 50), end = new Point(100, 100) };
public Form1()
{
InitializeComponent();
Controls.Add(line);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawLine(line.pen, line.start, line.end);
}
}