Click here to Skip to main content
15,905,322 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to use shortcut key for button in my winform application.
like "ctrl S" FOR Search Button

What I have tried:

i have used ..
if ((e.Control && e.KeyCode == Keys.S))
{
btnSearch.Focus();
}
..in this when i press button ctrl S + enter ..then its working ,but I dont want to press key enter after press enter,i want to use only ctrl S and it should be working.please tell me solution for this
Posted
Updated 30-Dec-17 20:21pm

First off, CTRL+S shouldn't be "Search" - the Windows convention for CTRL+S is "Save" and swapping that around is a bad idea - it confuses users. The convention for "Search" is CTRL+F or F3

The simplest way to add a shortcut is to use the designer: Highlight your button and look at the Properties pane. Select the Text property, and add an ampersand in front of the letter you want to use: "&Save" will set ALT+S as the shortcut.
Unfortunately this only works for ALT+key combinations.

For CTRL+key you need to do two things:
1) Set the Form.KeyPreview property to true.
2) Override ProcessCmdKey:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
    KeyEventArgs e = new KeyEventArgs(keyData);
    if (e.Control && e.KeyCode == Keys.F)
        {
        DoSearch();  // Your method here.
        return true; // Handled - prevent it being passed down the chain as well.
        }
    return base.ProcessCmdKey(ref msg, keyData);
    }
 
Share this answer
 
Comments
Member 13275563 31-Dec-17 2:09am    
ok thanks..
but in Code
what is this method ......DoSearch();
Member 13275563 31-Dec-17 2:10am    
i have not yet use any method for this..
OriginalGriff 31-Dec-17 4:14am    
:sigh:
Write a method to do your search.
Call it "DoSearch" and call that from the ProcessCmdKey and your button.

You shouldn't do much in event handler methods except call public / private methods to do the actual work - it's easier to reuse code that way and "cleans up" the handler code.
Add a ContextMenuStrip (ctxFrom) with a ToolStripMenuItem (miFind) using the formdesigner.
Use propertygrid to set miFind ShortcutKeys property and a click-eventhandler (calling search).
Set forms ContextMenuStrip-property to ctxForm.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900