Jame O. Weinburgh
Jame O. Weinburgh

Reputation: 67

Why does my application only capture keyevents if its focused?

I am working on a project where I can count the keys that are being pressed and to do so I am using the keydown event.

Here is the issue(s)

1. It only captures the keypress if the application is focused. It doesnt have to be inside the textbox, the textbox is only there to show that its working. How do I make it to where I can ahve it minimized and still capture keys? (In the gif you can see that I am not typing inside the textbox until the end)

  1. How do I make it capture non capitalized letters? Do I just simply convert it?

Here is a gif showing you how its working http://recordit.co/IKubOT0pin

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 testkeydown
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.A)
            {
                textBox.AppendText("A");
            }
        }
    }
}

Upvotes: 0

Views: 168

Answers (2)

Amir Ziarati
Amir Ziarati

Reputation: 15097

The thing you want is referes as keyLogger applications . You must google key looging or key logger.

There are lots of sites that will teach you how to do it. One of them is this:

http://null-byte.wonderhowto.com/how-to/create-simple-hidden-console-keylogger-c-sharp-0132757/

Upvotes: 0

BobbyTables
BobbyTables

Reputation: 4705

The first part: Because the event is an event that the window emits. If you want to capture key-events "globally" you need another approach, for example using hooks, like this answer:

Using global keyboard hook (WH_KEYBOARD_LL) in WPF / C#

The second part: If you want to capture the keys (in the window/application) in their correct capitalization, you can hook up an event on the TextCompositionManager, like so:

    // on load or startup or something, set the handler
    TextCompositionManager.AddTextInputHandler(this,
    new TextCompositionEventHandler(OnTextComposition));


    // then the actual handler
    private void OnTextComposition(object sender, TextCompositionEventArgs e)
    {
        Console.WriteLine(e.Text);
    }

And e.Text will have the actual "letter" thats typed

Upvotes: 1

Related Questions