[英]Reorder toolStrip items within the same toolStrip without holding the ALT Key pressed in C# VS 2008
我有一個toolStrip1放在C#中的Form(System.Windows.Forms)上,並添加了五個toolStrip按鈕。 現在我想知道如何讓用戶通過將它們拖動到toolStrip1中的其他位置來重新排序這些按鈕。 我在文章中建議將toolStrip1.AllowItemReorder設置為true ,將AllowDrop設置為false 。
現在應該在toolStrip1中啟用項目重新排序的自動處理。 但它不起作用 - 只有按住ALT-Key,toolStrip1才會對用戶的重新排序嘗試作出反應。 我是否真的要處理DragEvent,DragEnter,DragLeave本身以避免在重新排序項目時按住Alt鍵?
如果是這樣的話,請舉例說明如果我想在toolStrip1中的不同位置拖動一個項目而不保留任何ALT鍵(如Internet Explorer收藏夾),這個事件在toolStrip上的工具是什么樣的。 我對此事沒有經驗。
好吧,你可能不得不使用這個有點hacky的解決方案。 整個想法是你必須按代碼按住Alt鍵 。 我已嘗試使用MouseDown
事件(即使在PreFilterMessage handler
)但它失敗了。 唯一的事件適合在觸發時按住Alt鍵是MouseEnter
。 您必須為所有ToolStripItems
注冊MouseEnter
事件處理程序,當鼠標離開其中一個項目時,您必須在MouseLeave
事件處理程序中釋放Alt鍵。 釋放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
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.