分享如何用C# Button實現下拉菜單
本文為你講解了C# Button下拉菜單實現的思路,步驟及代碼!筆者講述的很清楚,很有條理,實用性很強的。主要的思路還是在于要把ContextMenuStrip控件實例與按鈕關聯,并取消按鈕的右擊事件。
C# Button實現下拉菜單為實現這個功能, 花費的時間太長了, 覺得本人真夠笨. 回過頭來看, 其實很簡單的東西!
在項目中,要用到按鈕實現下拉菜單的功能,而且是在MDI窗體中。當菜單的顯示范疇超出MDI窗體的工做區時,就要換另一顯示方式,不至于顯示混亂。如圖:
實現C# Button下拉菜單
實現C# Button下拉菜單
(發覺一問題,如果把Form1拉到像Form3的大小,還會出現圖一的情況。客戶沒這么邪吧)
C# Button下拉菜單實現思路:
1、要把ContextMenuStrip控件實例與按鈕關聯
2、取得MDI工做區的大小
3、取消按鈕的右擊事件(因為與ContextMenuStrip相關系的控件右鍵都會響應且顯示)
4、鼠標單擊時設置菜單顯示位置
C# Button下拉菜單實現步驟:
1、創建用戶控件,且用戶控件承繼自Button類
2、定義ContextMenuStrip對象
3、定義顯示ContextMenuStrip對象立標point
4、重寫按鈕單擊事件和ContextMenuStrip屬性(設置與之關聯的ContextMenuStrip實例用到),還有重寫鼠標右擊事件,使其不響應任何操做
C# Button下拉菜單代碼:
以上講述了實現C# Button下拉菜單的思路、步驟及代碼,希望能給大家帶來幫助。
- ///
- /// 說明: 使用此Button時要設置ContextMenuStrip屬性值
- /// 單擊些Button的Click事件要傳入所在工做區的寬高
- /// 如果沒有所需的屬性值,則如平時所使用的Button一至
- /// 使用例子:
- /// DropButton.WorkSizeX =
this.MdiParent.ClientRectangle.Width;- /// DropButton.WorkSizeY =
this.MdiParent.ClientRectangle.Height;- /// 應用:
- /// 創建人: lrj
- /// 創建日期:2008-05-22
- /// 修改人:
- /// 修改日期:
- ///
- public partial class DropButton : Button
- {
- private ContextMenuStrip contextMenuStrip;
- private Point point; //立標
- private int x = 0; //立標x
- private int y = 0; //立標y
- private int workSize_x;//工做區x
- private int workSize_y;//工做區y
- public DropButton()
- {
- InitializeComponent();
- x = this.Size.Width ;
- y = 0;
- }
- ///
- /// 工做區的完
- ///
- public int WorkSizeX
- {
- get { return workSize_x; }
- set { workSize_x = value; }
- }
- ///
- /// 工做區的高
- ///
- public int WorkSizeY
- {
- get { return workSize_y; }
- set { workSize_y = value - 55; }
- }
- ///
- /// ContextMenuStrip菜單
- ///
- public override ContextMenuStrip ContextMenuStrip
- {
- get { return contextMenuStrip; }
- set
- {
- if (contextMenuStrip != null)
- {
- contextMenuStrip = value;
- }
- }
- }
- //
- //重寫的單擊事件
- //
- protected override void OnClick(EventArgs e)
- {
- base.OnClick(e);
- //菜單在工做區離邊框的寬高
- int _x = this.Parent.Location.X + this.Location.X +
this.Size.Width + contextMenuStrip.Size.Width;- int _y = this.Parent.Location.Y + this.Location.Y +
contextMenuStrip.Size.Height ;- if
- (_x < WorkSizeX - 8)
- {
- x = this.Size.Width;
- }
- else
- {
- x = 0 - contextMenuStrip.Size.Width;
- }
- if
- (_y < WorkSizeY)
- {
- y = 0;
- }
- else
- {
- y = 0 - contextMenuStrip.Size.Height + this.Size.Height;
- }
- point =
- new Point(x, y);
- contextMenuStrip.Show(this, point);
- }
- //
- //使鼠標右鍵失效
- //
- protected override void OnMouseDown(MouseEventArgs mevent)
- {
- base.OnMouseDown(mevent);
- if (mevent.Button.ToString() != "Right")
- {
- }
- }
- }
【編輯推薦】