2013-09-29 104 views
1

我有一個帶有無編號項目和一個contexmenustrip的列表框。我寫了這段代碼(我知道它看起來太原始了,因爲我的不熟練)它工作正常,但我有一個小問題。 當您點擊列表框中的某個項目時,我想讓cms在您的鼠標位置附近打開。當您點擊空白時,它會在之前的位置打開。沒關係,但每次點擊都會重新打開cms。當您點擊空白而不是項目時,是否可以使其保持打開狀態?如何防止contexmenustrip關閉?

 public Form1() 
    { 
     InitializeComponent(); 
    } 
    int a, b, tx, ty; 
    int mx=0; 
     private void listBox1_MouseClick(object sender, MouseEventArgs e) 
    { 
     b = a; 
     a = listBox1.SelectedIndex;   

    if (listBox1.SelectedIndex != -1) 
     {    
      if (a!= b) 
      { 

       contextMenuStrip1.Show(MousePosition.X + 10, MousePosition.Y); 

       tx = MousePosition.X; 
       ty = MousePosition.Y; 
       mx =1; 
      } 
      else if (a==0 && b==0 && mx== 0) 
      { 
       tx = MousePosition.X; 
       ty = MousePosition.Y; 

       contextMenuStrip1.Show(tx + 10, ty); 
       mx = 1; 
      } 
      else 
      { 
       contextMenuStrip1.Show(tx + 10, ty); 
      } 
     }  
    } 

回答

1

使用AutoCloseContextMenuStrip屬性,以防止它自動關閉。

ContextMenuStrip cms = new ContextMenuStrip(); 
cms.AutoClose = false; 

然後調用Close方法來手動關閉它

cms.Close(); 

或處理Closing事件的ContextMenuStrip,並根據您的病情

void cms_Closing(object sender, ToolStripDropDownClosingEventArgs e) 
{ 
    if(your condition) 
    { 
     e.Cancel = true; 
    } 
} 
+0

我創建了一個布爾cmscls設置e.Cancel = true。然後void cms_Closing(object sender,ToolStripDropDownClosingEventArgs e) if(cmscls == false) e.Cancel = true; } }並將cmscls = false添加到last else {}中。它沒有工作。無論如何,我可能會放棄。 – emmett