前言
大概是我孤陋寡闻了吧,泡在百度上翻来覆去没找到类似的控件;我想可能大家是不需要,其实,我也不太需要,就是那么突发奇想的,就想写一个这样的控件出来。。。
Bejson访问过吧?Notepad++用过吧?发现一个事情没有?左边都有行数导航。嗯,就是这个东西。没用过?那下面看个图
有用没用?好像没用,又好像有......
开发环境:.NET Framework版本:4.8
开发工具:Visual Studio 2022
实现步骤
protected override void OnMouseMove(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
SetScroll();
}
base.OnMouseMove(e);
}
protected override bool ProcessCmdKey(ref Message m, Keys keyData)
{
if (keyData == Keys.Left || keyData == Keys.Right || keyData == Keys.Down || keyData == Keys.Up)
{
SetScroll();
}
return base.ProcessCmdKey(ref m, keyData);
}
protected override void OnMouseWheel(MouseEventArgs e)
{
SetScroll();
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
SetScroll();
}
private void SetScroll()
{
if (AsyncScroll != null)
{
BeginInvoke(new Action(() =>
{
int Pos = GetScrollPos(Handle, SB_VERT);
AsyncScroll(Pos);
}));
GC.Collect();
}
}
public partial class NumTextBox : UserControl { const int SB_VERT = 1; const int WM_VSCROLL = 0X0115; const int SB_THUMBPOSITION = 4; [DllImport("user32.dll")] static extern int SetScrollPos(IntPtr hWnd, int nBar, int nPos, bool bRedraw); [DllImport("user32.dll")] private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam); public override string Text { get { return txt_text.Text; } set { txt_text.Text = value; } } public NumTextBox() { InitializeComponent(); txt_text.AsyncScroll += pos => { SetScrollPos(txt_num.Handle, SB_VERT, (SB_THUMBPOSITION + 0x10000 * pos), true); SendMessage(txt_num.Handle, WM_VSCROLL, (IntPtr)(SB_THUMBPOSITION + 0x10000 * pos), IntPtr.Zero); }; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); txt_num.BackColor = panel_split.BackColor = Color.WhiteSmoke; } private void txt_text_TextChanged(object sender, EventArgs e) { txt_num.Clear(); string[] lines = txt_text.Text.Split('\n'); string[] nums = new string[lines.Length]; for (int i = 1; i <= lines.Length; i++) { nums[i - 1] = i + ""; } txt_num.Lines = nums; } }
实现效果
联系客服