I encounter a problem to make my Office Addin works with my global keyboard on Powerpoint 2013 but not on the previous versions (2007 and 2010).
I do not get any exception but it seems that the OnKeyDown event is never triggered on Powerpoint 2013, and I don't know why.
I get the same problems on all versions of Windows (XP, 7, 8 & 8.1), on 32 & 64 bits environments. The version of Microsoft Office is 32 bits.
Here is a code sample :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Office = Microsoft.Office.Core;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace testHook
{
public partial class ThisAddIn
{
Hook hook;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
hook = new Hook(Hook.HookType.KeyBoard, Hook.HookVisibility.Global);
hook.OnKeyDown += new KeyEventHandler(hook_OnKeyDown);
hook.Start();
}
void hook_OnKeyDown(object sender, KeyEventArgs e)
{
MessageBox.Show(e.KeyCode.ToString());
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
hook.Stop();
hook = null;
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
class Hook
{
private IntPtr m_Hook = (IntPtr)0;
private HookVisibility m_Visibility;
private HookType m_HookType;
private HookProc m_Proc;
public enum HookType { KeyBoard };
public enum KeyBoardEventType { KeyDown, KeyUp, SysKeyDown, SysKeyUp, KeyShift, KeyCapital, NumLock };
public enum HookVisibility { Global, Local };
private delegate IntPtr HookProc(int nCode, int wParam, IntPtr lParam);
private KeyPressEventHandler m_onKeyPress;
private KeyEventHandler m_onKeyUp;
private KeyEventHandler m_onKeyDown;
public event KeyPressEventHandler OnKeyPress
{
add
{
m_onKeyPress += value;
}
remove
{
m_onKeyPress -= value;
}
}
public event KeyEventHandler OnKeyUp
{
add
{
m_onKeyUp += value;
}
remove
{
m_onKeyUp -= value;
}
}
public event KeyEventHandler OnKeyDown
{
add
{
m_onKeyDown += value;
}
remove
{
m_onKeyDown -= value;
}
}
#region DLLImport
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hmod, int dwThreadId);
[DllImport("user32.dll")]
private static extern IntPtr CallNextHookEx(IntPtr hHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern bool UnhookWindowsHookEx(IntPtr hHook);
[DllImport("Kernel32.dll", SetLastError = true)]
private static extern IntPtr GetModuleHandle(IntPtr lpModuleName);
[DllImport("Kernel32.dll", SetLastError = true)]
private static extern IntPtr GetModuleHandle(String lpModuleName);
[DllImport("Kernel32.dll")]
private static extern IntPtr GetCurrentThreadId();
[DllImport("user32")]
private static extern int ToAscii(int uVirtKey, int uScanCode, byte[] lpbKeyState, byte[] lpwTransKey, int fuState);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern short GetKeyState(int vKey);
[DllImport("user32")]
private static extern int GetKeyboardState(byte[] pbKeyState);
#endregion
[StructLayout(LayoutKind.Sequential)]
private class KeyboardHookStruct
{
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;
}
public Hook(HookType H, HookVisibility H2)
{
m_HookType = H;
m_Visibility = H2;
}
public bool Start()
{
if (m_HookType == HookType.KeyBoard)
m_Proc = new HookProc(KeyProc);
if (m_Visibility == HookVisibility.Global)
m_Hook = SetWindowsHookEx(getHookType(m_HookType, m_Visibility), m_Proc, GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName), 0);
else if (m_Visibility == HookVisibility.Local)
m_Hook = SetWindowsHookEx(getHookType(m_HookType, m_Visibility), m_Proc, GetModuleHandle((IntPtr)0), (int)GetCurrentThreadId());
if (m_Hook == (IntPtr)0)
return false;
return true;
}
public bool Stop()
{
return UnhookWindowsHookEx(m_Hook);
}
private int getHookType(HookType H, HookVisibility V)
{
if (H == HookType.KeyBoard && V == HookVisibility.Local)
return 2;
if (H == HookType.KeyBoard && V == HookVisibility.Global)
return 13;
else return -1;
}
private int getKeyBoardEventType(KeyBoardEventType K)
{
if (K == KeyBoardEventType.KeyDown)
return 0x100;
if (K == KeyBoardEventType.KeyUp)
return 0x101;
if (K == KeyBoardEventType.SysKeyDown)
return 0x104;
if (K == KeyBoardEventType.SysKeyUp)
return 0x105;
if (K == KeyBoardEventType.KeyShift)
return 0x10;
if (K == KeyBoardEventType.KeyCapital)
return 0x14;
if (K == KeyBoardEventType.NumLock)
return 0x90;
else return -1;
}
private IntPtr KeyProc(int nCode, int wParam, IntPtr lParam)
{
bool handled = false;
if ((nCode >= 0) && (m_onKeyDown != null || m_onKeyUp != null || m_onKeyPress != null))
{
KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
if (m_onKeyDown != null && (wParam == 0x100 || wParam == 0x104))
{
Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
KeyEventArgs e = new KeyEventArgs(keyData);
m_onKeyDown(this, e);
handled = handled || e.Handled;
}
if (m_onKeyPress != null && wParam == 0x100)
{
bool isShift = ((GetKeyState(0x10) & 0x80) == 0x80 ? true : false);
bool isCapslock = (GetKeyState(0x14) != 0 ? true : false);
byte[] keyState = new byte[256];
GetKeyboardState(keyState);
byte[] inBuffer = new byte[2];
if (ToAscii(MyKeyboardHookStruct.vkCode, MyKeyboardHookStruct.scanCode, keyState, inBuffer, MyKeyboardHookStruct.flags) == 1)
{
char key = (char)inBuffer[0];
if ((isCapslock ^ isShift) && Char.IsLetter(key))
key = Char.ToUpper(key);
KeyPressEventArgs e = new KeyPressEventArgs(key);
m_onKeyPress(this, e);
handled = handled || e.Handled;
}
}
if (m_onKeyUp != null && (wParam == 0x101 || wParam == 0x105))
{
Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
KeyEventArgs e = new KeyEventArgs(keyData);
m_onKeyUp(this, e);
handled = handled || e.Handled;
}
}
if (handled)
return (IntPtr)1;
else
return CallNextHookEx(m_Hook, nCode, (IntPtr)wParam, (IntPtr)lParam);
}
}
}
My application need to fire events during the slideshow because I have some others windows which are displayed during the presentation, and I have to update them according to the keys that the user presses. I have tried a lot of solutions but the hook is the only one that can do perfectly the job.
I tried too a local keyboard hook instead of a global one. I actually think that it is the only way to make it works because it is a bug from Microsoft, and not from the code. However, I can't make the local one works properly on any version of Powerpoint.
The issue is not Powerpoint specific, it occurs with any Office product.
I'm working on a Outlook addin and fancing this problem.
It has been reported (without any answer unfortunely) to Microsoft:
https://social.msdn.microsoft.com/Forums/office/en-US/93d08ccc-9e77-4f72-9c51-477468d89681/keyboardhook-will-not-work-in-word-2013?forum=worddev
I have been able to make a "workaround": i have register a Global Hook AND a Local one ("Thread"). It works, but the keyProc is called "weirdly" when it's local, not respecting documented parameters:
- wParam is not one of WM_*, but contains directly the vkCode
- lParam cannot be accessed (AccessViolation)
As I understood, it's because some "TranslateMessage" processing.
I have also adapted your code to be able to catch ALT combination.
private bool wParamAlt;
private IntPtr KeyProc(int nCode, int wParam, IntPtr lParam)
{
bool handled = false;
if ((nCode == 0) && (m_onKeyDown != null || m_onKeyUp != null || m_onKeyPress != null))
{
KeyboardHookStruct MyKeyboardHookStruct;
if (wParam >= 0x100)
{
MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
wParamAlt = false;
}
else
{
MyKeyboardHookStruct = new KeyboardHookStruct();
MyKeyboardHookStruct.vkCode = wParam;
if (wParamAlt)
{
wParamAlt = (wParam == 18);
wParam = 0x104;
}
else
{
wParamAlt = (wParam == 18);
wParam = 0x100;
}
}
if (m_onKeyDown != null && (wParam == 0x100 || wParam == 0x104))
{
Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
if (wParam == 0x104)
keyData |= Keys.Alt;
KeyEventArgs e = new KeyEventArgs(keyData);
m_onKeyDown(this, e);
handled = handled || e.Handled;
}
if (m_onKeyPress != null && wParam == 0x100)
{
bool isShift = ((GetKeyState(0x10) & 0x80) == 0x80 ? true : false);
bool isCapslock = (GetKeyState(0x14) != 0 ? true : false);
byte[] keyState = new byte[256];
GetKeyboardState(keyState);
byte[] inBuffer = new byte[2];
if (ToAscii(MyKeyboardHookStruct.vkCode, MyKeyboardHookStruct.scanCode, keyState, inBuffer, MyKeyboardHookStruct.flags) == 1)
{
char key = (char)inBuffer[0];
if ((isCapslock ^ isShift) && Char.IsLetter(key))
key = Char.ToUpper(key);
KeyPressEventArgs e = new KeyPressEventArgs(key);
m_onKeyPress(this, e);
handled = handled || e.Handled;
}
}
if (m_onKeyUp != null && (wParam == 0x101 || wParam == 0x105))
{
Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
if (wParam == 0x105)
keyData |= Keys.Alt;
KeyEventArgs e = new KeyEventArgs(keyData);
m_onKeyUp(this, e);
handled = handled || e.Handled;
}
}
if (handled)
return (IntPtr)1;
else
return CallNextHookEx(m_Hook, nCode, (IntPtr)wParam, (IntPtr)lParam);
}
Related
I'm using the full class provided as best answer in: C# Hook Global Keyboard Events - .net 4.0 without any changes to it. However, when pressing a key when focussed on the powerpoint, I get the following error:
Exception thrown: 'System.Runtime.InteropServices.COMException'
I open the powerpoint by:
PowerPoint.Presentation presentation = (PowerPoint.Presentation)PowerPointItems[0];
PowerPoint.Application application = presentation.Application;
PowerPoint.SlideShowSettings settings = presentation.SlideShowSettings;
settings.ShowType = (PowerPoint.PpSlideShowType)1;
settings.ShowPresenterView = MsoTriState.msoFalse;
PowerPoint.SlideShowWindow sw = settings.Run();
sw.View.AcceleratorsEnabled = MsoTriState.msoFalse;
presentation.SlideShowWindow.View.GotoSlide(1);
presentation.SlideShowWindow.View.FirstAnimationIsAutomatic();
The callback function looks like:
private static void Kh_KeyDown(Keys key, bool Shift, bool Ctrl, bool Alt)
{
Console.WriteLine("a");
PowerPoint.Presentation presentation = (PowerPoint.Presentation)PowerPointItems[0];
Console.WriteLine("b");
int nr_slides = presentation.Slides.Count;
Console.WriteLine("c");
}
However, while a and b are printed in the output, c is not but the exception is. This makes me think for some reason the exception is thrown because of the line
int nr_slides = presentation.Slides.Count;
Any thought on why this could be the case?
The code provided on C# Hook Global Keyboard Events - .net 4.0:
public class KeyboardHook : IDisposable
{
bool Global = false;
public delegate void ErrorEventHandler(Exception e);
public delegate void LocalKeyEventHandler(Keys key, bool Shift, bool Ctrl, bool Alt);
public event LocalKeyEventHandler KeyDown;
public event LocalKeyEventHandler KeyUp;
public event ErrorEventHandler OnError;
public delegate int CallbackDelegate(int Code, IntPtr W, IntPtr L);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct KBDLLHookStruct
{
public Int32 vkCode;
public Int32 scanCode;
public Int32 flags;
public Int32 time;
public Int32 dwExtraInfo;
}
[DllImport("user32", CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr SetWindowsHookEx(HookType idHook, CallbackDelegate lpfn, IntPtr hInstance, int threadId);
[DllImport("user32", CallingConvention = CallingConvention.StdCall)]
private static extern bool UnhookWindowsHookEx(IntPtr idHook);
[DllImport("user32", CallingConvention = CallingConvention.StdCall)]
private static extern int CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall)]
private static extern int GetCurrentThreadId();
[DllImport("kernel32.dll")]
static extern IntPtr LoadLibrary(string lpFileName);
public enum HookType : int
{
WH_JOURNALRECORD = 0,
WH_JOURNALPLAYBACK = 1,
WH_KEYBOARD = 2,
WH_GETMESSAGE = 3,
WH_CALLWNDPROC = 4,
WH_CBT = 5,
WH_SYSMSGFILTER = 6,
WH_MOUSE = 7,
WH_HARDWARE = 8,
WH_DEBUG = 9,
WH_SHELL = 10,
WH_FOREGROUNDIDLE = 11,
WH_CALLWNDPROCRET = 12,
WH_KEYBOARD_LL = 13,
WH_MOUSE_LL = 14
}
private IntPtr HookID = IntPtr.Zero;
CallbackDelegate TheHookCB = null;
//Start hook
public KeyboardHook(bool Global)
{
this.Global = Global;
TheHookCB = new CallbackDelegate(KeybHookProc);
if (Global)
{
IntPtr hInstance = LoadLibrary("User32");
HookID = SetWindowsHookEx(HookType.WH_KEYBOARD_LL, TheHookCB,
hInstance, //0 for local hook. or hwnd to user32 for global
0); //0 for global hook. eller thread for hooken
}
else
{
HookID = SetWindowsHookEx(HookType.WH_KEYBOARD, TheHookCB,
IntPtr.Zero, //0 for local hook. or hwnd to user32 for global
GetCurrentThreadId()); //0 for global hook. or thread for the hook
}
}
public void test()
{
if (OnError != null) OnError(new Exception("test"));
}
bool IsFinalized = false;
~KeyboardHook()
{
if (!IsFinalized)
{
UnhookWindowsHookEx(HookID);
IsFinalized = true;
}
}
public void Dispose()
{
if (!IsFinalized)
{
UnhookWindowsHookEx(HookID);
IsFinalized = true;
}
}
[STAThread]
//The listener that will trigger events
private int KeybHookProc(int Code, IntPtr W, IntPtr L)
{
KBDLLHookStruct LS = new KBDLLHookStruct();
if (Code < 0)
{
return CallNextHookEx(HookID, Code, W, L);
}
try
{
if (!Global)
{
if (Code == 3)
{
IntPtr ptr = IntPtr.Zero;
int keydownup = L.ToInt32() >> 30;
if (keydownup == 0)
{
if (KeyDown != null) KeyDown((Keys)W, GetShiftPressed(), GetCtrlPressed(), GetAltPressed());
}
if (keydownup == -1)
{
if (KeyUp != null) KeyUp((Keys)W, GetShiftPressed(), GetCtrlPressed(), GetAltPressed());
}
//System.Diagnostics.Debug.WriteLine("Down: " + (Keys)W);
}
}
else
{
KeyEvents kEvent = (KeyEvents)W;
Int32 vkCode = Marshal.ReadInt32((IntPtr)L); //Leser vkCode som er de første 32 bits hvor L peker.
if (kEvent != KeyEvents.KeyDown && kEvent != KeyEvents.KeyUp && kEvent != KeyEvents.SKeyDown && kEvent != KeyEvents.SKeyUp)
{
}
if (kEvent == KeyEvents.KeyDown || kEvent == KeyEvents.SKeyDown)
{
if (KeyDown != null) KeyDown((Keys)vkCode, GetShiftPressed(), GetCtrlPressed(), GetAltPressed());
}
if (kEvent == KeyEvents.KeyUp || kEvent == KeyEvents.SKeyUp)
{
if (KeyUp != null) KeyUp((Keys)vkCode, GetShiftPressed(), GetCtrlPressed(), GetAltPressed());
}
}
}
catch (Exception e)
{
if (OnError != null) OnError(e);
//Ignore all errors...
}
return CallNextHookEx(HookID, Code, W, L);
}
public enum KeyEvents
{
KeyDown = 0x0100,
KeyUp = 0x0101,
SKeyDown = 0x0104,
SKeyUp = 0x0105
}
[DllImport("user32.dll")]
static public extern short GetKeyState(System.Windows.Forms.Keys nVirtKey);
public static bool GetCapslock()
{
return Convert.ToBoolean(GetKeyState(System.Windows.Forms.Keys.CapsLock)) & true;
}
public static bool GetNumlock()
{
return Convert.ToBoolean(GetKeyState(System.Windows.Forms.Keys.NumLock)) & true;
}
public static bool GetScrollLock()
{
return Convert.ToBoolean(GetKeyState(System.Windows.Forms.Keys.Scroll)) & true;
}
public static bool GetShiftPressed()
{
int state = GetKeyState(System.Windows.Forms.Keys.ShiftKey);
if (state > 1 || state < -1) return true;
return false;
}
public static bool GetCtrlPressed()
{
int state = GetKeyState(System.Windows.Forms.Keys.ControlKey);
if (state > 1 || state < -1) return true;
return false;
}
public static bool GetAltPressed()
{
int state = GetKeyState(System.Windows.Forms.Keys.Menu);
if (state > 1 || state < -1) return true;
return false;
}
}
In general, you need to catch the COMException, interrogate ErrorCode (HRESULT) property, and search for the error code definition; this will provide direction on how to troubleshoot the issue further.
Reference: COMException Class: Handling a COMException exception on MSDN
One idea, without knowing the error code, is this interaction might need to occur on the thread which instantiated the control. You might be able to resolve this by using Invoke or BeginInvoke.
Control.BeginInvoke Method
If you add more details to the question I will try to provide a better answer.
I would like to intercept while I push CTRL + A + A
I read the article
How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5?
and someone pasted a code originally posted here:
https://www.fluxbytes.com/csharp/how-to-register-a-global-hotkey-for-your-application-in-c/?unapproved=2279&moderation-hash=b3ec34d2621e0be051ed354f09c436d2#comment-2279
Anyway, I tried to change the code adding and "&" but this and some other attempt was wrong.
How can I get if I press CTRL + A + A ?
Thanks for the help!
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace GlobalHotkeyExampleForm
{
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
}
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
enum KeyModifier
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
WinKey = 8
}
public Form1()
{
InitializeComponent();
int id = 0; // The id of the hotkey.
RegisterHotKey(this.Handle, id, (int)KeyModifier.Control, Keys.A.GetHashCode()); // Register ctrl + a as global hotkey.
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0x0312)
{
/* Note that the three lines below are not needed if you only want to register one hotkey.
* The below lines are useful in case you want to register multiple keys, which you can use a switch with the id as argument, or if you want to know which key/modifier was pressed for some particular reason. */
Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF); // The key of the hotkey that was pressed.
KeyModifier modifier = (KeyModifier)((int)m.LParam & 0xFFFF); // The modifier of the hotkey that was pressed.
int id = m.WParam.ToInt32(); // The id of the hotkey that was pressed.
MessageBox.Show("Hotkey has been pressed!");
// do something
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
UnregisterHotKey(this.Handle, 0); // Unregister hotkey with id 0 before closing the form. You might want to call this more than once with different id values if you are planning to register more than one hotkey.
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
This is the solution that I've found to listen Key Pressure.
I took the code from "Dylan's Web" and I changed something:
https://www.dylansweb.com/2014/10/low-level-global-keyboard-hook-sink-in-c-net/
This is the class with a couple of lines more:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Input;
namespace DesktopWPFAppLowLevelKeyboardHook
{
public class LowLevelKeyboardListener
{
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private const int WM_KEYUP = 0x101;
private const int WM_SYSKEYDOWN = 0x104;
private const int WM_SYSKEYUP = 0x105;
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
public event EventHandler<KeyPressedArgs> OnKeyPressed;
private LowLevelKeyboardProc _proc;
private IntPtr _hookID = IntPtr.Zero;
public LowLevelKeyboardListener()
{
_proc = HookCallback;
}
public void HookKeyboard()
{
_hookID = SetHook(_proc);
}
public void UnHookKeyboard()
{
UnhookWindowsHookEx(_hookID);
}
private IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
}
}
private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN)
{
int vkCode = Marshal.ReadInt32(lParam);
int status = 1;
if (OnKeyPressed != null) { OnKeyPressed(this, new KeyPressedArgs(KeyInterop.KeyFromVirtualKey(vkCode), status)); }
}
else if (nCode >= 0 && wParam == (IntPtr)WM_KEYUP || wParam == (IntPtr)WM_SYSKEYUP)
{
int vkCode = Marshal.ReadInt32(lParam);
int status = 0;
if (OnKeyPressed != null) { OnKeyPressed(this, new KeyPressedArgs(KeyInterop.KeyFromVirtualKey(vkCode), status)); }
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
}
public class KeyPressedArgs : EventArgs
{
public Key KeyPressed { get; private set; }
public int KeyStatus { get; private set; }
public KeyPressedArgs(Key key, int status)
{
KeyPressed = key;
KeyStatus = status;
}
}
}
This is the Form:
using DesktopWPFAppLowLevelKeyboardHook;
using System;
using System.Windows.Forms;
namespace AppLowLevelKeyboardHook
{
public partial class Form1 : Form
{
private LowLevelKeyboardListener _listener;
public int ctrlStatus;
public int cStatus;
public Form1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, EventArgs e)
{
_listener = new LowLevelKeyboardListener();
_listener.OnKeyPressed += _listener_OnKeyPressed;
_listener.HookKeyboard();
}
private void _listener_OnKeyPressed(object sender, KeyPressedArgs e)
{
this.textBox_DisplayKeyboardInput.Text += e.KeyPressed.ToString() + e.KeyStatus.ToString();
if (e.KeyStatus == 1 && (e.KeyPressed.ToString() == "LeftCtrl" || e.KeyStatus.ToString() == "RightCtrl"))
{
if (ctrlStatus == 0)
{
ctrlStatus = ctrlStatus + 1;
timer1.Start();
}
}
else if (e.KeyStatus == 1 && e.KeyPressed.ToString() == "C")
{
if (ctrlStatus == 1 && (cStatus == 0 || cStatus == 2))
{
cStatus = cStatus + 1;
}
}
//no need to wait that CTRL will be released
//else if (e.KeyStatus == 0 && (e.KeyPressed.ToString() == "LeftCtrl" || e.KeyStatus.ToString() == "RightCtrl"))
//{
// if (ctrlStatus == 1)
// {
// ctrlStatus = ctrlStatus + 1;
// }
//}
else if (e.KeyStatus == 0 && e.KeyPressed.ToString() == "C")
{
if (ctrlStatus == 1)
{
if (cStatus == 1 || cStatus == 3)
{
cStatus = cStatus + 1;
}
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if ((ctrlStatus == 1) && cStatus == 3 || cStatus == 4) //no need to wait that CTRL will be released (ctrlStatus == 2)
{
//do something
label1.Text = "";
label1.Refresh();
label1.Text = Clipboard.GetText(TextDataFormat.UnicodeText);
//\do something
}
ctrlStatus = 0;
cStatus = 0;
timer1.Stop();
}
private void Window_Closing(object sender, FormClosingEventArgs e)
{
_listener.UnHookKeyboard();
}
}
}
PS: originally it was WPF app but mine it's a WFA and KeyInterop is not included.
So I simply added a reference assembly to WindowsBase.dll
Yesterday I'm back on this question and finally, I did what I was searching to do but changing the strategy because with the upper code I didn't really found a solution for my target. I'm going to report why I think it can be useful to someone else and maybe someone has a different solution.
So, on the upper code, I tried to intercept CTRL+C+C and than get what use copy on the Windows Clipboard. But here it's the problem, that code registers the shortkey, so any other software can't continue to use CTRL+C. I tried to unregister the shortkey after to have cached that CTRL+C has been pressed but I've found only problems. Anyway, I don't like "to stole" a shortkey to another app, I prefer to "listen" key while they are pressed.
So here it follows the code with some comments (I'll paste the solution that I've found "listening keys pressed" adding a new answer).
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text;
namespace GlobalHotkeyExampleForm
{
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
}
public int shortkey = 0;
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
enum KeyModifier
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
WinKey = 8
}
public Form1()
{
InitializeComponent();
int id = 0; // The id of the hotkey.
RegisterHotKey(this.Handle, id, (int)KeyModifier.Control, Keys.C.GetHashCode()); // Register CTRL + C as global hotkey.
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0x0312)
{
/* Note that the three lines below are not needed if you only want to register one hotkey.
* The below lines are useful in case you want to register multiple keys, which you can use a switch with the id as argument, or if you want to know which key/modifier was pressed for some particular reason. */
Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF); // The key of the hotkey that was pressed.
KeyModifier modifier = (KeyModifier)((int)m.LParam & 0xFFFF); // The modifier of the hotkey that was pressed.
int id = m.WParam.ToInt32(); // The id of the hotkey that was pressed.
if (modifier == KeyModifier.Control && key == Keys.C)
{
shortkey = shortkey + 1;
label1.Text = (shortkey.ToString());
//if I enebale this code it works partially. The UnregisterHotKey and RegisterHotKey works perfectly and alone also SendKeys works prefectly, but together it doesn't:
//it doesn't recognize that CTRL is still pressed and I don't want to do CTRL C + CTRL C and I don't like "to stole" the shortkey from other apps!;
//I tried to use SendKeys to resend CTRL C or onlt CTRL but it doens't work and it creates only Register problems
//UnregisterHotKey(this.Handle, 0); //unregister the hotkey catching
//SendKeys.Send("^c"); //send key to active application (it doesn't matter if this is the application)
////register the hotkey catching as C only
//RegisterHotKey(this.Handle, id, (int)KeyModifier.Control, Keys.C.GetHashCode());
//SendKeys.Send("^c");
//SendKeys.Send("^");
timer1.Start();
}
//MessageBox.Show("Hotkey has been pressed!");
// do something
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
UnregisterHotKey(this.Handle, 0); // Unregister hotkey with id 0 before closing the form. You might want to call this more than once with different id values if you are planning to register more than one hotkey.
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (shortkey == 2)
{
string returnMyText = Clipboard.GetText(TextDataFormat.Text);
}
shortkey = 0;
timer1.Stop();
}
}
}
Im looking for a way that so Users that use my Program can change the Hotkeys theirself so its not bound to D,F12,K,F,A and so on.. i kinda want that ppl can change it via a Textbox or maybe via a Settings File. Been Stuck on it for couple Weeks now and i just cant find a way to make it happen, its my first Program im working on.
public void gHook_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.D:
// stuff
Salvagebtn.PerformClick();
break;
case Keys.F12:
// stuff
pausebtn.PerformClick();
break;
case Keys.K:
//stuff
Geardropbtn.PerformClick();
break;
case Keys.F:
//stuff
Gamblebtn.PerformClick();
break;
case Keys.A:
//stuff
LeftClickSpambtn.PerformClick();
break;
case Keys.H:
// stuff
openGRbtn.PerformClick();
break;
case Keys.B:
//stuff
gemupbtn.PerformClick();
break;
}
}
I had a few minutes, during commercials. So, I wrote the following:
EDIT : Code wrapped with a global keyboard handler. You will also need to add a reference to PresentationCore and WindowsBase ...
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Windows.Input;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("user32.dll")]
static extern int MapVirtualKey(uint uCode, uint uMapType);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100,
WM_KEYUP = 0x0101,
S_WM_KEYDOWN = 0x0104,
S_WM_KEYUP = 0x0105;
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
private static Form1 hookForm;
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
}
}
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
static bool bShortcutPressed;
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (hookForm.Handle != GetForegroundWindow())
{
if (nCode >= 0 && ((wParam == (IntPtr)WM_KEYDOWN) || (wParam == (IntPtr)S_WM_KEYDOWN)))
{
int vkCode = Marshal.ReadInt32(lParam);
bool bCtrl = (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl));
bool bAlt = (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt));
bool bShift = (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift));
Keys hookKey = (Keys)vkCode;
hookKey = (bCtrl) ? ((Keys.Control | hookKey)) : hookKey;
hookKey = (bAlt) ? ((Keys.Alt | hookKey)) : hookKey;
hookKey = (bShift) ? ((Keys.Shift | hookKey)) : hookKey;
Debug.Print($"hookKey {hookKey} {bCtrl} {bAlt} {bShift}");
if (!bShortcutPressed && dicTest.ContainsValue(hookKey))
{
hookForm.OnKeyDown(new System.Windows.Forms.KeyEventArgs(hookKey));
bShortcutPressed = true; Debug.Print($"{bShortcutPressed}");
}
}
if (nCode >= 0 && (((wParam == (IntPtr)WM_KEYUP) || (wParam == (IntPtr)S_WM_KEYUP)))) { bShortcutPressed = false; Debug.Print($"{bShortcutPressed}"); }
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
static Dictionary<string, Keys> dicTest = new Dictionary<string, Keys>();
public void AddHotKey(Action function, Keys key, bool ctrl = false, bool shift = false, bool alt = false)
{
KeyDown += delegate (object sender, System.Windows.Forms.KeyEventArgs e) { if (IsHotkey(e, key, ctrl, shift, alt)) { function(); } };
}
public bool IsHotkey(System.Windows.Forms.KeyEventArgs eventData, Keys key, bool ctrl = false, bool shift = false, bool alt = false) =>
eventData.KeyCode == key && eventData.Control == ctrl && eventData.Shift == shift && eventData.Alt == alt;
public Form1() => InitializeComponent();
private void Form1_Load(object sender, EventArgs e)
{
_hookID = SetHook(_proc);
hookForm = this;
KeyPreview = true;
String[] names = Enum.GetNames(typeof(Keys));
foreach (string key in names) { comboBox1.Items.Add(key); }
comboBox1.SelectedItem = comboBox1.Items[0];
KeyDown += Form1_KeyDown;
}
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
Debug.Print($"Form1_KeyDown : {e.KeyData}");
}
protected override void OnFormClosing(FormClosingEventArgs e) => UnhookWindowsHookEx(_hookID);
private void button1_Click(object sender, EventArgs e)
{
Keys hookKey = (Keys)Enum.Parse(typeof(Keys), comboBox1.Text);
hookKey = (checkBox1.Checked) ? ((Keys.Control | hookKey)) : hookKey;
hookKey = (checkBox2.Checked) ? ((Keys.Alt | hookKey)) : hookKey;
hookKey = (checkBox3.Checked) ? ((Keys.Shift | hookKey)) : hookKey;
if (!dicTest.ContainsValue(hookKey))
{
Debug.Print($"Going to add : {hookKey} : to our Shortcut Dictionary<>");
dicTest.Add("test", hookKey);
AddHotKey(() => { button2.PerformClick(); }, (Keys)new KeysConverter().ConvertFrom(comboBox1.Text), checkBox1.Checked, checkBox3.Checked, checkBox2.Checked);
//checkBox1.Enabled = checkBox2.Enabled = checkBox3.Enabled = comboBox1.Enabled = button1.Enabled = false;
label2.Text = "Go ahead and tryout your Shortcut now ...";
}
else { label2.Text = "Shortcut key is already stored in our Dictionary<> ..."; }
}
private void button2_Click(object sender, EventArgs e) { Debug.Print($"Button2 was clicked"); }
}
}
You're presented with:
Trying the desired shortcut out:
Just an example, to show there are many ways to do things.
Easy to write them out to a file or something. If you were going to ... I'd change the AddHotKey Action param to a string which contains a function name and then using different methods you can have it invoke that function.
Really though, I'd incorporate a Dictionary as the one talked about below.
There's a myriad of different ways you could handle this. Personally, I'd opt for using a Dictionary with the Keycode as the Key, and a delegate/action as the value. Then on the keypress, you just call the function in the dictionary that's associated with that keycode. Something along the lines of:
Dictionary<KeyCode, System.Action> keyDict = new Dictionary<KeyCode, System.Action>();
// populate it however you wish. Whether it's user entry or from a file or something.
keyDict.Add(KeyCode.D, SomeFunction);
If you want to change the delegate in the dictionary:
keyDict[KeyCode.D] = SomeOtherFunction;
Then later in the event handler:
public void gHook_KeyDown(object sender, KeyEventArgs e)
{
keyDict[e.KeyCode].Invoke();
}
public void SomeFunction()
{
Console.WriteLine("called some function");
}
(This question might have a bit more detail if needed: Create dictionary with dynamic keys in C#)
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ScreenYos
{
public class KeyboardHook : IDisposable
{
private bool Global = false;
public delegate void LocalKeyEventHandler(Keys key, bool Printscreen);
public event LocalKeyEventHandler KeyDown;
public event LocalKeyEventHandler KeyUp;
public delegate int CallbackDelegate(int Code, int W, int L);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct KBDLLHookStruct
{
public Int32 vkCode;
public Int32 scanCode;
public Int32 flags;
public Int32 time;
public Int32 dwExtraInfo;
}
[DllImport("user32", CallingConvention = CallingConvention.StdCall)]
private static extern int SetWindowsHookEx(HookType idHook, CallbackDelegate lpfn, int hInstance, int threadId);
[DllImport("user32", CallingConvention = CallingConvention.StdCall)]
private static extern bool UnhookWindowsHookEx(int idHook);
[DllImport("user32", CallingConvention = CallingConvention.StdCall)]
private static extern int CallNextHookEx(int idHook, int nCode, int wParam, int lParam);
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall)]
private static extern int GetCurrentThreadId();
public enum HookType : int
{
WH_JOURNALRECORD = 0,
WH_JOURNALPLAYBACK = 1,
WH_KEYBOARD = 2,
WH_GETMESSAGE = 3,
WH_CALLWNDPROC = 4,
WH_CBT = 5,
WH_SYSMSGFILTER = 6,
WH_MOUSE = 7,
WH_HARDWARE = 8,
WH_DEBUG = 9,
WH_SHELL = 10,
WH_FOREGROUNDIDLE = 11,
WH_CALLWNDPROCRET = 12,
WH_KEYBOARD_LL = 13,
WH_MOUSE_LL = 14
}
private int HookID = 0;
private CallbackDelegate TheHookCB = null;
public KeyboardHook(bool Global)
{
this.Global = Global;
TheHookCB = new CallbackDelegate(KeybHookProc);
if (Global)
{
HookID = SetWindowsHookEx(HookType.WH_KEYBOARD_LL, TheHookCB,
0,
0);
}
else
{
HookID = SetWindowsHookEx(HookType.WH_KEYBOARD, TheHookCB,
0,
GetCurrentThreadId());
}
}
private bool IsFinalized;
~KeyboardHook()
{
if (!IsFinalized)
{
UnhookWindowsHookEx(HookID);
IsFinalized = true;
}
}
public void Dispose()
{
if (!IsFinalized)
{
UnhookWindowsHookEx(HookID);
IsFinalized = true;
}
}
private int KeybHookProc(int Code, int W, int L)
{
KBDLLHookStruct LS = new KBDLLHookStruct();
if (Code < 0)
{
return CallNextHookEx(HookID, Code, W, L);
}
try
{
if (!Global)
{
if (Code == 3)
{
IntPtr ptr = IntPtr.Zero;
int keydownup = L >> 30;
if (keydownup == 0)
{
if (KeyDown != null)
KeyDown((Keys) W, GetPrintscreenPressed());
}
if (keydownup == -1)
{
if (KeyUp != null) KeyUp((Keys) W, GetPrintscreenPressed());
}
//System.Diagnostics.Debug.WriteLine("KeyDown: " + (Keys)W);
}
}
else
{
KeyEvents kEvent = (KeyEvents) W;
Int32 vkCode = Marshal.ReadInt32((IntPtr) L);
if (kEvent != KeyEvents.KeyDown && kEvent != KeyEvents.KeyUp && kEvent != KeyEvents.SKeyDown &&
kEvent != KeyEvents.SKeyUp)
{
}
if (kEvent == KeyEvents.KeyDown || kEvent == KeyEvents.SKeyDown)
{
if (KeyDown != null)
KeyDown((Keys) vkCode, GetPrintscreenPressed());
}
if (kEvent == KeyEvents.KeyUp || kEvent == KeyEvents.SKeyUp)
{
if (KeyUp != null) KeyUp((Keys) vkCode, GetPrintscreenPressed());
}
}
}
catch (Exception e)
{
//Console.WriteLine(e.Message);
}
return CallNextHookEx(HookID, Code, W, L);
}
public enum KeyEvents
{
KeyDown = 0x0100,
KeyUp = 0x0101,
SKeyDown = 0x0104,
SKeyUp = 0x0105
}
[DllImport("user32.dll")]
public static extern short GetKeyState(Keys nVirtKey);
public static bool GetPrintscreenPressed()
{
int state = GetKeyState(Keys.PrintScreen);
if (state > 1 || state < -1) return true;
return false;
}
}
}
My usage:
private static void Kh_KeyDown(Keys key, bool Printscreen)
{
if (new Form1().ShowDialog() == DialogResult.OK)
{
Application.Run(new Form1());
}
}
So program runs in system tray and the aim of the code is capture keys globally and when printscreen is pressed run Form1 yet it captures every key and no matter what key i press, it runs form1.
I assume that's because you initialized a general callback for all Keys on KeyDown.
You must either filter by Keys.PrintScreen when you call the event
or
Filter by Keys.PrintScreen in your Eventhandler.
private static void Kh_KeyDown(Keys key, bool Printscreen)
{
if (key == Keys.PrintScreen && new Form1().ShowDialog() == DialogResult.OK)
{
Application.Run(new Form1());
}
}
Thomas
i have my program that Captures weighing and send it to a open window.
its work excellent , except with a single software - Microsoft Word
I have tried everything and have no idea why.
my code:
this is the GlobalKeyBoardHook.cs class
public class GlobalKeyboardHook
{
[DllImport("user32.dll")]
static extern int CallNextHookEx(IntPtr hhk, int code, int wParam, ref keyBoardHookStruct lParam);
[DllImport("user32.dll")]
static extern IntPtr SetWindowsHookEx(int idHook, LLKeyboardHook callback, IntPtr hInstance, uint theardID);
[DllImport("user32.dll")]
static extern bool UnhookWindowsHookEx(IntPtr hInstance);
[DllImport("kernel32.dll")]
static extern IntPtr LoadLibrary(string lpFileName);
public delegate int LLKeyboardHook(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 = 0x0100;
const int WM_KEYUP = 0x0101;
const int WM_SYSKEYDOWN = 0x0104;
const int WM_SYSKEYUP = 0x0105;
LLKeyboardHook llkh;
public List<Keys> HookedKeys = new List<Keys>();
IntPtr Hook = IntPtr.Zero;
public event KeyEventHandler KeyDown;
public event KeyEventHandler KeyUp;
// This is the Constructor. This is the code that runs every time you create a new GlobalKeyboardHook object
public GlobalKeyboardHook()
{
llkh = new LLKeyboardHook(HookProc);
// This starts the hook. You can leave this as comment and you have to start it manually (the thing I do in the tutorial, with the button)
// Or delete the comment mark and your hook will start automatically when your program starts (because a new GlobalKeyboardHook object is created)
// That's why there are duplicates, because you start it twice! I'm sorry, I haven't noticed this...
// hook(); <-- Choose!
}
~GlobalKeyboardHook()
{ unhook(); }
public void hook()
{
IntPtr hInstance = LoadLibrary("User32");
Hook = SetWindowsHookEx(WH_KEYBOARD_LL, llkh, hInstance, 0);
}
public void unhook()
{
UnhookWindowsHookEx(Hook);
}
public int HookProc(int Code, int wParam, ref keyBoardHookStruct lParam)
{
if (Code >= 0)
{
Keys key = (Keys)lParam.vkCode;
if (HookedKeys.Contains(key))
{
KeyEventArgs kArg = new KeyEventArgs(key);
if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) && (KeyDown != null))
KeyDown(this, kArg);
else if ((wParam == WM_KEYUP || wParam == WM_SYSKEYUP) && (KeyUp != null))
KeyUp(this, kArg);
if (kArg.Handled)
return 1;
}
}
return CallNextHookEx(Hook, Code, wParam, ref lParam);
}
// --- from here start the program --
GlobalKeyboardHook gHook;
gHook = new GlobalKeyboardHook(); // Create a new GlobalKeyboardHook
gHook.KeyDown += new KeyEventHandler(gHook_KeyDown);
foreach (Keys key in Enum.GetValues(typeof(Keys)))
{
gHook.HookedKeys.Add(key);
}
gHook.hook();
public void gHook_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == KeyPressg) //Pause-Break //19
{
ProccName = (GetActiveWindowTitle().ToString());
Start(ProccName);
gHook.unhook();
gHook.hook();
}
else
{
}
}
private string GetActiveWindowTitle()
{
const int nChars = 256;
StringBuilder Buff = new StringBuilder(nChars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
return Buff.ToString();
}
return null;
}
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll")]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
public void Start(string NAME)
{
MSG = lblMSG.Text.Trim();
IntPtr zero = IntPtr.Zero;
for (int i = 0; (i < 60) && (zero == IntPtr.Zero); i++)
{
Thread.Sleep(500);
zero = FindWindow(null, NAME);
}
if (zero != IntPtr.Zero)
{
try
{
string text = lblMSG.Text.Trim();
text = text.Replace("gHook", "");
//OLD
//foreach (char c in text)
// SendKeys.SendWait(c.ToString());
//NEW
if (text.Length == 0) return;
SendKeys.SendWait(text);
if (MyParam._KeyAfter == "Enter")
{
MyParam.FromKEY = true;
SendKeys.SendWait("{ENTER}");
}
else if (MyParam._KeyAfter == "TAB")
{
SendKeys.SendWait("{TAB}");
}
else if (MyParam._KeyAfter == "Key Down")
{
SendKeys.SendWait("{DOWN}");
}
SendKeys.Flush();
}
catch { }
}
}
Any ideas why ?
thanks
EDIT
i fount the problem place:
public void Start(string NAME)
{
// --> NAME Contain --> Word - 123.docx for example when Word window open
MSG = lblMSG.Text.Trim();
IntPtr zero = IntPtr.Zero;
for (int i = 0; (i < 60) && (zero == IntPtr.Zero); i++)
{
Thread.Sleep(500);
zero = FindWindow(null, NAME); // <-- in Word zero Always Contain 0 And never goes on in the code so stuck
}
// <--- the program stops here and stuck
if (zero != IntPtr.Zero)
{