简体   繁体   中英

Don't show context menu if nothing is selected

I like to have a context menu only show up if an item is actually selected in a listbox in a winforms c# application.

Currently, I am able to select an item if it is right clicked properly, and I can disable the right click menu if nothing is selected, however, I don't want the menu to even show up.

how can this be accomplished?

private void genPassMenu_Opening(object sender, CancelEventArgs e)
    {
        genPassMenu.Enabled = lstPasswords.SelectedIndex > 0;
        genPassMenu.Visible = lstPasswords.SelectedIndex > 0;

    }

I tried both of those situations on their own, and it only works for enabled.
Perhaps Opening isn't the correct event to choose?
Tx

Try this:

private void genPassMenu_Opening(object sender, CancelEventArgs e)
{
    //if (lstPasswords.SelectedIndex == -1) e.Cancel = true;
    e.Cancel = (lstPasswords.SelectedIndex == -1);
}

Easy,

    private void genPassMenu_Opening(object sender, CancelEventArgs e) 
    { 
        e.Cancel = (lstPasswords.SelectedIndex == 0); 

    } 

I typically set the properties of each context menu item according to its appropriateness for the particular GUI element that is selected. Perhaps by setting the visible attribute on each menu item, rather than the whole menu, you can get the results that you want.

private void genPassMenu_Opening(object sender, CancelEventArgs e)
    {
        //genPassMenu.Enabled = lstPasswords.SelectedIndex > 0;
        //genPassMenu.Visible = lstPasswords.SelectedIndex > 0;
        e.Cancel = (lstPasswords.SelectedIndex <= 0);


    }

I saw when the above did hte opposite I reversed the code slightly. For some reason having the equality also didn't work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM