在WinForm中创建边界控件的最佳实践

时间:2012-08-28 06:59:57

标签: c# .net winforms border

我在C#.NET中编写WinForm应用程序,当用户点击它时,我需要在应用程序的任何UI组件中添加虚线/点线或任何其他类型的边框。我想在Visual Studio中获得类似WinForm GUI编辑器的东西。

我是.NET的新手,所以我不太清楚通过本机方法和属性可能实现什么,以及我需要自己实现什么。我试图在网上找到一些东西,但我不知道该搜索什么,有不同的方法。例如,可以人工绘制边框,我的意思是使用图形。但我想应该有更简单的方法。

你有什么建议?在这种情况下,最佳做法是什么?请提供部分代码。

1 个答案:

答案 0 :(得分:3)

每个Control都有Paint个事件。您必须订阅此事件并查看给定的参数。 sender是应该绘制的当前控件。您可以在方法中将其强制转换为Control。现在,您可以通过检查control.Focused检查控件是否聚焦,如果它是真的,只需在PaintEventArgs的图形对象中执行任何您喜欢的操作。这可以进一步封装在扩展方法中,这将使用起来相当容易。

public static void DrawBorderOnFocused(this Control control)
{
    if(control == null) throw new ArgumentNullException("control");
    control.Paint += OnControlPaint;
}

public static void OnControlPaint(object sender, PaintEventArgs e)
{
    var control = (Control)sender;

    if(control.Focused)
    {
       var graphics = e.Graphics;
       var bounds = e.Graphics.ClipBounds;

       // ToDo: Draw the desired shape above the current control
       graphics.DrawLine(Pens.BurlyWood, new PointF(bounds.Left, bounds.Top), new PointF(bounds.Bottom, bounds.Right));
    }
}

代码中的用法将类似于:

public MyClass()
{
    InitializeComponent();

    textBox1.DrawBorderOnFocused();
    textBox2.DrawBorderOnFocused();
}
相关问题