Simulate key stroke in any application - c#

How do I simulate a key stroke in a window that is not my C# application ?
Right now i'm using SendKeys.Send() but it does not work. The thing is I have a global keyboard hook so I catch the input directly from the keyboard and SendKeys.Send() is not seen like a real keyboard stroke.
The best would be to simulate a real keystroke this way, no matter what is the application i'm in, my program will catch it as if someone pressed a key.
I guess I found part of the problem. This is the event called if a key is pressed :
static void KeyBoardHook_KeyPressed(object sender, KeyPressedEventArgs e)
{
// Writes the pressed key in the console (it works)
Console.WriteLine(e.KeyCode.ToString());
// Check if pressed key is Up Arrow (it works and enters the condition)
if(e.KeyCode == Keys.Up)
{
// Send the key again. (does not work)
SendKeys.Send("{UP}");
}
}
I tried it this way to :
static void KeyBoardHook_KeyPressed(object sender, KeyPressedEventArgs e)
{
// Writes the pressed key in the console (it works)
Console.WriteLine(e.KeyCode.ToString());
// Check if pressed key is Up Arrow (it works and enters the condition)
if(e.KeyCode == Keys.Up)
{
// Send the key again. (does not work)
PostMessage(proc.MainWindowHandle,WM_KEYDOWN, VK_UP,0);
}
}
but it does not work either. The thing is since I send the key inside my event, will it call itself because a key has been pressed ? In case someone needs it, the code above.
[STAThread]
static void Main(string args)
{
KeyBoardHook.CreateHook();
KeyBoardHook.KeyPressed += KeyBoardHook_KeyPressed;
Application.Run();
KeyBoardHook.Dispose();
}
if you need the KeyBoardHook class I can post it too.
My guess is that my keyboard hook is catching the low-level keyboard outputs and the SendKeys is just simulating a keystroke so my hook doesn't catch it. Anybody thinks of a work around ?

I suggest you use this very cool library that masks all the complexity for you, the Windows Input Simulator available here: http://inputsimulator.codeplex.com/
I believe it's based on the Windows' SendInput function.

You can p/invoke the keybd_event (which is much simpler and easier) or SendInput (which is newer and has more capabilities) functions, which simulate keyboard input at a much lower level.

Related

Part of function executes 2 times if it's not in debug mode or Thread.Sleep lasts less than 1900ms

I have been dealing with really strange thing. In debug mode or if Thread.Sleep is set above 1900ms everything is fine, but if I'm not in debug mode a function OnKeyPressed is called twice while the function is still running.I thought, that it's because EventHandler calls OnKeyPressed twice, but when I pressed the key programmatically nothing has changed. What's more I have observed that the Thread.Sleep is called just one time. How do I know the code is executed two times? I have 2 the same objects in my savedWords collection.
Some details of the code I've written:
I have a Listbox<string> savedWords where I keep text from clipboard. I am using an InputSimulator Framework to simulate keyboard events(only to send key combination). I have a simple InputClass where I obtain a method CopyText in order to simulate key combination of ctrl+c to save the text in clipboard. I'm not able to get into the clipboard if I'm not using STA Attribute, so it has to be there. In order to hook the keyboard(to listening if the key I want to is pressed) I'm using the second solution(with the HandledEventArgs) from here Global keyboard capture in C# application .
Here is my code:
private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e)
{
if (e.KeyboardData.VirtualCode==(int)Keys.F1)
{
string storedText="";
e.Handled = true;
System.Windows.Clipboard.Clear();
Thread.Sleep(50);
Thread t = new Thread(
() => { storedText = pasteMethod.CopyText(); }
);
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
System.Threading.Thread.Sleep(1900); // If I set the time below 1900 it executes twice
if (!String.IsNullOrWhiteSpace(storedText))
{
savedWords.Add(storedText); //Here I add the text from clipboard to my collection and it's the part of code which is called twice
}
}
Taking a wild guess here, but the neither the keyboard hook you referenced nor your use of it filter the keyboard event by the event type. There are four event types based on this doc: WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN, and WM_SYSKEYUP. If you are processing both the key down and key up event or processing the key down event repeatedly depending on the repeat count, you will have your event handler called multiple times for the same conceptual key press. The keyboard hook you referenced passes the event type to its registered handlers, so you can filter on that and only handle the key up events to ensure that no matter how long the key is pressed you handle its press only one time.
Also, if you are only handling a specific key press event, you might want to consider registering a global hotkey instead of processing a hook callback for every unrelated key press.

error cs1001 cant use command ctrl c

Im trinying to write a word via pressed (ctrl+ c) but not work
please help me
please give me a hand
using System;
using System.Runtime.InteropServices;
class MainClass
{
static void Main()
{
ConsoleKeyInfo keypress;
keypress = Console.ReadKey(); // read keystrokes
if (keypress.Key == ConsoleKey.(CTRL-C))
{
Console.Write("One ");
}
}
}
Console applications consider CTRL+C to be the "termination command" of which is expected to cease functionality of the application and force it to close. Using CTRL+C as your input keys is faulty to begin with...
HOWEVER...
The keypress.Key should be the C key and you then need to also check if any "modifiers" are pressed. ALT, SHIFT, CTRL are the primary modifier keys and you usually check a boolean value to see if they are pressed or not . . so your application will check to see if the C key is pressed and if the CTRL modifier is pressed as well.
Check this out to get more information:
How to determine which key modifier is pressed

Pause between sending keystrokes to DirectX Application

I'd like to send a sequence of keypresses (to make up a word) to the window of a DirectX application followed by a pause before sending the ENTER key.
I'm able to send individual keypresses with the InputManager library, but I'm unsure of how to implement "waits" in between certain key sequences with this keyboard hook.
ie: Send the message "Hello", wait for 250ms followed by the ENTER key.
SendKeys and SendWait will not work for what I'm doing, as they will not send keystrokes to the DirectX application.
Here is some pseudo-code explaining what I'm trying to accomplish:
using InputManager;
namespace MyProject
{
public partial class form1: Form
{
private void helloButton_Click(object sender, EventArgs e)
{
Keyboard.KeyPress(Keys.H);
Keyboard.KeyPress(Keys.E);
Keyboard.KeyPress(Keys.L);
Keyboard.KeyPress(Keys.L);
Keyboard.KeyPress(Keys.O);
// (Wait 250ms)
Keyboard.KeyPress(Keys.Enter);
}
}
}
You can use Thread.Sleep(250);. This will pause the currently working thread for x amount of milliseconds.
Note that you will need to include System.Threading in your using statements.

Disable normal behavior of Alt key

When pressing the Alt key, normally the focus goes to the window's menu. I need to disable it globally. Because my application works with Alt key. When the user presses some key in combination with the Alt key, my application sends another key to active application. So I just need to ignore Alt when it opens the menu.
I'm new to programming and I'm looking for VB.Net or C# code.
My first answer is to NOT use the Alt key for your program and use Ctrl instead. Blocking "normal" things from happening usually leads to pain in the future.
But if you must use the Alt key I would check out this article which uses message filters to try and intercept it at the application level.
If that doesn't do what you're looking for, you might need to look into Global hooks, this link will get you started down the path. Global hooks are generally considered evil so you should only use this if the above two suggestions don't work. You must make sure that you uninstall your hooks otherwise you might find that you need to reboot your computer often to fix weird keyboard problems.
This works for me:
private class AltKeyFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
return m.Msg == 0x0104 && ((int)m.LParam & 0x20000000) != 0;
}
}
And then you add the message filter like so:
Application.AddMessageFilter(new AltKeyFilter());
You can try something like this:
public void HandleKeyDown(object sender, keyEventArgs e)
{
//do whatever you want with or without Alt
if (e.Modifiers == Keys.Alt)
e.SuppressKeyPress = true;
}
This should allow you to use Alt for whatever you want but keep it from activating the menustrip. Note that e.SuppressKeyPress = true also sets e.Handled = true.
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.keyeventargs.suppresskeypress?view=windowsdesktop-5.0

keyboard Events

whenever i am pressing key in my server system i ll send that keyevent to another system after that the correspondingaction should be happend in the client machine.. help me to get a better way to solve this problem
thanx in advance
If I understand it correctly then what you have doesn't sound too bad. Are you saying that:
You have a client server architecture.
At the server (presumably at command console or management application) you press a key.
The key corresponds to an action. The action needs to be invoked at the client.
You could implement this using asynchronous WCF. See here and here for more some more info. One way to look at this problem is as a distributed observer pattern. Your server is the subject and the client(s) are the observer(s).
Update: Handling Key Events in .Net
You could try adding a KeyDown event handler to your form:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control & e.KeyCode == Keys.C)
{
MessageBox.Show( "Ctrl + C pressed" );
// Swallow key event, i.e. indicate that it was handled.
e.Handled = true;
}
}
But if you have any controls on your form then you won't get the event. What you probably need to do is sniff windows messages using a message filter. E.g.
public class KeyDownMessageFilter : IMessageFilter
{
public const int WM_KEYDOWN = 0x0100;
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_KEYDOWN)
{
// Key Down
return true; // Event handled
}
return false;
}
}
Add this message filter to the application using the AddMessageFilter method. If you want to check if the CTRL key is pressed for the key down message then check the lparam.
If any of this isn't clear then let me know.
please give us more details on what you're trying to do.
To simulate key presses in Windows Forms, I'd use SendKeys class.

Categories