事实上,您的控件是可见的,但有 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 会有所帮助。同样,您仍然需要计算您的行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);
}
}