我有一个可编辑的组合框,其中包含文本。我正在尝试获取它,因此如果用户单击该组合框中的某个位置,则光标将放置在用户单击的任何位置。目前,其行为是当用户单击组合框时,整个文本都会突出显示,并且光标将放置在文本末尾。
我尝试过各种 mousedown 事件或尝试使用 Selectionstart,但这只有在我想将光标放置在文本开头或文本结尾等位置时才会有帮助。这对于组合框来说是可能的还是我必须重组以使用不同的类型?
要实现将光标放置在用户在 WinForms 应用程序中的可编辑 ComboBox 中单击的位置的行为,您可以处理 ComboBox 的 MouseDown 事件。在此事件处理程序中,您可以计算文本内的单击位置并相应地设置 SelectionStart 属性。
private void comboBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
// Get the clicked position within the text
int clickPosition = comboBox1.GetCharIndexFromPosition(e.Location);
// Set the cursor position
comboBox1.SelectionStart = clickPosition;
comboBox1.SelectionLength = 0; // Deselect any selected text
}
}
注意:突出显示整个文本是用户习惯的可编辑组合框的默认行为。