I am writing a WPF application which monitors Clipboard changes.
I wrote the following class:
public class ClipboardInterop : IDisposable
{
public event EventHandler ClipboardContentChanged;
private void OnClipboardContentChanged()
{
var handlers = ClipboardContentChanged;
if (handlers != null)
{
handlers(this, new EventArgs());
}
}
public static ClipboardInterop GetClipboardInterop(Window window)
{
var hwndSource = PresentationSource.FromVisual(window) as HwndSource;
if (hwndSource == null) return null;
return new ClipboardInterop(hwndSource);
}
private IntPtr _thisHandle;
private IntPtr _nextHandle;
private HwndSource _hwndSource;
public bool IsListening { get; private set; }
private ClipboardInterop(HwndSource hwndSource)
{
_hwndSource = hwndSource;
_thisHandle = hwndSource.Handle;
IsListening = false;
}
public bool StartViewingClipboard()
{
Win32.SetLastError(0);
_nextHandle = Win32.SetClipboardViewer(_thisHandle);
if (_nextHandle == IntPtr.Zero)
{
UInt32 eCode = Win32.GetLastError();
if (eCode != 0)
{
return false;
}
}
_hwndSource.AddHook(HwndSourceHook);
IsListening = true;
return true;
}
public bool StopViewingClipboard()
{
Win32.SetLastError(0);
Win32.ChangeClipboardChain(_thisHandle, _nextHandle);
UInt32 eCode = Win32.GetLastError();
IsListening = false;
return eCode == 0;
}
private IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
case Win32.WM_CHANGECBCHAIN:
_nextHandle = lParam;
if (_nextHandle != IntPtr.Zero)
{
Win32.SendMessage(_nextHandle, (UInt32)msg, wParam, lParam);
}
break;
case Win32.WM_DRAWCLIPBOARD:
OnClipboardContentChanged();
if (_nextHandle != IntPtr.Zero)
{
Win32.SendMessage(_nextHandle, (UInt32)msg, wParam, lParam);
}
break;
}
return IntPtr.Zero;
}
public void Dispose()
{
if (IsListening)
StopViewingClipboard();
_hwndSource = null;
_nextHandle = IntPtr.Zero;
_thisHandle = IntPtr.Zero;
}
}
Win32.cs looks like:
internal static class Win32
{
/// <summary>
/// The WM_DRAWCLIPBOARD message notifies a clipboard viewer window that
/// the content of the clipboard has changed.
/// </summary>
internal const int WM_DRAWCLIPBOARD = 0x0308;
/// <summary>
/// A clipboard viewer window receives the WM_CHANGECBCHAIN message when
/// another window is removing itself from the clipboard viewer chain.
/// </summary>
internal const int WM_CHANGECBCHAIN = 0x030D;
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetClipboardViewer(
IntPtr hWndNewViewer);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ChangeClipboardChain(
IntPtr hWndRemove,
IntPtr hWndNewNext);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SendMessage(
IntPtr hWnd,
UInt32 msg,
IntPtr wParam,
IntPtr lParam);
[DllImport("kernel32.dll")]
public static extern void SetLastError(
UInt32 errorCode);
[DllImport("kernel32.dll")]
public static extern UInt32 GetLastError();
}
MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
Loaded="MainWindow_OnLoaded">
<Button Content="Toggle" Click="ButtonBase_OnClick"></Button>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
private ClipboardInterop _clipboardInterop;
public MainWindow()
{
InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
_clipboardInterop.StopViewingClipboard();
_clipboardInterop.StartViewingClipboard();
}
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
_clipboardInterop = ClipboardInterop.GetClipboardInterop(this);
_clipboardInterop.StartViewingClipboard();
_clipboardInterop.ClipboardContentChanged +=
(o, args) => Debug.WriteLine(DateTime.Now.ToLongTimeString() + " Content changed");
}
}
So now when I start the application all is fine, the event is fired once when I copy text to the clipboard. When I click the button, and copy text to clipboard again, the event is fired twice. Another button click and the event is fired three times. I don't know why this is happening. Can anybody help me out?
Well I modified my code with the help of this, and obviously I forgot to remove the hook in StopViewingClipboard.
Here's the fixed code:
public class ClipboardInterop : IDisposable
{
public event EventHandler ClipboardContentChanged;
private void OnClipboardContentChanged()
{
var handlers = ClipboardContentChanged;
if (handlers != null)
{
handlers(this, new EventArgs());
}
}
public static ClipboardInterop GetClipboardInterop(Window window)
{
var wih = new WindowInteropHelper(window);
var hwndSource = HwndSource.FromHwnd(wih.Handle);
if (hwndSource == null)
{
return null;
}
return new ClipboardInterop(hwndSource);
}
private IntPtr _hWndNextViewer;
private HwndSource _hWndSource;
public bool IsViewing { get; private set; }
private ClipboardInterop(HwndSource hwndSource)
{
_hWndSource = hwndSource;
IsViewing = false;
}
public bool StartViewingClipboard()
{
Win32.SetLastError(0);
_hWndNextViewer = Win32.SetClipboardViewer(_hWndSource.Handle);
if (_hWndNextViewer == IntPtr.Zero)
{
UInt32 eCode = Win32.GetLastError();
if (eCode != 0)
{
return false;
}
}
_hWndSource.AddHook(WinProc);
IsViewing = true;
return true;
}
public bool StopViewingClipboard()
{
Win32.SetLastError(0);
Win32.ChangeClipboardChain(_hWndSource.Handle, _hWndNextViewer);
_hWndNextViewer = IntPtr.Zero;
_hWndSource.RemoveHook(WinProc);
UInt32 eCode = Win32.GetLastError();
IsViewing = false;
return eCode == 0;
}
private IntPtr WinProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
switch (msg)
{
case Win32.WM_CHANGECBCHAIN:
if (wParam == _hWndNextViewer)
{
_hWndNextViewer = lParam;
}
else if (_hWndNextViewer != IntPtr.Zero)
{
Win32.SendMessage(_hWndNextViewer, msg, wParam, lParam);
}
break;
case Win32.WM_DRAWCLIPBOARD:
OnClipboardContentChanged();
Win32.SendMessage(_hWndNextViewer, msg, wParam, lParam);
break;
}
return IntPtr.Zero;
}
public void Dispose()
{
if (IsViewing)
StopViewingClipboard();
_hWndSource = null;
_hWndNextViewer = IntPtr.Zero;
}
}
Related
I managed using bar-code scanner successfully in my WPF project using a keyboard hook as follows (I skip some details, but basically, I can rely on the fact that I know which keyboard is my scanner).
/// <summary>
/// Add this KeyboardHook to a window
/// </summary>
/// <param name="window">The window to add to</param>
public void AddHook(Window window) {
if (form == null)
throw new ArgumentNullException("window");
if (mHwndSource != null)
throw new InvalidOperationException("Hook already present");
WindowInteropHelper w = new WindowInteropHelper(window);
IntPtr hwnd = w.Handle;
mHwndSource = HwndSource.FromHwnd(hwnd);
if (mHwndSource == null)
throw new ApplicationException("Failed to receive window source");
mHwndSource.AddHook(WndProc);
RAWINPUTDEVICE[] rid = new RAWINPUTDEVICE[1];
rid[0].usUsagePage = 0x01;
rid[0].usUsage = 0x06;
rid[0].dwFlags = RIDEV_INPUTSINK;
rid[0].hwndTarget = hwnd;
if (!RegisterRawInputDevices(rid, (uint)rid.Length, (uint)Marshal.SizeOf(rid[0])))
throw new ApplicationException("Failed to register raw input device(s).");
}
The approach then processes WM_INPUT messages to retrieve information about any keyboard events that occur and handles the event accordingly if it is coming from the Bar-code scanner that is already known.
Now the thing is that in Winforms I should not use hooks but override WndProc as stated here, but I am somehow struggling to understand how I can use WndProc as I need to know:
a) what event I really need to handle in the WndProc method
b) how I can identify the device that fired the event
Any help would be very appreciated!
Cheers!
I ended using the following approach:
public class BarcodeScannedEventArgs : EventArgs {
public BarcodeScannedEventArgs(string text) {
mText = text;
}
public string ScannedText { get { return mText; } }
private readonly string mText;
}
public class BarCodeListener : IDisposable {
DateTime _lastKeystroke = new DateTime(0);
string _barcode = string.Empty;
Form _form;
bool isKeyPreview;
public bool ProcessCmdKey(ref Message msg, Keys keyData) {
bool res = processKey(keyData);
return keyData == Keys.Enter ? res : false;
}
protected bool processKey(Keys key) {
// check timing (>7 keystrokes within 50 ms ending with "return" char)
TimeSpan elapsed = (DateTime.Now - _lastKeystroke);
if (elapsed.TotalMilliseconds > 50) {
_barcode = string.Empty;
}
// record keystroke & timestamp -- do NOT add return at the end of the barcode line
if (key != Keys.Enter) {
_barcode += (char)key;
}
_lastKeystroke = DateTime.Now;
// process barcode only if the return char is entered and the entered barcode is at least 7 digits long.
// This is a "magical" rule working well for EAN-13 and EAN-8, which both have at least 8 digits...
if (key == Keys.Enter && _barcode.Length > 7) {
if (BarCodeScanned != null) {
BarCodeScanned(_form, new BarcodeScannedEventArgs(_barcode));
}
_barcode = string.Empty;
return true;
}
return false;
}
public event EventHandler<BarcodeScannedEventArgs> BarCodeScanned;
public BarCodeListener(Form f) {
_form = f;
isKeyPreview = f.KeyPreview;
// --- set preview and register event...
f.KeyPreview = true;
}
public void Dispose() {
if (_form != null) {
_form.KeyPreview = isKeyPreview;
//_form.KeyPress -= KeyPress_scanner_preview;
}
}
}
}
Then, add the following lines of code to your form which is listening to your scanner:
private BarCodeListener ScannerListener;
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
bool res = false;
if (ScannerListener != null) {
res = ScannerListener.ProcessCmdKey(ref msg, keyData);
}
res = keyData == Keys.Enter ? res : base.ProcessCmdKey(ref msg, keyData);
return res;
}
I post here a piece of code I used for a while before using the above version. It is derived from here, and I didn't re-test. Comes as is, hope it helps anyway...
public BarCodeListener(IntPtr handle) {
SetDeviceHook(handle);
}
public void SetDeviceHook(IntPtr handle) {
if (string.IsNullOrWhiteSpace(LibConst.ScannerDeviceName)) {
return;
}
var hook = new KeyboardHook();
var availableScanners = KeyboardHook.GetKeyboardDevices();
foreach (string s in availableScanners) {
// you need to figure out the device name and put it here!!!!
if (s.Contains("VID_0C2E&PID_0200")) {
hook.SetDeviceFilter(s);
hook.KeyPressed += OnBarcodeKeyWpf;
hook.AddHook(handle);
}
}
}
string InputText;
void OnBarcodeKey(object sender, KeyPressEventArgs e) {
if (this.isInitialisationChar(e.KeyChar.ToString())) {
InputText = String.Empty;
}
else if (this.isTerminationChar(e.KeyChar.ToString())) {
if ((BarCodeScanned != null) && (!string.IsNullOrEmpty(InputText))) {
BarCodeScanned(this, new BarcodeScannedEventArgs(InputText));
InputText = String.Empty;
}
}
else {
InputText += e.KeyChar.ToString();
}
}
void OnBarcodeKeyWpf(object sender, KeyPressedEventArgs e) {
if (this.isInitialisationChar(e.Text)){
InputText = String.Empty;
}
else if (this.isTerminationChar(e.Text)){
if ((BarCodeScanned != null) && (!string.IsNullOrEmpty(InputText))) {
BarCodeScanned(this, new BarcodeScannedEventArgs(InputText));
InputText = String.Empty;
}
}
else{
InputText += e.Text;
}
}
bool isInitialisationChar(string s) {
return string.IsNullOrEmpty(s);
}
bool isTerminationChar(string s) {
return ((s == "\r") || string.IsNullOrEmpty(s));
}
}
public class KeyPressedEventArgs : EventArgs
{
public KeyPressedEventArgs(string text) {
mText = text;
}
public string Text { get { return mText; } }
private readonly string mText;
}
public partial class KeyboardHook
: IDisposable
{
private static readonly Regex DeviceNamePattern = new Regex(#"#([^#]+)");
public event EventHandler<KeyPressedEventArgs> KeyPressed;
/// <summary>
/// Set the device to use in keyboard hook
/// </summary>
/// <param name="deviceId">Name of device</param>
/// <returns>true if device is found</returns>
public bool SetDeviceFilter(string deviceId) {
Dictionary<string, IntPtr> devices = FindAllKeyboardDevices();
return devices.TryGetValue(deviceId, out mHookDeviceId);
}
/// <summary>
/// Add this KeyboardHook to a window
/// </summary>
/// <param name="window">The window to add to</param>
public void AddHook(BaseForm form) {
if (form == null)
throw new ArgumentNullException("window");
if (mHwndSource != null)
throw new InvalidOperationException("Hook already present");
//--- NEG: wpf code:
//WindowInteropHelper w = new WindowInteropHelper(form);
//IntPtr hwnd = w.Handle;
//---
IntPtr hwnd = form.Handle;
mHwndSource = HwndSource.FromHwnd(hwnd);
if (mHwndSource == null)
throw new ApplicationException("Failed to receive window source");
mHwndSource.AddHook(WndProc);
RAWINPUTDEVICE[] rid = new RAWINPUTDEVICE[1];
rid[0].usUsagePage = 0x01;
rid[0].usUsage = 0x06;
rid[0].dwFlags = RIDEV_INPUTSINK;
rid[0].hwndTarget = hwnd;
if (!RegisterRawInputDevices(rid, (uint)rid.Length, (uint)Marshal.SizeOf(rid[0])))
throw new ApplicationException("Failed to register raw input device(s).");
}
/// <summary>
/// Add this KeyboardHook to a window
/// </summary>
/// <param name="window">The window to add to</param>
public void AddHook(IntPtr handle) {
if (handle == null)
throw new ArgumentNullException("window");
if (mHwndSource != null)
throw new InvalidOperationException("Hook already present");
//--- NEG: wpf code:
//WindowInteropHelper w = new WindowInteropHelper(form);
//IntPtr hwnd = w.Handle;
//---
IntPtr hwnd = handle;
mHwndSource = HwndSource.FromHwnd(hwnd);
if (mHwndSource == null)
throw new ApplicationException("Failed to receive window source");
mHwndSource.AddHook(WndProc);
RAWINPUTDEVICE[] rid = new RAWINPUTDEVICE[1];
rid[0].usUsagePage = 0x01;
rid[0].usUsage = 0x06;
rid[0].dwFlags = RIDEV_INPUTSINK;
rid[0].hwndTarget = hwnd;
if (!RegisterRawInputDevices(rid, (uint)rid.Length, (uint)Marshal.SizeOf(rid[0])))
throw new ApplicationException("Failed to register raw input device(s).");
}
/// <summary>
/// Remove this keyboard hook from window (if it is added)
/// </summary>
public void RemoveHook() {
if (mHwndSource == null)
return; // not an error
RAWINPUTDEVICE[] rid = new RAWINPUTDEVICE[1];
rid[0].usUsagePage = 0x01;
rid[0].usUsage = 0x06;
rid[0].dwFlags = 0x00000001;
rid[0].hwndTarget = IntPtr.Zero;
RegisterRawInputDevices(rid, (uint)rid.Length, (uint)Marshal.SizeOf(rid[0]));
mHwndSource.RemoveHook(WndProc);
mHwndSource.Dispose();
mHwndSource = null;
}
public void Dispose() {
RemoveHook();
}
private IntPtr mHookDeviceId;
private HwndSource mHwndSource;
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) {
switch (msg) {
case WM_INPUT:
if (ProcessInputCommand(mHookDeviceId, lParam)) {
MSG message;
PeekMessage(out message, IntPtr.Zero, WM_KEYDOWN, WM_KEYDOWN, PM_REMOVE);
}
break;
}
return IntPtr.Zero;
}
/// <summary>
/// Get a list of keyboard devices available
/// </summary>
/// <returns>Collection of devices available</returns>
public static ICollection<string> GetKeyboardDevices() {
return FindAllKeyboardDevices().Keys;
}
private static Dictionary<string, IntPtr> FindAllKeyboardDevices() {
Dictionary<string, IntPtr> deviceNames = new Dictionary<string, IntPtr>();
uint deviceCount = 0;
int dwSize = (Marshal.SizeOf(typeof(RAWINPUTDEVICELIST)));
if (GetRawInputDeviceList(IntPtr.Zero, ref deviceCount, (uint)dwSize) == 0) {
IntPtr pRawInputDeviceList = Marshal.AllocHGlobal((int)(dwSize*deviceCount));
try {
GetRawInputDeviceList(pRawInputDeviceList, ref deviceCount, (uint)dwSize);
for (int i = 0; i < deviceCount; i++) {
uint pcbSize = 0;
var rid = (RAWINPUTDEVICELIST)Marshal.PtrToStructure(
new IntPtr((pRawInputDeviceList.ToInt32() + (dwSize*i))),
typeof(RAWINPUTDEVICELIST));
GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, IntPtr.Zero, ref pcbSize);
if (pcbSize > 0) {
IntPtr pData = Marshal.AllocHGlobal((int)pcbSize);
try {
GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, pData, ref pcbSize);
string deviceName = Marshal.PtrToStringAnsi(pData);
// The list will include the "root" keyboard and mouse devices
// which appear to be the remote access devices used by Terminal
// Services or the Remote Desktop - we're not interested in these
// so the following code with drop into the next loop iteration
if (deviceName.ToUpper().Contains("ROOT"))
continue;
// If the device is identified as a keyboard or HID device,
// Check if it is the one we're looking for
if (rid.dwType == RIM_TYPEKEYBOARD || rid.dwType == RIM_TYPEHID) {
Match match = DeviceNamePattern.Match(deviceName);
if (match.Success)
deviceNames.Add(match.Groups[1].Value, rid.hDevice);
}
}
finally {
Marshal.FreeHGlobal(pData);
}
}
}
}
finally {
Marshal.FreeHGlobal(pRawInputDeviceList);
}
}
return deviceNames;
}
/// <summary>
/// Processes WM_INPUT messages to retrieve information about any
/// keyboard events that occur.
/// </summary>
/// <param name="deviceId">Device to process</param>
/// <param name="lParam">The WM_INPUT message to process.</param>
private bool ProcessInputCommand(IntPtr deviceId, IntPtr lParam) {
uint dwSize = 0;
try {
// First call to GetRawInputData sets the value of dwSize
// dwSize can then be used to allocate the appropriate amount of memory,
// storing the pointer in "buffer".
GetRawInputData(lParam, RID_INPUT, IntPtr.Zero,ref dwSize, (uint)Marshal.SizeOf(typeof(RAWINPUTHEADER)));
IntPtr buffer = Marshal.AllocHGlobal((int)dwSize);
try {
// Check that buffer points to something, and if so,
// call GetRawInputData again to fill the allocated memory
// with information about the input
if (buffer != IntPtr.Zero &&
GetRawInputData(lParam, RID_INPUT, buffer, ref dwSize, (uint)Marshal.SizeOf(typeof(RAWINPUTHEADER))) == dwSize) {
// Store the message information in "raw", then check
// that the input comes from a keyboard device before
// processing it to raise an appropriate KeyPressed event.
RAWINPUT raw = (RAWINPUT)Marshal.PtrToStructure(buffer, typeof(RAWINPUT));
if (raw.header.hDevice != deviceId)
return false;
if (raw.header.dwType != RIM_TYPEKEYBOARD)
return false;
if (raw.keyboard.Message != WM_KEYDOWN && raw.keyboard.Message != WM_SYSKEYDOWN)
return false;
// On most keyboards, "extended" keys such as the arrow or page
// keys return two codes - the key's own code, and an "extended key" flag, which
// translates to 255. This flag isn't useful to us, so it can be
// disregarded.
if (raw.keyboard.VKey > VK_LAST_KEY)
return false;
if (KeyPressed != null) {
string scannedText = null;
lock (mLocalBuffer) {
if (GetKeyboardState(mKeyboardState)) {
if (ToUnicode(raw.keyboard.VKey, raw.keyboard.MakeCode, mKeyboardState, mLocalBuffer, 64, 0) > 0) {
if (mLocalBuffer.Length > 0) {
scannedText = mLocalBuffer.ToString();
}
}
}
}
if (!string.IsNullOrEmpty(scannedText))
KeyPressed(this, new KeyPressedEventArgs(scannedText));
}
return true;
}
}
finally {
Marshal.FreeHGlobal(buffer);
}
}
catch (Exception e) {
throw new AppException(SCL_Languages.getValue("internalerror"), e.Message, e);
}
return false;
}
private static readonly StringBuilder mLocalBuffer = new StringBuilder(64);
private static readonly byte[] mKeyboardState = new byte[256];
}
public partial class KeyboardHook
{
private const int RIDEV_INPUTSINK = 0x00000100;
private const int RIDEV_REMOVE = 0x00000001;
private const int RID_INPUT = 0x10000003;
private const int FAPPCOMMAND_MASK = 0xF000;
private const int FAPPCOMMAND_MOUSE = 0x8000;
private const int FAPPCOMMAND_OEM = 0x1000;
private const int RIM_TYPEMOUSE = 0;
private const int RIM_TYPEKEYBOARD = 1;
private const int RIM_TYPEHID = 2;
private const int RIDI_DEVICENAME = 0x20000007;
private const int WM_KEYDOWN = 0x0100;
private const int WM_SYSKEYDOWN = 0x0104;
private const int WM_INPUT = 0x00FF;
private const int VK_OEM_CLEAR = 0xFE;
private const int VK_LAST_KEY = VK_OEM_CLEAR; // this is a made up value used as a sentinal
private const int PM_REMOVE = 0x01;
[StructLayout(LayoutKind.Sequential)]
private struct RAWINPUTDEVICELIST
{
public IntPtr hDevice;
[MarshalAs(UnmanagedType.U4)]
public int dwType;
}
[StructLayout(LayoutKind.Explicit)]
private struct RAWINPUT
{
[FieldOffset(0)]
public RAWINPUTHEADER header;
[FieldOffset(16)]
public RAWMOUSE mouse;
[FieldOffset(16)]
public RAWKEYBOARD keyboard;
[FieldOffset(16)]
public RAWHID hid;
}
[StructLayout(LayoutKind.Sequential)]
private struct RAWINPUTHEADER
{
[MarshalAs(UnmanagedType.U4)]
public int dwType;
[MarshalAs(UnmanagedType.U4)]
public int dwSize;
public IntPtr hDevice;
[MarshalAs(UnmanagedType.U4)]
public int wParam;
}
[StructLayout(LayoutKind.Sequential)]
private struct RAWHID
{
[MarshalAs(UnmanagedType.U4)]
public int dwSizHid;
[MarshalAs(UnmanagedType.U4)]
public int dwCount;
}
[StructLayout(LayoutKind.Sequential)]
private struct BUTTONSSTR
{
[MarshalAs(UnmanagedType.U2)]
public ushort usButtonFlags;
[MarshalAs(UnmanagedType.U2)]
public ushort usButtonData;
}
[StructLayout(LayoutKind.Explicit)]
private struct RAWMOUSE
{
[MarshalAs(UnmanagedType.U2)]
[FieldOffset(0)]
public ushort usFlags;
[MarshalAs(UnmanagedType.U4)]
[FieldOffset(4)]
public uint ulButtons;
[FieldOffset(4)]
public BUTTONSSTR buttonsStr;
[MarshalAs(UnmanagedType.U4)]
[FieldOffset(8)]
public uint ulRawButtons;
[FieldOffset(12)]
public int lLastX;
[FieldOffset(16)]
public int lLastY;
[MarshalAs(UnmanagedType.U4)]
[FieldOffset(20)]
public uint ulExtraInformation;
}
[StructLayout(LayoutKind.Sequential)]
private struct RAWKEYBOARD
{
[MarshalAs(UnmanagedType.U2)]
public ushort MakeCode;
[MarshalAs(UnmanagedType.U2)]
public ushort Flags;
[MarshalAs(UnmanagedType.U2)]
public ushort Reserved;
[MarshalAs(UnmanagedType.U2)]
public ushort VKey;
[MarshalAs(UnmanagedType.U4)]
public uint Message;
[MarshalAs(UnmanagedType.U4)]
public uint ExtraInformation;
}
[StructLayout(LayoutKind.Sequential)]
private struct RAWINPUTDEVICE
{
[MarshalAs(UnmanagedType.U2)]
public ushort usUsagePage;
[MarshalAs(UnmanagedType.U2)]
public ushort usUsage;
[MarshalAs(UnmanagedType.U4)]
public int dwFlags;
public IntPtr hwndTarget;
}
[DllImport("User32.dll")]
private static extern uint GetRawInputDeviceList(IntPtr pRawInputDeviceList, ref uint uiNumDevices, uint cbSize);
[DllImport("User32.dll")]
private static extern uint GetRawInputDeviceInfo(IntPtr hDevice, uint uiCommand, IntPtr pData, ref uint pcbSize);
[DllImport("User32.dll")]
private static extern bool RegisterRawInputDevices(RAWINPUTDEVICE[] pRawInputDevice, uint uiNumDevices, uint cbSize);
[DllImport("User32.dll")]
private static extern uint GetRawInputData(IntPtr hRawInput, uint uiCommand, IntPtr pData, ref uint pcbSize, uint cbSizeHeader);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetKeyboardState(byte[] lpKeyState);
[DllImport("user32.dll")]
private static extern int ToUnicode(uint wVirtKey, uint wScanCode, byte[] lpKeyState, [Out, MarshalAs(UnmanagedType.LPWStr, SizeConst = 64)] StringBuilder pwszBuff,
int cchBuff, uint wFlags);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool PeekMessage(out MSG lpmsg, IntPtr hwnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);
I'm using FlashWindowEx() to flash an application window when it needs to attract a user's attention. The window caption and taskbar button flashes continuously until the application receives focus. How can I check whether the application is currently flashing (i.e. has not received focus since it was instructed to flash).
Here are two possible solutions. One uses WH_SHELL, and one uses a NativeWindow. You will have to provide your own extension method (FlashWindow()) to start the flashing.
// base class. Two different forms subclass this form to illustrate two
// different solutions.
public class FormFlash : Form {
protected Label lb = new Label { Text = "Not flashing", Dock = DockStyle.Top };
public FormFlash() {
Controls.Add(lb);
Thread t = new Thread(() => {
Thread.Sleep(3000);
if (Form.ActiveForm == this)
SetForegroundWindow(GetDesktopWindow()); // deactivate the current form by setting the desktop as the foreground window
this.FlashWindow(); // call extension method to flash window
lb.BeginInvoke((Action) delegate {
lb.Text = "Flashing";
});
});
t.IsBackground = true;
t.Start();
}
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern IntPtr GetDesktopWindow();
}
// this solution is a bit simpler. Relies on the programmer knowing when the
// flashing started. Uses a NativeWindow to detect when a WM_ACTIVATEAPP
// message happens, that signals the end of the flashing.
class FormFlashNW : FormFlash {
NW nw = null;
public FormFlashNW() {
}
protected override void OnHandleCreated(EventArgs e) {
base.OnHandleCreated(e);
nw = new NW(this.Handle, lb);
}
protected override void OnHandleDestroyed(EventArgs e) {
base.OnHandleDestroyed(e);
nw.ReleaseHandle();
}
class NW : NativeWindow {
Label lb = null;
public NW(IntPtr handle, Label lb) {
AssignHandle(handle);
this.lb = lb;
}
protected override void WndProc(ref Message m) {
base.WndProc(ref m);
const int WM_ACTIVATEAPP = 0x1C;
if (m.Msg == WM_ACTIVATEAPP) {
lb.BeginInvoke((Action) delegate {
lb.Text = "Not flashing";
});
}
}
}
}
// this solution is more complicated. Relies on setting up the hook proc.
// The 'isFlashing' bool fires true and false alternating while the flashing
// is active.
public class FormShellHook : FormFlash {
public FormShellHook() {
FlashWindowExListener.Register(this);
FlashWindowExListener.FlashEvent += FlashExListener_FlashEvent;
}
void FlashExListener_FlashEvent(Form f, bool isFlashing) {
if (f == this) {
lb.Text = DateTime.Now.ToLongTimeString() + " is flashing: " + isFlashing;
}
}
}
public class FlashWindowExListener {
private delegate IntPtr CallShellProc(int nCode, IntPtr wParam, IntPtr lParam);
private static CallShellProc procShell = new CallShellProc(ShellProc);
private static Dictionary<IntPtr,Form> forms = new Dictionary<IntPtr,Form>();
private static IntPtr hHook = IntPtr.Zero;
public static event FlashWindowExEventHandler FlashEvent = delegate {};
public delegate void FlashWindowExEventHandler(Form f, bool isFlashing);
static FlashWindowExListener() {
int processID = GetCurrentThreadId();
// we are interested in listening to WH_SHELL events, mainly the HSHELL_REDRAW event.
hHook = SetWindowsHookEx(WH_SHELL, procShell, IntPtr.Zero, processID);
System.Windows.Forms.Application.ApplicationExit += delegate {
UnhookWindowsHookEx(hHook);
};
}
public static void Register(Form f) {
if (f.IsDisposed)
throw new ArgumentException("Cannot use disposed form.");
if (f.Handle == IntPtr.Zero) {
f.HandleCreated += delegate {
forms[f.Handle] = f;
};
}
else
forms[f.Handle] = f;
f.HandleDestroyed += delegate {
Unregister(f);
};
}
public static void Unregister(Form f) {
forms.Remove(f.Handle);
}
private static IntPtr ShellProc(int nCode, IntPtr wParam, IntPtr lParam) {
if (nCode == HSHELL_REDRAW) {
Form f = null;
// seems OK not having to call f.BeginInvoke
if (forms.TryGetValue(wParam, out f))
FlashEvent(f, (int) lParam == 1);
}
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
private const int WH_SHELL = 10;
private const int HSHELL_REDRAW = 6;
[DllImport("user32.dll")]
private static extern int UnhookWindowsHookEx(IntPtr idHook);
[DllImport("user32.dll")]
private static extern IntPtr SetWindowsHookEx(int idHook, CallShellProc lpfn, IntPtr hInstance, int threadId);
[DllImport("kernel32.dll")]
private static extern int GetCurrentThreadId();
[DllImport("user32.dll")]
private static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
}
I want to add a possibility to type Cyrillic letters in my XNA-game.
I can't use default Input.KeyboardState because Input.Keys enum contains only English letters. So, I used keyboard-hook to handle Windows input. But it returns keycode, which can be used for English letters (because ASCII-code matches key-code), but don't work properly with Cyrillic. For "a-я" can be used 848 offset, but for more specific letters, like "і" or "ї" there are different values.
Is there efficient way to convert key-code into Cyrillic letter in ASCII? Or maybe there is solution without nasty keyboard-hook?
BTW, here keyboard-hook class listing:
#region EventArgs
public class CharacterEventArgs : EventArgs
{
private readonly char character;
private readonly int lParam;
private readonly int keyLayout;
public CharacterEventArgs(char character, int lParam, int keyLayout)
{
this.character = character;
this.lParam = lParam;
this.keyLayout = keyLayout;
}
#region Properties
public int KeyLayout
{
get { return keyLayout; }
}
public char Character
{
get { return character; }
}
public int Param
{
get { return lParam; }
}
public int RepeatCount
{
get { return lParam & 0xffff; }
}
public bool ExtendedKey
{
get { return (lParam & (1 << 24)) > 0; }
}
public bool AltPressed
{
get { return (lParam & (1 << 29)) > 0; }
}
public bool PreviousState
{
get { return (lParam & (1 << 30)) > 0; }
}
public bool TransitionState
{
get { return (lParam & (1 << 31)) > 0; }
}
#endregion
}
public class KeyEventArgs : EventArgs
{
private Keys keyCode;
public KeyEventArgs(Keys keyCode)
{
this.keyCode = keyCode;
}
public Keys KeyCode
{
get { return keyCode; }
}
}
#endregion
#region delegats
public delegate void CharEnteredHandler(object sender, CharacterEventArgs e);
public delegate void KeyEventHandler(object sender, KeyEventArgs e);
#endregion
public static class EventInput
{
#region events
/// <summary>
/// Event raised when a character has been entered.
/// </summary>
public static event CharEnteredHandler CharEntered;
/// <summary>
/// Event raised when a key has been pressed down. May fire multiple times due to keyboard repeat.
/// </summary>
public static event KeyEventHandler KeyDown;
/// <summary>
/// Event raised when a key has been released.
/// </summary>
public static event KeyEventHandler KeyUp;
#endregion
delegate IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
static bool initialized;
static IntPtr prevWndProc;
static WndProc hookProcDelegate;
static IntPtr hIMC;
static GameWindow gameWindow;
#region constants
const int GWL_WNDPROC = -4;
const int WM_KEYDOWN = 0x100;
const int WM_KEYUP = 0x101;
const int WM_CHAR = 0x102;
const int WM_IME_SETCONTEXT = 0x0281;
const int WM_INPUTLANGCHANGE = 0x51;
const int WM_GETDLGCODE = 0x87;
const int WM_IME_COMPOSITION = 0x10f;
const int DLGC_WANTALLKEYS = 4;
#endregion
#region Win32-functions
//to handle input
[DllImport("Imm32.dll")]
static extern IntPtr ImmGetContext(IntPtr hWnd);
[DllImport("Imm32.dll")]
static extern IntPtr ImmAssociateContext(IntPtr hWnd, IntPtr hIMC);
[DllImport("user32.dll")]
static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
//to get keyboard layout
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowThreadProcessId(
[In] IntPtr hWnd,
[Out, Optional] IntPtr lpdwProcessId
);
[DllImport("user32.dll", SetLastError = true)]
static extern ushort GetKeyboardLayout(
[In] int idThread
);
#endregion
static ushort GetKeyboardLayout()
{
return GetKeyboardLayout(GetWindowThreadProcessId(gameWindow.Handle, IntPtr.Zero));
}
#region Initialize
/// <summary>
/// Initialize the TextInput with the given GameWindow.
/// </summary>
/// <param name="window">The XNA window to which text input should be linked.</param>
public static void Initialize(GameWindow window)
{
if (initialized)
throw new InvalidOperationException("TextInput.Initialize can only be called once!");
gameWindow = window;
hookProcDelegate = new WndProc(HookProc);
prevWndProc = (IntPtr)SetWindowLong(window.Handle, GWL_WNDPROC,
(int)Marshal.GetFunctionPointerForDelegate(hookProcDelegate));
hIMC = ImmGetContext(window.Handle);
initialized = true;
}
#endregion
static IntPtr HookProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
IntPtr returnCode = CallWindowProc(prevWndProc, hWnd, msg, wParam, lParam);
switch (msg)
{
case WM_GETDLGCODE:
returnCode = (IntPtr)(returnCode.ToInt32() | DLGC_WANTALLKEYS);
break;
case WM_KEYDOWN:
if (KeyDown != null)
KeyDown(null, new KeyEventArgs((Keys)wParam));
break;
case WM_KEYUP:
if (KeyUp != null)
KeyUp(null, new KeyEventArgs((Keys)wParam));
break;
case WM_CHAR:
if (CharEntered != null)
{
CharEntered(null, new CharacterEventArgs((char) wParam, lParam.ToInt32(), GetKeyboardLayout()));
}
break;
case WM_IME_SETCONTEXT:
if (wParam.ToInt32() == 1)
ImmAssociateContext(hWnd, hIMC);
break;
case WM_INPUTLANGCHANGE:
ImmAssociateContext(hWnd, hIMC);
returnCode = (IntPtr)1;
break;
}
return returnCode;
}
}
Have you considered using Windows Forms for character input? I don't speak Russian, but I can only assume that the KeyPress event must handle Cyrillic correctly in Russian locales, and it would be much simpler than pumping Windows messages yourself.
using System.Windows.Forms;
...
var form = (Form)Form.FromHandle(window.Handle);
form.KeyPress += form_KeyPress;
...
private void form_KeyPress(Object sender, KeyPressEventArgs e)
{
Console.WriteLine(e.KeyChar);
e.Handled = true;
}
Here is keyboard hook code:
class globalKeyboardHook
{
#region Constant, Structure and Delegate Definitions
public delegate int keyboardHookProc(int code, int wParam, ref keyboardHookStruct lParam);
public static keyboardHookProc callbackDelegate;
public struct keyboardHookStruct
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;
}
const int WH_KEYBOARD_LL = 13;
const int WM_KEYDOWN = 0x100;
const int WM_KEYUP = 0x101;
const int WM_SYSKEYDOWN = 0x104;
const int WM_SYSKEYUP = 0x105;
#endregion
#region Instance Variables
public List<Keys> HookedKeys = new List<Keys>();
private static IntPtr hhook = IntPtr.Zero;
#endregion
#region Events
public event KeyEventHandler KeyDown;
public event KeyEventHandler KeyUp;
#endregion
#region Constructors and Destructors
public globalKeyboardHook()
{
hook();
GC.KeepAlive(callbackDelegate);
}
~globalKeyboardHook()
{
unhook();
}
#endregion
#region Public Methods
public void hook()
{
IntPtr hInstance = LoadLibrary("User32");
callbackDelegate = new keyboardHookProc(hookProc);
hhook = SetWindowsHookEx(WH_KEYBOARD_LL, callbackDelegate, hInstance, 0);
if (hhook == IntPtr.Zero) throw new Win32Exception();
}
public void unhook()
{
bool ok = UnhookWindowsHookEx(hhook);
if (!ok) throw new Win32Exception();
callbackDelegate = null;
}
public int hookProc(int code, int wParam, ref keyboardHookStruct lParam)
{
if (code >= 0)
{
Keys key = (Keys)lParam.vkCode;
if (HookedKeys.Contains(key))
{
KeyEventArgs kea = new KeyEventArgs(key);
if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && (KeyDown != null))
{
KeyDown(this, kea);
}
else if ((wParam == WM_KEYUP || wParam == WM_SYSKEYUP) && (KeyUp != null))
{
KeyUp(this, kea);
}
if (kea.Handled)
return 1;
}
}
return CallNextHookEx(hhook, code, wParam, ref lParam); // Exception on this line
}
#endregion
#region DLL imports
[DllImport("user32.dll")]
static extern IntPtr SetWindowsHookEx(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);
[DllImport("user32.dll")]
static extern bool UnhookWindowsHookEx(IntPtr hInstance);
[DllImport("user32.dll")]
static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref keyboardHookStruct lParam);
[DllImport("kernel32.dll")]
static extern IntPtr LoadLibrary(string lpFileName);
#endregion
}
When I initialize it in Child Form constructor first nothing happens, you can press all you want but nothing gets to event:
private globalKeyboardHook kh = new globalKeyboardHook();
public FrmMainForm(FrmVideo owner)
{
InitializeComponent();
_videoForm = owner;
try
{
_videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (_videoDevices.Count == 0)
{
throw new ApplicationException();
}
foreach (FilterInfo device in _videoDevices)
{
camerasCombo.Items.Add(device.Name);
}
camerasCombo.SelectedIndex = 1;
}
catch (ApplicationException)
{
camerasCombo.Items.Add("No local capture devices");
_videoDevices = null;
}
kh.KeyUp += new KeyEventHandler(kh_KeyUp);
kh.hook();
}
void kh_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F12)
_videoForm.TakeOver = !_videoForm.TakeOver;
if (e.KeyCode == Keys.Escape)
Application.Exit();
}
Until I call piece of Aforge code for capturing from webcam, this starts streaming on Parent form:
var videoSource = new VideoCaptureDevice(_videoDevices[camerasCombo.SelectedIndex].MonikerString)
{
DesiredFrameSize = new Size(Globals.FrameWidth, Globals.FrameHeight),
DesiredFrameRate = 12
};
if (videoSource != null)
{
_videoForm.Device = videoSource;
_videoForm.Start();
button1.Enabled = false;
}
After that on any keypress I get:
CallbackOnCollectedDelegate was detected on return next hook, any ideas?
Oh, and I am unhooking on dispose of form:
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
kh.unhook();
base.Dispose(disposing);
}
This requires psychic debugging and infer something you didn't document. The oddity is that the MDA is triggered when you call CallNextHookEx(). Which is somewhat strange, the callback to your hook procedure actually worked. That delegate object wasn't collected. It is the next hook procedure call that failed.
There's a simple explanation for that: you called SetWindowsHookEx() more than once. Now using a static variable to store the delegate object will seriously bite, as static variables usually do, it is capable of storing only one delegate object. The second time you call hook(), it will overwrite the delegate of the first hook and it is thus no longer prevented from getting garbage collected. Which indeed triggers the MDA on the CallNextHookEx() since that will call the hook procedure for the first hook.
So your hook() method needs to be improved to this:
public void hook()
{
if (callbackDelegate != null)
throw new InvalidOperationException("Cannot hook more than once");
// etc..
}
It is actually not illegal to hook more than once, Windows doesn't mind. Just don't declare the variable static.
I have a swf inside a html page. If I open it with IE or FF and put it into full screen I can exit full screen with the ESC button.
Now if i try this with my WinForms app and WebBrowser (or ShockWave Flash Object) it's not working??
Any ideas?
I know it's late but Ctrl + W does the trick for me
As outlined here there is a problem with Windows Forms' ActiveX container support. The keyboard message does not get passed to the Flash player.
The solution I've come up with (based on code from here) is to write a keyboard hook to catch the Escape key and to pass a message to the Flash window to close if it's active.
First, there's the KeyHook class which provides the plumbing to listen for the Escape key.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Your.Utility
{
public class KeyBordHook
{
private const int WM_KEYDOWN = 0x100;
private const int WM_KEYUP = 0x101;
private const int WM_SYSKEYDOWN = 0x104;
private const int WM_SYSKEYUP = 0x105;
//Global event
public event KeyEventHandler OnKeyDownEvent;
public event KeyEventHandler OnKeyUpEvent;
public event KeyPressEventHandler OnKeyPressEvent;
private static int hKeyboardHook = 0;
private const int WH_KEYBOARD_LL = 13; //keyboard hook constant
private HookProc KeyboardHookProcedure; // declare keyhook event type
//declare keyhook struct
[StructLayout(LayoutKind.Sequential)]
public class KeyboardHookStruct
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;
}
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern bool UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
[DllImport("user32")]
private static extern int ToAscii(int uVirtKey, int uScanCode, byte[] lpbKeyState, byte[] lpwTransKey, int fuState);
[DllImport("user32")]
private static extern int GetKeyboardState(byte[] pbKeyState);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
private delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
private List<Keys> preKeys = new List<Keys>();
public KeyBordHook()
{
Start();
}
~KeyBordHook()
{
Stop();
}
public void Start()
{
//install keyboard hook
if (hKeyboardHook == 0)
{
KeyboardHookProcedure = new HookProc(KeyboardHookProc);
//hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().GetModules()[0]), 0);
Process curProcess = Process.GetCurrentProcess();
ProcessModule curModule = curProcess.MainModule;
hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, GetModuleHandle(curModule.ModuleName), 0);
if (hKeyboardHook == 0)
{
Stop();
throw new Exception("SetWindowsHookEx ist failed.");
}
}
}
public void Stop()
{
bool retKeyboard = true;
if (hKeyboardHook != 0)
{
retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
hKeyboardHook = 0;
}
//if unhook failed
if (!(retKeyboard)) throw new Exception("UnhookWindowsHookEx failed.");
}
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
if ((nCode >= 0) && (OnKeyDownEvent != null || OnKeyUpEvent != null || OnKeyPressEvent != null))
{
KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
if ((OnKeyDownEvent != null || OnKeyPressEvent != null) && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
{
Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
if (IsCtrlAltShiftKeys(keyData) && preKeys.IndexOf(keyData) == -1)
{
preKeys.Add(keyData);
}
}
if (OnKeyDownEvent != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
{
Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
KeyEventArgs e = new KeyEventArgs(GetDownKeys(keyData));
OnKeyDownEvent(this, e);
}
if (OnKeyPressEvent != null && wParam == WM_KEYDOWN)
{
byte[] keyState = new byte[256];
GetKeyboardState(keyState);
byte[] inBuffer = new byte[2];
if (ToAscii(MyKeyboardHookStruct.vkCode,
MyKeyboardHookStruct.scanCode,
keyState,
inBuffer,
MyKeyboardHookStruct.flags) == 1)
{
KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]);
OnKeyPressEvent(this, e);
}
}
if ((OnKeyDownEvent != null || OnKeyPressEvent != null) && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
{
Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
if (IsCtrlAltShiftKeys(keyData))
{
for (int i = preKeys.Count - 1; i >= 0; i--)
{
if (preKeys[i] == keyData)
{
preKeys.RemoveAt(i);
}
}
}
}
if (OnKeyUpEvent != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
{
Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
KeyEventArgs e = new KeyEventArgs(GetDownKeys(keyData));
OnKeyUpEvent(this, e);
}
}
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}
private Keys GetDownKeys(Keys key)
{
Keys rtnKey = Keys.None;
foreach (Keys keyTemp in preKeys)
{
switch (keyTemp)
{
case Keys.LControlKey:
case Keys.RControlKey:
rtnKey = rtnKey | Keys.Control;
break;
case Keys.LMenu:
case Keys.RMenu:
rtnKey = rtnKey | Keys.Alt;
break;
case Keys.LShiftKey:
case Keys.RShiftKey:
rtnKey = rtnKey | Keys.Shift;
break;
default:
break;
}
}
rtnKey = rtnKey | key;
return rtnKey;
}
private Boolean IsCtrlAltShiftKeys(Keys key)
{
switch (key)
{
case Keys.LControlKey:
case Keys.RControlKey:
case Keys.LMenu:
case Keys.RMenu:
case Keys.LShiftKey:
case Keys.RShiftKey:
return true;
default:
return false;
}
}
}
}
Next, you need to create an instance of the KeyHook class in your Windows Form ...
// inside Form class ...
private readonly KeyBordHook _keyBordHook = new KeyBordHook();
private void InitKeyHook()
{
_keyBordHook.OnKeyPressEvent += new KeyPressEventHandler(_KeyBordHook_OnKeyPressEvent);
_keyBordHook.Start();
}
void _KeyBordHook_OnKeyPressEvent(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == Convert.ToChar(Keys.Escape))
WindowHelper.CloseWindowIfActive("Flash");
}
public void StartKeyListening()
{
InitKeyHook();
}
public void StopKeyListening()
{
_keyBordHook.Stop();
}
And, the code to actually close the Flash Window...
public sealed class WindowHelper
{
[DllImport("USER32.dll", SetLastError = true)]
private static extern IntPtr GetForegroundWindow();
[DllImport("USER32.dll", SetLastError = true)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
static uint WM_CLOSE = 0x10;
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("USER32.dll", SetLastError = true)]
static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
private static bool CloseWindow(IntPtr hWnd)
{
bool returnValue = PostMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
if (!returnValue)
throw new Win32Exception(Marshal.GetLastWin32Error());
return true;
}
public static void CloseWindowIfActive(string windowTitle)
{
const int nChars = 256;
StringBuilder buff = new StringBuilder(nChars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, buff, nChars) <= 0) return;
if (buff.ToString().ToLower().IndexOf(windowTitle.ToLower()) > -1)
CloseWindow(handle);
}
}
I'm sure there's improvements to be made in all of the above but so far, this solution appears to work for me.
Note that this code allows you to record all key strokes across all apps so it's definitely overkill and may not be desirable to integrate into a customer bound application!
Did you try F11? That's the default for IE.