
In this tutorial, we will look into a common feature that we usually require on a desktop application, using keyboard events and hotkeys. As WPF technology is a little different from Microsoft’s windows forms technology, it might be a little confusing to use this feature in WPF, especially 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:
Let’s first look into generic keyboard event binding on the WPF application. To bind, you can either do it in ‘.xaml’ file or the code behind the C# code file. Let’s see and example of ‘Key Up’ event, which is triggered when a user writes something on a WPF control and releases his finger from a keyboard key. It will trigger for all keyboard keys, so if you want a specific key, you will need it to restrict for processing or not in the handler function.
if you want it to add manually on the design/XAML file, the control code should look as follows:
<TextBox Name="txtTestTextBox" TextWrapping="Wrap" Margin="10,0,0,0" KeyUp="my_text_KeyUp" />
Code language: HTML, XML (xml)
On the other hand, in the code behind C# file, we can add it as follows:
txtTestTextBox.KeyUp += my_text_KeyUp;
The handler code should be something like this and have the “KeyEventArgs” type as the second parameter of the handler function. the 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.
}
}
Code language: JavaScript (javascript)
Binding WPF Hotkeys:
Well, let’s move on a little to implement hotkey. In general, hotkeys are keyboard shortcuts with which we can do certain operation on applications which are usually used most often. These keyboard shortcuts usually come with a modifier key such as Alt, Ctrl etc, with the use of ‘ModifierKeys’ enum. If you don’t need it, you can specify ‘None’ as well. Let’s 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
}
}
Code language: PHP (php)
“RoutedCommand” is the original key setting with which we are willing to bind a specific event. Here we added two different keyboard combinations and thus, two different “RoutedCommand” objects. In the next line, we have specified the key combinations. We have used the ‘Alt’ key as the modifier here, and you can use another or ignore the 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 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");
}
Code language: JavaScript (javascript)
Notice that the first handler has the ‘ExecutedRoutedEventArgs’ as the second parameter, which is specific to this WPF hotkey binding example. On the other hand, the second example takes ‘RoutedEventArgs’ as the second parameter (as its base class) to facilitate binding this event from the mouse click event as well. So, as we may usually have to implement a handler in both ways(mouse click and hokey), it’s important to know the generalized way.
References:
I hope this small tutorial on WPF hotkeys and keyboard event bindings will help you on your way. To learn 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