すべてControl
にPaint
イベントがあります。このイベントをサブスクライブして、指定された引数を調べる必要があります。sender
ペイントする必要がある現在のコントロールです。メソッド内でにキャストできますControl
。これで、コントロールがフォーカスされているかどうかをチェックしてチェックできます。control.Focused
それがtrueであるかどうかは、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();
}