• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Development / How To Use Hotkeys/Keyboard Events In WPF Application Using C#

How To Use Hotkeys/Keyboard Events In WPF Application Using C#

January 17, 2013 by Rana Ahsan 7 Comments

WPF Hotkeys Tutorials

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 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Development Tagged With: .net, c#, wpf

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. Ricardo says

    August 23, 2013 at 8:14 am

    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.

    Reply
  2. Willian says

    December 12, 2014 at 8:15 am

    Thanks Ali, it was very helpful!

    Best Regards.

    Reply
  3. Anjum S Khan says

    May 25, 2015 at 12:12 am

    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.

    Reply
  4. sarfaraz akhtar says

    March 28, 2018 at 12:58 am

    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();
    }
    }
    }
    }

    Reply
  5. sarfaraz akhtar says

    March 28, 2018 at 1:04 am

    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;
    }
    }
    }
    }
    }

    Reply
  6. sarfaraz akhtar says

    March 28, 2018 at 1:21 am

    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

    Reply
    • pravat says

      May 21, 2020 at 9:04 am

      How to Restricted Alt + Tab ,Ctrl ,win key when Web Browser open in c# wpf windows

      Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application
  • Getting Started With UDP Programming in Java
    Getting Started With UDP Programming in Java
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023