這是棘手的Drag&Drop
操作保持鼠標捕獲,所以你不能用鼠標事件..
一種方法是建立一個Timer
做的工作..:
Timer cursTimer = new Timer();
void cursTimer_Tick(object sender, EventArgs e)
{
int cp = txtExpresion.GetCharIndexFromPosition(
txtExpresion.PointToClient(Control.MousePosition));
txtExpresion.SelectionStart = cp;
txtExpresion.SelectionLength = 0;
txtExpresion.Refresh();
}
Timer
使用Control.MousePosition
函數來確定光標位置每25ms左右,設置插入符並更新TextBox
。
在您的活動中,您將其初始化並確保TextBox
具有焦點;最後你在當前選擇添加字符串:
private void txtExpresion_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(string)))
{
e.Effect = DragDropEffects.Copy;
txtExpresion.Focus();
cursTimer = new Timer();
cursTimer.Interval = 25;
cursTimer.Tick += cursTimer_Tick;
cursTimer.Start();
}
}
private void txtExpresion_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(System.String)))
{
cursTimer.Stop();
string Item = (System.String)e.Data.GetData(typeof(System.String));
string[] split = Item.Split(':');
txtExpresion.SelectedText = split[1]
}
}
一種不同的方式來解決這將是不使用正常拖動&下降,只有代碼鼠標事件,但是一個好的工作了我的第一次測試。
更新
雖然上述方案確實工作,使用Timer
似乎並不完全優雅。從Reza的回答可以看出,使用DragOver
事件會更好。但是,不要畫一個光標,爲什麼不去做真實的事情,即控制實際的工字母..?
的DragOver
事件被稱爲在移動過程中所有的時間,所以它的工作原理很像MousMove
會:所以在這裏是兩個解決方案,我相信這將是它的最佳方式的合併:
private void txtExpresion_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(System.String)))
{
string Item = (System.String)e.Data.GetData(typeof(System.String));
string[] split = Item.Split(':');
txtExpresion.SelectionLength = 0;
txtExpresion.SelectedText = split[1];
}
}
private void txtExpresion_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(string)))
{
e.Effect = DragDropEffects.Copy;
txtExpresion.Focus();
}
}
private void txtExpresion_DragOver(object sender, DragEventArgs e)
{
int cp = txtExpresion.GetCharIndexFromPosition(
txtExpresion.PointToClient(Control.MousePosition));
txtExpresion.SelectionStart = cp;
txtExpresion.Refresh();
}
來源
2016-08-11 19:43:39
TaW
看到更新的答案,它融合了最好的我原來的和禮的解決方案的@! – TaW