111,125
社区成员
发帖
与我相关
我的任务
分享
收藏了
public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern bool CreateCaret(IntPtr hWnd, IntPtr hBitmap, int nWidth, int nHeight);
[DllImport("user32.dll")]
static extern bool ShowCaret(IntPtr hWnd);
[DllImport("user32.dll")]
static extern bool DestroyCaret();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Func<Control, IEnumerable<Control>> descendants = null;
descendants = control => control.Controls.Cast<Control>().SelectMany(c => new[] {c}.Union(descendants(c)));
descendants(this).Where(c => c is TextBox).ToList().ForEach(textbox =>
{
textbox.GotFocus += textBox_GotFocus;
textbox.LostFocus += textbox_LostFocus;
});
}
void textBox_GotFocus(object sender, EventArgs e)
{
var textbox = (TextBox)sender;
int w = (int)textbox.Font.Size, h = textbox.Font.Height;
var bmp = new Bitmap(w, h);
using (var g = Graphics.FromImage(bmp))
{
g.Clear(Color.Black);
g.DrawLine(new Pen(Color.White, 2), 0, h, w, h);
}
CreateCaret(textbox.Handle, bmp.GetHbitmap(), 0, 0);
ShowCaret(textbox.Handle);
}
void textbox_LostFocus(object sender, EventArgs e)
{
DestroyCaret();
}
}