简体   繁体   中英

Window Forms shortcut key using C#

I'm building a Windows Forms application where I have a menuStrip and a toolStripMenuItem called 'Preferences', that is self-explanatory for opening a preferences form.

The problem is that I have bound the shortcut key for that item to Ctrl + P which opens the printer dialog, which I assume is defaulted in all Windows Forms forms.

Is there any way to disable that the printer dialog overwrites my shortkey?

When naming the "Preferences" menu item, just put an ampersand ( & ) in front of the P . You'll end up with Alt instead of Ctrl for your shortcut key, but Visual Studio will wire everything up for you.

There is no default wiring in a Windows Forms application that intercepts the Ctrl + P shortcut and brings up a print dialog. If you have a print command in a menu on your form, that menu item might have the Ctrl + P configured as shortcut key and if that is the case, one of them will need to get some other shortcut key.

I do however question whether the user would bring up the preferences dialog so often that the command actually needs a shortcut key. I would probably just use access keys instead and let the print function keep Ctrl + P . That would conform to how many other applications work as well.

There is no automatic opening of a print dialog box with Ctrl + P because Windows has no way of knowing what you want to print on a generic form. However, I have tested this just to make sure and I am not getting the same problem. I think you probably have a print option somewhere, either in the menu or a toolbar. If you are supposed to be able to print from that form, then you should reassign one of them a new shortcut key or get rid of the Preferences shortcut key, as it is probably used infrequently (unless there is a reason other than "Preferences begins with a 'P'" for you to have Ctrl + P be the shortcut, you should probably change the Preferences shortcut).

Other answers suggest putting an ampersand in front of the P so the shortcut will be Alt + P . This works only if the preferences option is on the top level. If the preferences menu item is inside the File menu or the Tools menu, this won't work (instead, you will need to press Alt and the top-level menu access key, folowed by the P to open preferences); you'll need to change the regular shortcut key. You can still change the shortcut key to Alt + P in the shortcut key proprety.

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