【问题标题】:How to catch key states when I am dragging an object over a control? - C#当我在控件上拖动对象时如何捕捉关键状态? - C#
【发布时间】:2026-01-12 06:10:01
【问题描述】:

当我在列表框中拖动一些文本时,我需要使用一些键更改拖放效果。

bool ctrlD = false;

private void MainForm_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Control && e.KeyCode == Keys.D)
        ctrlD = true;
}

// KeyUp 

private void textBox_MouseDown(object sender, MouseEventArgs e)
{
    textBox.DoDragDrop(textBox.Text, DragDropEffects.All);
}

private void listBox_DragOver(object sender, DragEventArgs e)
{
    if (ctrlD) e.Effect = DragDropEffects.Copy;
    else e.Effect = DragDropEffects.Move;
}

问题是 DragOver 方法看不到何时按下任何键。效果不变。我该怎么办?

【问题讨论】:

标签: c# winforms drag-and-drop cursor keydown


【解决方案1】:
bool ctrlD = false

使用对象发送者

private void textBox_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
      this.DoDragDrop(sender, DragDropEffects.All);
    }
}

确保将 AllowDrop 设置为 True

添加 (MyContol) (_DragEnter) 和 (_DragDrop) 事件

private void MyControl_DragEnter(object sender, DragEventArgs e)
{
    /*
    DragDropEffects
    */
    e.Effect = DragDropEffects.Copy; 
}

private void MyControl_DragDrop(object sender, DragEventArgs e)
{
    TextBox tb = e.Data.GetData(typeof(TextBox)) as TextBox;
    /*
    MyControl.Controls.Add(tb);
    * Your code here
    */
}

【讨论】:

    【解决方案2】:

    您需要阅读 listBox_DragOver 事件中的 DragEventArgs 以了解拖动操作使用了哪些按钮和键:

        if ((e.KeyState & 32) == 32) { bool alt = true; }
        if ((e.KeyState & 16) == 16) { bool mousebuttonmiddle = true; }
        if ((e.KeyState & 8) == 8) { bool control = true; }
        if ((e.KeyState & 4) == 4) { bool shift = true; }
        if ((e.KeyState & 2) == 2) { bool mousebutton2 = true; }
        if ((e.KeyState & 1) == 1) { bool mousebutton1 = true; }
    

    【讨论】:

      最近更新 更多