おそらく、この最初の例が役立つでしょう。セル編集モードに入ると、クリックしたマウスの位置から 3 文字が選択されます。
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);
}
}
このコードは、まだ編集モードになっていない場合にのみ実行されることに注意してください! これはおそらくあなたのコードが失敗する場所です..
更新:ユーザーが最初のマウスダウンで編集モードと選択の設定の両方を開始するオプションが必要なようです。これは、私のためにそれを行うコードです。
エディット コントロールとテンポラリLambda
の両方に少し使用しますが、 .なしで書くこともできます。モード..TextBox
Timer
Lambda
Timer
MouseDown
Capture
保護されたセルと非テキスト セルの場合は null になる、特にエディター コントロールの場合、それ以降のすべてのエラー チェックはユーザーに委ねられていることに注意してください。
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;
}
}