Nella risposta precedente ti ho portato a conoscenza di RawInput.dll
L'esempio è basato su WindowsForm, mentre tu stai lavorando in WPF. Una finestra WPF non ha un Handle, bisogna crearlo, il seguente codice crea l'Handle alla finestra WPF corrente, e tre label mostrano i tasti premuti e da quale tastiera.
Dovrai crearti la tua RawInput.dll, copiarla nella cartella del tuo progetto e aggiungerla ai riferimenti.
Codice test in WPF, da incollare in MainWindow.xaml.cs:
using System;
using System.Windows;
using RawInput_dll;
using System.Windows.Interop;
using System.Diagnostics;
using System.Globalization;
namespace TastiereWPF
{
/// <summary>
/// Logica di interazione per MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private readonly RawInput _rawinput; // instance
const bool CaptureOnlyInForeground = false;
public MainWindow()
{
InitializeComponent();
// create handle to current WPF Window (this)
IntPtr windowHandle = new WindowInteropHelper(this).EnsureHandle();
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
_rawinput = new RawInput(windowHandle, CaptureOnlyInForeground);
_rawinput.AddMessageFilter(); // Adding a message filter will cause keypresses to be handled
Win32.DeviceAudit(); // Writes a file DeviceAudit.txt to the current directory
_rawinput.KeyPressed += OnKeyPressed; // add event
}
private void OnKeyPressed(object sender, RawInputEventArg e)
{
label1.Content = "ASCII " + e.KeyPressEvent.VKey.ToString(CultureInfo.InvariantCulture);
label2.Content = "Tasto " + e.KeyPressEvent.VKeyName;
label3.Content = e.KeyPressEvent.Source;
}
private static void CurrentDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
{
var ex = e.ExceptionObject as Exception;
if (null == ex) return;
// Log this error. Logging the exception doesn't correct the problem but at least now
// you may have more insight as to why the exception is being thrown.
Debug.WriteLine("Unhandled Exception: " + ex.Message);
Debug.WriteLine("Unhandled Exception: " + ex);
MessageBox.Show(ex.Message);
}
}
}