2013-09-27 16 views
0

我在C#中的Form(System.Windows.Forms)上放置了too​​lStrip1,並向其中添加了五個toolStrip按鈕。現在我想知道如何讓用戶通過在toolStrip1中的其他位置上拖動它們來重新排序這些按鈕。正如微軟在文章中所建議的那樣,我將toolStrip1.AllowItemReorder設置爲trueAllowDrop爲假在同一toolStrip中重新排序ToolStrip項目,而無需按住C#中的ALT鍵2008 VS

現在應該可以在toolStrip1中自動處理物品重新排序。但它不起作用 - 只有當我按住ALT鍵時,toolStrip1纔會響應用戶的重新排序嘗試。 我真的要處理DragEvent,DragEnter,DragLeave我自己,以避免在重新排序項目過程中保持Alt鍵嗎?

如果是這樣,請給我舉一個例子,如果這個事件看起來像toolStripButtons的toolStrip,如果我想在toolStrip1中的一個不同位置上拖動一個項目而不需要保存任何ALT鍵(比如Internet Explorer收藏夾一樣)。我在這件事上沒有經驗。

回答

2

那麼,你可能不得不使用這個有點冒險的解決方案。整個想法是你必須按按住Alt鍵碼。我試過用MouseDown事件(即使在PreFilterMessage handler),但它失敗了。唯一的事件是適合於在觸發時按住Alt鍵爲MouseEnter。您必須爲所有ToolStripItems註冊MouseEnter事件處理程序,當鼠標離開其中一個項目時,必須在MouseLeave事件處理程序中釋放Alt項。在替代鍵發佈後,我們必須發送ESC鍵以使表單處於活動狀態(否則,即使在控制按鈕上,包括Minimize, Maximize, Close在內,所有懸停效果似乎都被忽略)。下面是可用的代碼:

public partial class Form1 : Form { 
    [DllImport("user32.dll", SetLastError = true)] 
    static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo); 
    public Form1(){ 
    InitializeComponent(); 
    //Register event handlers for all the toolstripitems initially 
    foreach (ToolStripItem item in toolStrip1.Items){ 
     item.MouseEnter += itemsMouseEnter; 
     item.MouseLeave += itemsMouseLeave; 
    } 
    //We have to do this if we add/remove some toolstripitem at runtime 
    //Otherwise we don't need the following code 
    toolStrip1.ItemAdded += (s,e) => { 
     item.MouseEnter += itemsMouseEnter; 
     item.MouseLeave += itemsMouseLeave; 
    }; 
    toolStrip1.ItemRemoved += (s,e) => { 
     item.MouseEnter -= itemsMouseEnter; 
     item.MouseLeave -= itemsMouseLeave; 
    }; 
    } 
    bool pressedAlt; 
    private void itemsMouseEnter(object sender, EventArgs e){ 
     if (!pressedAlt) { 
      //Hold the Alt key 
      keybd_event(0x12, 0, 0, 0);//VK_ALT = 0x12 
      pressedAlt = true; 
     } 
    } 
    private void itemsMouseLeave(object sender, EventArgs e){ 
     if (pressedAlt){ 
      //Release the Alt key 
      keybd_event(0x12, 0, 2, 0);//flags = 2 -> Release the key 
      pressedAlt = false; 
      SendKeys.Send("ESC");//Do this to make the GUI active again 
     }    
    } 
}