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