C# • Handle Events

Listing 3. It isn't enough to be able to drag and drop information. You must be able to handle the events created when you perform these actions. This code shows you how to handle the DragEnter and DragDrop events when they fire.

[FlagsAttribute]
enum KeyPushed
{
   // Corresponds to DragEventArgs.KeyState values
   LeftMouse = 1,
   RightMouse = 2,
   ShiftKey = 4,
   CtrlKey = 8,
   MiddleMouse = 16,
   AltKey = 32,
}

private void TeamA_DragEnter(object sender, DragEventArgs e)
{
   KeyPushed kp = (KeyPushed) e.KeyState;
   // Make sure data type is string
   if (e.Data.GetDataPresent(typeof(string)))
   {
      // Only accept drag with left mouse key
      if ( (kp & KeyPushed.LeftMouse) == KeyPushed.LeftMouse) 
      {
         if ((kp & KeyPushed.CtrlKey) == 
            KeyPushed.CtrlKey)
         {
            e.Effect = DragDropEffects.Copy; // Copy
         }
         else 
         {
            e.Effect = DragDropEffects.Move; // Move 
         }
      }
      else // Is not left mouse key
      {
      e.Effect = DragDropEffects.None;
   }
   } else // Is not a string
   {
      e.Effect = DragDropEffects.None;
   }
}
// Handle DragDrop event

private void TeamA_Drop(object sender, DragEventArgs e)
{
   // Add dropped data to TextBox
   lstTeamA.Items.Add( 
      (string) e.Data.GetData(DataFormats.Text));
}