winform开发中实现listbox内容添加到textbox光标后面,代码如下:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private int txtSelectStart;
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);
/// <summary>
/// 设置textbox光标
/// </summary>
/// <param name="txb"></param>
/// <param name="pos"></param>
public void SetCursorPosofTextBox(TextBox txb, int pos)
{
txb.Focus();
SendMessage(txb.Handle, 177, pos, pos);
}
private void Form2_Load(object sender, EventArgs e)
{
this.textBox1.Text = "abcdef";
}
/// <summary>
/// 光标离开textbox时记录光标位置
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void textBox1_Leave(object sender, EventArgs e)
{
txtSelectStart = this.textBox1.SelectionStart;
}
/// <summary>
/// 双击listbox时添加字符串到光标位置
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listBox1_DoubleClick(object sender, EventArgs e)
{
this.textBox1.Text = this.textBox1.Text.Insert(txtSelectStart, listBox1.SelectedItem.ToString());
this.SetCursorPosofTextBox(this.textBox1,txtSelectStart + listBox1.SelectedItem.ToString().Length);
}
}
效果图: