Поделиться через


DragEventArgs.KeyState Свойство

Определение

Возвращает текущее состояние клавиш SHIFT, CTRL и ALT, а также состояние кнопок мыши.

public:
 property int KeyState { int get(); };
public int KeyState { get; }
member this.KeyState : int
Public ReadOnly Property KeyState As Integer

Значение свойства

Текущее состояние клавиш SHIFT, CTRL и ALT и кнопок мыши.

Примеры

В следующем примере демонстрируется операция перетаскивания между двумя ListBox элементами управления. В примере вызывается DoDragDrop метод при запуске действия перетаскивания. Действие перетаскивания начинается, если мышь перемещена больше, чем SystemInformation.DragSize из расположения мыши во время MouseDown события. Метод IndexFromPoint используется для определения индекса элемента для перетаскивания во время MouseDown события.

В примере также показано использование пользовательских курсоров для операции перетаскивания. В примере предполагается, что два файла 3dwarro.cur курсора и 3dwno.cur, существующие в каталоге приложения, для пользовательских курсоров перетаскивания и без перетаскивания соответственно. Настраиваемые курсоры будут использоваться UseCustomCursorsCheckCheckBox при проверке. Пользовательские курсоры задаются в обработчике GiveFeedback событий.

Состояние клавиатуры вычисляется в DragOver обработчике событий справа ListBox, чтобы определить, какая операция перетаскивания будет основываться на состоянии клавиш SHIFT, CTRL, ALT или CTRL+ALT. Расположение в месте, где ListBox будет происходить удаление, также определяется во время DragOver события. Если данные, которые нужно удалить, не Stringявляется, DragEventArgs.Effect то для нее задано DragDropEffects.Noneзначение . Наконец, в списке DropLocationLabelLabelотображается состояние удаления.

Данные, которые нужно удалить справаListBox, определяются в DragDrop обработчике событий, а String значение добавляется в соответствующее место в .ListBox Если операция перетаскивания перемещается за пределы формы, операция перетаскивания отменяется в обработчике QueryContinueDrag событий.

Этот фрагмент кода демонстрирует использование DragEventArgs класса. См. DoDragDrop метод для полного примера кода.

void ListDragTarget_DragOver( Object^ /*sender*/, System::Windows::Forms::DragEventArgs^ e )
{
   // Determine whether string data exists in the drop data. If not, then
   // the drop effect reflects that the drop cannot occur.
   if (  !e->Data->GetDataPresent( System::String::typeid ) )
   {
      e->Effect = DragDropEffects::None;
      DropLocationLabel->Text = "None - no string data.";
      return;
   }

   // Set the effect based upon the KeyState.
   if ( (e->KeyState & (8 + 32)) == (8 + 32) && ((e->AllowedEffect & DragDropEffects::Link) == DragDropEffects::Link) )
   {
      // KeyState 8 + 32 = CTRL + ALT
      // Link drag-and-drop effect.
      e->Effect = DragDropEffects::Link;
   }
   else
   if ( (e->KeyState & 32) == 32 && ((e->AllowedEffect & DragDropEffects::Link) == DragDropEffects::Link) )
   {
      // ALT KeyState for link.
      e->Effect = DragDropEffects::Link;
   }
   else
   if ( (e->KeyState & 4) == 4 && ((e->AllowedEffect & DragDropEffects::Move) == DragDropEffects::Move) )
   {
      // SHIFT KeyState for move.
      e->Effect = DragDropEffects::Move;
   }
   else
   if ( (e->KeyState & 8) == 8 && ((e->AllowedEffect & DragDropEffects::Copy) == DragDropEffects::Copy) )
   {
      // CTRL KeyState for copy.
      e->Effect = DragDropEffects::Copy;
   }
   else
   if ( (e->AllowedEffect & DragDropEffects::Move) == DragDropEffects::Move )
   {
      // By default, the drop action should be move, if allowed.
      e->Effect = DragDropEffects::Move;
   }
   else
            e->Effect = DragDropEffects::None;





   
   // Get the index of the item the mouse is below.
   // The mouse locations are relative to the screen, so they must be
   // converted to client coordinates.
   indexOfItemUnderMouseToDrop = ListDragTarget->IndexFromPoint( ListDragTarget->PointToClient( Point(e->X,e->Y) ) );
   
   // Updates the label text.
   if ( indexOfItemUnderMouseToDrop != ListBox::NoMatches )
   {
      DropLocationLabel->Text = String::Concat( "Drops before item # ", (indexOfItemUnderMouseToDrop + 1) );
   }
   else
            DropLocationLabel->Text = "Drops at the end.";
}
private void ListDragTarget_DragOver(object sender, DragEventArgs e)
{
    // Determine whether string data exists in the drop data. If not, then
    // the drop effect reflects that the drop cannot occur.
    if (!e.Data.GetDataPresent(typeof(System.String)))
    {
        e.Effect = DragDropEffects.None;
        DropLocationLabel.Text = "None - no string data.";
        return;
    }

    // Set the effect based upon the KeyState.
    if ((e.KeyState & (8 + 32)) == (8 + 32) &&
        (e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link)
    {
        // KeyState 8 + 32 = CTRL + ALT

        // Link drag-and-drop effect.
        e.Effect = DragDropEffects.Link;
    }
    else if ((e.KeyState & 32) == 32 &&
        (e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link)
    {
        // ALT KeyState for link.
        e.Effect = DragDropEffects.Link;
    }
    else if ((e.KeyState & 4) == 4 &&
        (e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move)
    {
        // SHIFT KeyState for move.
        e.Effect = DragDropEffects.Move;
    }
    else if ((e.KeyState & 8) == 8 &&
        (e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
    {
        // CTRL KeyState for copy.
        e.Effect = DragDropEffects.Copy;
    }
    else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move)
    {
        // By default, the drop action should be move, if allowed.
        e.Effect = DragDropEffects.Move;
    }
    else
    {
        e.Effect = DragDropEffects.None;
    }

    // Get the index of the item the mouse is below. 

    // The mouse locations are relative to the screen, so they must be 
    // converted to client coordinates.

    indexOfItemUnderMouseToDrop =
        ListDragTarget.IndexFromPoint(ListDragTarget.PointToClient(new Point(e.X, e.Y)));

    // Updates the label text.
    if (indexOfItemUnderMouseToDrop != ListBox.NoMatches)
    {
        DropLocationLabel.Text = "Drops before item #" + (indexOfItemUnderMouseToDrop + 1);
    }
    else
    {
        DropLocationLabel.Text = "Drops at the end.";
    }
}
Private Sub ListDragTarget_DragOver(ByVal sender As Object, ByVal e As DragEventArgs) Handles ListDragTarget.DragOver
    ' Determine whether string data exists in the drop data. If not, then
    ' the drop effect reflects that the drop cannot occur.
    If Not (e.Data.GetDataPresent(GetType(System.String))) Then

        e.Effect = DragDropEffects.None
        DropLocationLabel.Text = "None - no string data."
        Return
    End If

    ' Set the effect based upon the KeyState.
    If ((e.KeyState And (8 + 32)) = (8 + 32) And
        (e.AllowedEffect And DragDropEffects.Link) = DragDropEffects.Link) Then
        ' KeyState 8 + 32 = CTRL + ALT

        ' Link drag-and-drop effect.
        e.Effect = DragDropEffects.Link

    ElseIf ((e.KeyState And 32) = 32 And
        (e.AllowedEffect And DragDropEffects.Link) = DragDropEffects.Link) Then

        ' ALT KeyState for link.
        e.Effect = DragDropEffects.Link

    ElseIf ((e.KeyState And 4) = 4 And
        (e.AllowedEffect And DragDropEffects.Move) = DragDropEffects.Move) Then

        ' SHIFT KeyState for move.
        e.Effect = DragDropEffects.Move

    ElseIf ((e.KeyState And 8) = 8 And
        (e.AllowedEffect And DragDropEffects.Copy) = DragDropEffects.Copy) Then

        ' CTRL KeyState for copy.
        e.Effect = DragDropEffects.Copy

    ElseIf ((e.AllowedEffect And DragDropEffects.Move) = DragDropEffects.Move) Then

        ' By default, the drop action should be move, if allowed.
        e.Effect = DragDropEffects.Move

    Else
        e.Effect = DragDropEffects.None
    End If

    ' Gets the index of the item the mouse is below. 

    ' The mouse locations are relative to the screen, so they must be 
    ' converted to client coordinates.

    indexOfItemUnderMouseToDrop =
        ListDragTarget.IndexFromPoint(ListDragTarget.PointToClient(New Point(e.X, e.Y)))

    ' Updates the label text.
    If (indexOfItemUnderMouseToDrop <> ListBox.NoMatches) Then
        DropLocationLabel.Text = "Drops before item #" & (indexOfItemUnderMouseToDrop + 1)
    Else
        DropLocationLabel.Text = "Drops at the end."
    End If

End Sub

Комментарии

Вы можете сделать эффект операции перетаскивания, чтобы зависеть от состояния определенного ключа. Например, вы можете скопировать или переместить данные в зависимости от того, нажимаются ли клавиши CTRL или SHIFT во время операции перетаскивания.

Биты, заданные в свойстве KeyState , определяют ключи или кнопки мыши, которые были нажаты во время операции. Например, если нажата левая кнопка мыши, задается первый бит свойства KeyState . Для проверки заданного состояния ключа можно использовать побитовый оператор AND.

В следующей таблице перечислены значения, используемые для указанного события.

Ценность Ключ
1 (бит 0) Левая кнопка мыши.
2 (бит 1) Правая кнопка мыши.
4 (бит 2) Клавиша SHIFT.
8 (бит 3) Клавиша CTRL.
16 (бит 4) Средняя кнопка мыши.
32 (бит 5) Клавиша ALT.

Применяется к