2014-11-20 76 views
1

我有下面的代码中,我试图实现一个拖放功能:的DragDrop和dragEnter事件射击两次

public Location_Alert() 
    { 
     InitializeComponent(); 
     #region Form Initialization 
     Recur_Txt.Text = "1"; 
     End_Date.Value = Start_Date.Value.Add(new TimeSpan(1,0,0,0)); 
     Recur_Time_Txt.Text = DateTime.Now.Add(new TimeSpan(0,15,0)).ToString("HH:mm"); 
     Location_Alert_Timer.Tick += new EventHandler(Location_Alert_Timer_Tick);//allow for timed recurrences in code 
     this.DragEnter += new DragEventHandler(Location_Alert_DragEnter);//set up monitoring for a Drag event, changing the cursor as users drags file(s) onto the form. 
     this.DragDrop +=new DragEventHandler(Location_Alert_DragDrop);//set up monitoring for a Drop event, allowing user to drag file onto the form 
     #endregion 
    } 

    private void Location_Alert_DragDrop(object sender, DragEventArgs e) 
    { 
     string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); 
     if (files.Length == 1) 
     { 
      int i = 0; 
      int ii = -1; 
      foreach(string file in files) 
      { 
       if (file.Contains("enot")) 
       { 
        if (ii == -1) 
        { 
         ii = i; 
        } 
       } 
       i++; 
      } 
      ImportFile(files[ii]); 
     } 
     else 
     { 
      MessageBox.Show("This application only supports a single drag and drop file, only the first *.enot file will be imported."); 
      int i = 0; 
      int ii = -1; 
      foreach (string file in files) 
      { 
       if (file.Contains("enot")) 
       { 
        if (ii == -1) 
        { 
         ii = i; 
        } 
       } 
       i++; 
      } 
      ImportFile(files[ii]); 
     } 
    } 

    private void Location_Alert_DragEnter(object sender, DragEventArgs e) 
    { 
     if (e.Data.GetDataPresent(DataFormats.FileDrop)) 
     { 
      int i = 0; 
      int ii = -1; 
      string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); 
      foreach (string file in files) 
      { 
       if (file.Contains("enot")) 
       { 
        if (ii == -1) 
        { 
         ii = i; 
        } 
       } 
       i++; 
      } 
      if (ii != -1) 
      { 
       e.Effect = DragDropEffects.Copy; 
      } 
      else 
      { 
       e.Effect = DragDropEffects.None; 
      } 
     } 
    } 

和的DragDrop和的dragenter事件总是激发两次。我的蜱虫事件没有,我不确定这背后的原因。除非用户遇到异常,否则额外的火灾不会引起问题。这将处理异常两次,在这种情况下意味着将2个消息框返回给用户。

+3

有没有机会让事件连线两次?一旦来自设计师,一旦在构造函数中?尝试评论构造函数的线路,看看它是否仍然有效。 – LarsTech 2014-11-20 22:42:49

回答

1

@LarsTech有答案:事件构造函数是在我的设计器视图以及我的窗体构造函数中声明的。

1

即使dragEnter被调用了两次,dragDrop总是被调用一次,如果你在dragEnter中放入e.Effect = DragDropEffects.Copy。

private void Location_Alert_DragDrop(object sender, DragEventArgs e) 
{ 
    ToDo(); 
} 
private void Location_Alert_DragEnter(object sender, DragEventArgs e) 
{ 
    e.Effect = DragDropEffects.Copy; 
}