WinForms TabControl拖放问题

时间:2011-02-21 20:42:00

标签: c# .net winforms tabcontrol

我有两个TabControls,我已经实现了在两个控件之间拖放tabpages的功能。它可以很好地工作,直到您从其中一个控件拖出最后一个标签页。然后控件停止接受丢弃,我不能将任何标签页放回该控件上。

一个方向的拖放代码如下。反方向与交换的控件名称相同。

// Source TabControl
private void tabControl1_MouseMove(object sender, MouseEventArgs e)
{
  if (e.Button == MouseButtons.Left) 
    this.tabControl1.DoDragDrop(this.tabControl1.SelectedTab, DragDropEffects.All);
}

//Target TabControl 
private void tabControl2_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
  if (e.Data.GetDataPresent(typeof(TabPage))) 
    e.Effect = DragDropEffects.Move;
  else 
    e.Effect = DragDropEffects.None; 
} 

private void tabControl2_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) 
{
  TabPage DropTab = (TabPage)(e.Data.GetData(typeof(TabPage))); 
  if (tabControl2.SelectedTab != DropTab)
    this.tabControl2.TabPages.Add (DropTab); 
}

1 个答案:

答案 0 :(得分:5)

您需要覆盖TabControl中的WndProc,并在HTTRANSPARENT消息中将HTCLIENT转为WM_NCHITTEST

例如:

const int WM_NCHITTEST = 0x0084;
const int HTTRANSPARENT = -1;
const int HTCLIENT = 1;

//The default hit-test for a TabControl's
//background is HTTRANSPARENT, preventing
//me from receiving mouse and drag events
//over the background.  I catch this and 
//replace HTTRANSPARENT with HTCLIENT to 
//allow the user to drag over us when we 
//have no TabPages.
protected override void WndProc(ref Message m) {
    base.WndProc(ref m);
    if (m.Msg == WM_NCHITTEST) {
        if (m.Result.ToInt32() == HTTRANSPARENT)
            m.Result = new IntPtr(HTCLIENT);
    }
}