In this tutorial, we will look into a common features that we usually require on a desktop application, using keyboard events and hotkey. As WPF technology is a little different from Microsoft’s windows forms technology, it might be a little confusing using this feature in WPF, specially for beginners with WPF application development. We will look into some c# code examples also to get wpf hotkey and keyboard events ready to go. I am assuming you know WPF basics more or less.
Binding Keyboard Event:
Lets first look into generic keyboard event binding on WPF application. To bind, you can either do in ‘.xaml’ file or in the code behind C# code file. lets see and example of ‘Key Up’ event, which is triggered when a user write something on a wpf control and release his finger from a keyboard key. It will trigger for all keyboard keys, so if you want for a specific key, you will need it to restrict for processing or not in the handler function.
if you want it add manually on design/xaml file, the control code should look like as follows:
<TextBox Name="txtTestTextBox" TextWrapping="Wrap" Margin="10,0,0,0" KeyUp="my_text_KeyUp" />
On the other hand, in code behind c# file, we can add it as follows:
txtTestTextBox.KeyUp += my_text_KeyUp;
The handler code should be something like this and it should have the “KeyEventArgs” type as the second parameter of the handler function. visual studio however can add it automatically for you as well.
private void my_text_KeyUp(object sender, KeyEventArgs e) { //handler codes go here as needed. if (e.Key == Key.Enter) { //do something if 'enter' key is pressed. } }
Binding WPF Hotkeys:
Well, lets move on a little to implement hotkey. In general, hotkey are keyboard shortcut with which we can do some certain operation on application which are usually used most often. This keyboard shortcuts usually comes with a modifier key such as Alt, Ctrl etc, with use of ‘ModifierKeys’ enum. If you don’t need it, you can specify ‘None’ as well. lets see an example c# function which binds two hotkey events:
private void AddHotKeys() { try { RoutedCommand firstSettings = new RoutedCommand(); firstSettings.InputGestures.Add(new KeyGesture(Key.A, ModifierKeys.Alt)); CommandBindings.Add(new CommandBinding(firstSettings , My_first_event_handler)); RoutedCommand secondSettings = new RoutedCommand(); secondSettings.InputGestures.Add(new KeyGesture(Key.B, ModifierKeys.Alt)); CommandBindings.Add(new CommandBinding(secondSettings , My_second_event_handler)); } catch (Exception err) { //handle exception error } }
“RoutedCommand” is the original key settings, witch which we are willing to bind a specific event. Here we added two different keyboard combination and thus two different “RoutedCommand” object. On the next line, we have specified the key combinations. We have used the ‘Alt’ key as the modifier here, you can use another or ignore modifier key as per your requirement.
‘CommandBindings’ is a built-in public property which contains “CommandBindingCollection” list and we can just add our settings there and it will be processed in run-time. Here we also specify the event handler where we want the event need to be triggered.
Here is simple handler functions for the above bindings;
private void My_first_event_handler(object sender, ExecutedRoutedEventArgs e) { //handler code goes here. MessageBox.Show("Alt+A key pressed"); } private void My_second_event_handler(object sender, RoutedEventArgs e) { //handler code goes here. MessageBox.Show("Alt+B key pressed"); }
Notice that, firs handler has the ‘ExecutedRoutedEventArgs’ as second parameter which is specific to this wpf hotkey binding examples. On the other hand, second example takes ‘RoutedEventArgs’ as second parameter (as its base class) to facilitate to bind this event from mouse click event as well. So, as we may usually have to implement to execute a handler in both ways(mouse click and hokey), its important to know the generalized way.
References:
Hope this small tutorial on wpf hotkeys and keyboard event bindings will help you on your way. To know more about wpf events, you can go to official msdn reference . Stay in touch. Happy coding 🙂
Hi, My name is Ricardo,
I’m trying to implement your code.
I’m using Telerik Suite in the xaml side, the problem is that the compiler does not accept the RoutedCommand for the ‘firstSettings’ instance creation, it shows me an error like this:
Telerik:Windows.Controls.RoutedCommand.RoutedCommand() is inaccessible due to its protection level.
Maybe you have any suggestions for this error?
Thanks in advance and sorry about my english.
Thanks Ali, it was very helpful!
Best Regards.
How to assign VS2010 like keybinding like Ctrl+W,J ? That is pressing Ctrl + W and then pressing J while keeping Ctrl+W pressed to view Object browser.
i used this for dynamic shorcut key and modifier
System.Windows.Controls.Label SKey = new System.Windows.Controls.Label();
SKey.Content = Convert.ToString(dr[“ShortCutKey”]);
SKey.Margin = new Thickness(460, -117, 0, 0);
SKey.Visibility = Visibility.Collapsed;
System.Windows.Controls.Label Modif = new System.Windows.Controls.Label();
Modif.Content = Convert.ToString(dr[“Modifier”]);
Modif.Margin = new Thickness(460, -117, 0, 0);
Modif.Visibility = Visibility.Collapsed;
KeyConverter k = new KeyConverter();
Key Bindkey = (Key)k.ConvertFromString(dr[“ShortCutKey”].ToString());
ModifierKeysConverter m = new ModifierKeysConverter();
ModifierKeys mkey = (ModifierKeys)m.ConvertFromString(dr[“Modifier”].ToString());
RoutedCommand firstSettings = new RoutedCommand();
firstSettings.InputGestures.Add(new KeyGesture(Bindkey, mkey));
CommandBindings.Add(new CommandBinding(firstSettings, ShortCutKey));
SP.Children.Add(IMG);
SP.Children.Add(TB);
SP.Children.Add(LblWn);
SP.Children.Add(Lblparam);
SP.Children.Add(DtPk);
SP.Children.Add(LblFormType);
SP.Children.Add(SKey);
SP.Children.Add(Modif);
private void ShortCutKey(object sender, ExecutedRoutedEventArgs e)
{
DateTime datetime;
string s = “”;
Key key=Key.None;
Common co = new Common();
CommonToAll cta = new CommonToAll();
var allPossibleKeys = Enum.GetValues(typeof(Key));
bool results = false;
foreach (var currentKey in allPossibleKeys)
{
key =(Key)currentKey;
if (key != Key.None)
if (Keyboard.IsKeyDown((Key)currentKey)) { results = true;break; }
}
if (Keyboard.Modifiers == ModifierKeys.Control)
{
co.CommonId = “Control”;
}
if (Keyboard.Modifiers == ModifierKeys.Alt)
{
co.CommonId = “Alt”;
}
co.Path = serverpathCIn();
co.DefaultStockType =Convert.ToString(key);
//if (co.CommonId == “Alt” && key.ToString()==”F4″)
//{
// int processid=0;
// Menu2 m = new Menu2(processid);
// m.Focus();
//}
using (DataTable dt = cta.MenuMasterSelectOnKey(co))
{
if(dt.Rows.Count>0)
{
DataRow dr1 = dt.Rows[0] as DataRow;
s = dr1[“Parameter”].ToString();
string form = dr1[“FormName”].ToString();
string formtype = dr1[“FormType”].ToString();
if (Convert.ToString(formtype) == “2”)
{
int processid = BusyIndProcess.BusyIndSatrt();
if (Convert.ToString(s) == “”)
{
s = “01-01-2000” + “,” + Convert.ToString(processid); ;
}
else
{
s = Convert.ToString(s) + “,” + “01-01-2000” + “,” + Convert.ToString(processid);
}
}
else
{
s = Convert.ToString(s);
}
if (s == “”)
{
Window wn = (Window)Activator.CreateInstance(Type.GetType(form.Trim()));
wn.Owner = this;
wn.Show();
wn.Focus();
}
else
{
string[] sl = s.Split(‘,’);
int count = Convert.ToInt32(sl.Length);
//MessageBox.Show(count.ToString ());
int[] s1 = new int[99];
string[] s2 = new string[99];
string str = “”;
int c = 0;
object[] mxz1 = new object[count];
foreach (string p in s.Split(‘,’))
{
int tem;
if (int.TryParse(p, out tem))
{
s1[c] = Convert.ToInt32(p);
str += “I”;
}
else
{
s2[c] = Convert.ToString(p);
str += “S”;
}
c++;
}
for (int j = 0; j <= str.Length – 1; j++)
{
foreach (char w in str.Substring(j, 1))
{
if (w.ToString() == "I")
{
mxz1[j] = Convert.ToInt32(s1[j]);
//MessageBox .Show (mxz1[j].ToString ());
}
else if (w.ToString() == "S")
{
mxz1[j] = s2[j];
//MessageBox.Show(mxz1[j].ToString());
}
}
}
Window wn = (Window)Activator.CreateInstance(Type.GetType(Convert.ToString(form)),mxz1);
wn.Owner = this;
wn.Show();
wn.Focus();
}
}
}
}
Ado.Net
public DataTable MenuMasterSelectOnKey(Common co)
{
using (SqlConnection con = new SqlConnection(co.Path))
{
con.Open();
using (SqlCommand cmd1 = con.CreateCommand())
{
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.CommandText = “MenuMasterSelectOnShortCutKeyandModifiers”;
cmd1.Parameters.AddWithValue(“@ShortCutKey”, co.DefaultStockType);
cmd1.Parameters.AddWithValue(“@Modifier”, co.CommonId);
using (SqlDataAdapter ad1 = new SqlDataAdapter(cmd1))
{
using (DataTable dt1 = new DataTable(“MenuMaster”))
{
ad1.Fill(dt1);
con.Close();
return dt1;
}
}
}
}
}
i used upper code for binding shartcutkeys with modifier
1.in the first comment i bind that code with radtreeview sorry gys i share half code only,
its really work
How to Restricted Alt + Tab ,Ctrl ,win key when Web Browser open in c# wpf windows