Search code examples
c#keypress

I am trying to get keystroke in C# wpf but it's not working. Is my code wrong?


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace clipper
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public void HandleKeyDownEvent(object sender, KeyEventArgs e)
        {
            MessageBox.Show("It came here");

            if (e.Key == Key.LeftCtrl && e.Key == Key.C)
            {
                MessageBox.Show("You have pressed control + c");
            }
        }
    }
}

So this is my code. I've tried googling the solution for keyPress event and I implemented it here. But as I am new to C#, I am not sure what went wrong. Please guide me.


Solution

  • you have to change KeyPreview to true and can you try e.Modifiers event. It may helps..

    private void Form1_Load(object sender, EventArgs e)
    {
        KeyPreview = true;
    }
    
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Modifiers == (Keys.Shift | Keys.Control))
        {
            MessageBox.Show(".");
        }
    }