2014-12-25 3 views
2

많은 비슷한 질문에도 불구하고 대답을 찾을 수 없었습니다. 내가하고 싶은 것은 다음과 같습니다.텍스트 상자의 마우스 위치에 텍스트 놓기

텍스트가있는 텍스트 상자와 각각 그림이있는 몇 개의 그림 상자가 있습니다. 그림에서 텍스트 상자로 드래그 앤 드롭을 수행하면 드롭 다운을 만들 때 (즉, mouseup 이벤트가 발생하는 지점에서) 커서가있는 위치의 텍스트가 텍스트 상자에 삽입되어야합니다.

첫 번째 부분은 괜찮 :

private void textBox1_DragDrop(object sender, DragEventArgs e) { 
     textBox1.Text.Insert(CORRECT_POSITION, e.Data.GetData(DataFormats.Text).ToString()); 
    } 

어떤 제안 :

private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { 
    // Create custom text ... 
    pictureBox1.DoDragDrop("Some custom text", DragDropEffects.Copy); 
} 

private void textBox1_DragEnter(object sender, DragEventArgs e) { 
    if (e.Data.GetDataPresent(DataFormats.Text)) 
     e.Effect = DragDropEffects.Copy; 
    else 
     e.Effect = DragDropEffects.None; 
} 

내 문제가 텍스트를 드롭 위치를 정의하는 방법은?

편집 : GetCharIndexFromPosition()을 사용하여 올바른 위치를 얻으려고했으나 정확한 위치를 반환하지 않는 것 같습니다. 다음 코드는 실제로 문자 위치를 반환하지만 어디서 가져 왔는지 전혀 알지 못합니다. 커서의 위치를 ​​나타내는 것은 아닙니다.

private void textBox1_DragDrop(object sender, DragEventArgs e) { 
    TextBox textBox1 = (TextBox)sender; 
    System.Drawing.Point position = new System.Drawing.Point(e.X, e.Y); 
    int index = textBox1.GetCharIndexFromPosition(position); 
    MessageBox.Show(index.ToString()); 
} 
+0

감사합니다. 포인트 질문에 대한 @linurb! –

답변

2

현재 마우스 위치를 TextBox 내의 클라이언트 좌표로 변환해야합니다. 또한 DragOver() 이벤트에서 삽입 점을 이동하여 사용자가 텍스트를 삽입 할 위치를 볼 수 있습니다.

private void pictureBox1_MouseMove(object sender, MouseEventArgs e) 
    { 
     if (e.Button == System.Windows.Forms.MouseButtons.Left) 
     { 
      pictureBox1.DoDragDrop("duck", DragDropEffects.Copy); 
     } 
    } 

    void textBox1_DragEnter(object sender, DragEventArgs e) 
    { 
     if (e.Data.GetDataPresent(DataFormats.Text)) 
      e.Effect = DragDropEffects.All; 
     else 
      e.Effect = DragDropEffects.None; 
    } 

    void textBox1_DragOver(object sender, DragEventArgs e) 
    { 
     int index = textBox1.GetCharIndexFromPosition(textBox1.PointToClient(Cursor.Position)); 
     textBox1.SelectionStart = index; 
     textBox1.SelectionLength = 0; 
    } 

    void textBox1_DragDrop(object sender, DragEventArgs e) 
    { 
     string txt = e.Data.GetData(DataFormats.Text).ToString(); 
     int index = textBox1.GetCharIndexFromPosition(textBox1.PointToClient(Cursor.Position)); 
     textBox1.SelectionStart = index; 
     textBox1.SelectionLength = 0; 
     textBox1.SelectedText = txt; 
    } 
+0

정말 고마워! 내가 오리 부분을 이해하지 않지만, 나는 또한 일하는 보너스 부분을 얻었다. :) MouseMove 이벤트 (?) 없이는 정상적으로 작동하는 것 같습니다. – linurb

+0

MouseMove() 이벤트는 끌어서 놓기를 시작하는 다른 방법입니다. –

+0

아, 알겠습니다. 감사. – linurb

관련 문제