views:

49

answers:

3

I have a dialog with a number of Alt-Letter shortcuts on labels for textboxes/etc. This dialog can present data in either an editable or a read-only mode. I've received a request to hide the underlines for the shortcuts if the dialog is in read only mode. Other than editing the label text at runtime (ugh) is there any way to remove them?

If you don't know what I'm referring to by alt-Letter shortcuts see this question.

A: 

You could try setting the KeyPreview property of the form to True and then add a handler for the form's KeyDown event. If the keypress is one of the shortcut keys then set the Handled property of the KeyEventArgs parameter to true. Or you can set the .SuppressKeyPress property of the KeyEventArgs variable to true.

You can check the .Alt property of the KeyEventArgs variable to make sure the Alt key is pressed at the same time.

TLiebe
+2  A: 

If you change the value of the UseMnemonic property, then the ampersand shows up in the label, so I'm not sure how you're going to be able to remove the underlines without changing the label.

Jacob G
+2  A: 

You could just iterate the controls and remove the ampersands. For example:

public partial class dlgSample : Form {
    public dlgSample(bool isReadOnly) {
        InitializeComponent();
        if (isReadOnly) ZapMnemonics(this.Controls);
    }

    private void ZapMnemonics(Control.ControlCollection ctls) {
        foreach (Control ctl in ctls) {
            if (ctl is Label || ctl is Button) ctl.Text = ctl.Text.Replace("&", "");
            ZapMnemonics(ctl.Controls);
        }
    }
}
Hans Passant
I believe the problem isn't removing them, it's putting them *back* afterward.
Jon Seigel
Easy: recreate the dialog.
Hans Passant
@Jon S: That's only a problem if the dialog can change from Read Only to Edit mode without being recreated. If so, he could keep a list of the original labels. Clumsy though.
Charles
@nobugz Thanks but the last thing I want is to give myself CM problems the first time I forget to make the same change to both dialogs.
Dan Neely
What the heck is a "CM problem"? What change? It's just a bit of code.
Hans Passant
@Jon Seigel There aren't any cases where I'd need to restore them, I was just hoping for a less ugly looking implementation than recursively walking the Controls property to hunt down and stomp on each label individually.
Dan Neely
JaredPar
@nobugs CM = Configuration Management. If I created MyDialogEditable and MyDialogReadOnly, then every time I had to change the data displayed I'd need to remember to make the change in two places. It's copy/paste code at the class level.
Dan Neely
@Dan: you missed the point: this is ONE dialog that does both. Note the constructor argument. Use it as a base class of your real dialogs, if you have to.
Hans Passant
@nobugz Sorry, I got confused and thought your "recreate the dialog" comment was a suggestion for an alternate implementation approach, not simply a reply to Jon S.
Dan Neely