也許這第一個例子會有所幫助。
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (dataGridView1.EditingControl == null)
{
dataGridView1.BeginEdit(false);
TextBox editor = (TextBox)dataGridView1.EditingControl;
// insert checks for null here if needed!!
int ms = editor.GetCharIndexFromPosition(e.Location);
editor.SelectionStart = ms;
editor.SelectionLength = Math.Min(3, editor.Text.Length - editor.SelectionStart);
}
}
需要注意的是,當我們在編輯模式尚不代碼只執行:它進入細胞的編輯模式時,從點擊鼠標位置選擇3個字符!這可能是您的代碼失敗的原因。
更新:由於您似乎希望用戶選擇啓動編輯模式並在第一次向下鼠標時設置選擇,這裏有一段代碼只是對我而言。
它使用兩個TextBox
編輯控件和臨時Timer
但也可以同樣地沒有Lambda
寫了一個小Lambda
..需要的Timer
爲MouseDown
事件不斷捕捉鼠標,直到該事件後也進行釋放Capture
,從而防止單元格進入編輯模式。
請注意,所有進一步的錯誤檢查都由您自己決定,尤其是對於編輯器控件,對於受保護的單元格和非文本單元格將爲空。
int mDwnChar = -1;
DataGridViewCell lastCell = null;
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex];
if (dataGridView1.EditingControl == null || cell != lastCell)
{
dataGridView1.BeginEdit(false);
TextBox editor = (TextBox)dataGridView1.EditingControl;
editor.MouseMove += (ts, te) =>
{
if (mDwnChar < 0) return;
int ms = editor.GetCharIndexFromPosition(te.Location);
if (ms >= 0 && mDwnChar >=0)
{
editor.SelectionStart = Math.Min(mDwnChar, ms);
editor.SelectionLength = Math.Abs(mDwnChar - ms + 1);
}
};
editor.MouseUp += (ts, te) => { mDwnChar = -1; };
mDwnChar = editor.GetCharIndexFromPosition(e.Location);
dataGridView1.Capture = false;
Timer timer00 = new Timer();
timer00.Interval = 20;
timer00.Tick += (ts, te) => {
timer00.Stop();
dataGridView1.BeginEdit(false);
};
timer00.Start();
lastCell = cell;
}
}
來源
2015-04-17 20:02:30
TaW
嗨!你有沒有看到這個https://social.msdn.microsoft.com/Forums/en-US/04362a62-8cbf-4d86-a1bc-2aba8e4978ca/cursor-position-in-textbox?forum=Vsexpressvcs? –
這很有幫助。現在我知道了脫字符和光標的區別。所以我的問題是兩者的相互作用。目前我使用selectionStart設置插入符號,所以現在我需要檢測鼠標光標在單擊位置並設置選擇開始。然後我需要檢測鼠標拖動的長度並設置選擇長度。我想我需要找到信息光標位置和鼠標拖動。 –
投射到文本框後,您可以使用'Textbox.GetCharFromPosition(mouseLocation)'成功。我認爲保留對TextBox的引用會使事情變得更簡單。 – TaW