I'm working on a C# project where I need to create the possibility for keyboard input.
A quiz question appears with 3 options. Two players at the same computer have each of their hand at the ASD keys and JKL keys. For the answer options, I'd like for it to be chosen by pressing keyboard keys, as using anything by mouse would be inconvenient for this purpose.
How could I do this? Do I need to use some scripts outside purely C#?
I assume that we are talking about a web application. Yes you have to use script. Let me explain to you this way: Your c# code is working on the server side. It does not have an effect on client side. Maybe some third party tools like devexpress or something else can be used for this situtaion, but i am not sure these tools can handle key press events. I always prefer developing my own script
$(document).keypress(function(event) { //handle keys });
Not enough detail here, please look at:
https://stackoverflow.com/questions/how-to-ask
This method retrieves the keys pressed by the user, For example by selecting Ctrl + O, a method called ImportFile() will run. Another useful event to use will be the KeyPressed which is particularly useful firing in textboxes for validation - checking if it's empty.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// If user selects Ctrl + O
if (keyData == (Keys.Control | Keys.O))
{
// Call method
ImportFile();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Take a look at Key Events: ProcessCmdKey for more details.
Related
I've looked around for six hours today in search of a method to complete the task I'm looking to accomplish. However with little luck every method I've tried has come out not working.
So the program I'm working on is a multiboxing application for video games. Essentially I want to have my created application running in the background. The user will check on checkbox's to state which keys they want to be captured, so not every key is being captured. Then while they are playing the main game, the application will send the keys that are checked to the games running in the background.
I've tried global hotkeys however never could get more than one key working. I've also tried to hook keys but for some reason, couldn't get that functional. I also dabbled into sendmessage with little luck there either.
Was just curious if anyone else had some ideas for going about doing this. To give an example of another program that does this same thing would be HotKeyNet, KeyClone, and ISboxer. I know there are more out there but that gives you an idea of what I'm trying to do with my application.
Alright, after quite a bit of research into different methods for sending keystrokes and reading keystrokes. I finally was able to splice to different types of coding together to provide the results I was looking for.
I'm posting up the answer, so anyone that is looking for the answer to this question later down the road has it available to them.
My two references for splicing this code together are the following:
http://www.codeproject.com/Articles/19004/A-Simple-C-Global-Low-Level-Keyboard-Hook
Send combination of keystrokes to background window
I used the global low level hook and postmessage for sending keystrokes to the background application.
So first you will need to follow the instructions from the first
link, to get the starting code working.
Download the working source code from link one, and use the
globalKeyboardHook.cs in your application.
Then in references place the following:
using System.Runtime.InteropServices; //Grabs for your DLLs
using Utilities; //Grabs from the file you added to your application.
Now you will want to place the following code in your class:
globalKeyboardHook gkh = new globalKeyboardHook();
[DllImport("user32.dll")] //Used for sending keystrokes to new window.
public static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Ansi)] //Used to find the window to send keystrokes to.
public static extern IntPtr FindWindow(string className, string windowName);
Now go ahead place your keystrokes you want to be grabbed this I
found is best in Form1_Loaded:
gkh.HookedKeys.Add(Keys.A);//This collects the A Key.
gkh.HookedKeys.Add(Keys.B);//This collects the B Key.
gkh.HookedKeys.Add(Keys.C);//This collects the C Key.
gkh.KeyDown += new KeyEventHandler(gkh_KeyDown); //Event for pressing the key down.
gkh.KeyUp += new KeyEventHandler(gkh_KeyUp); //Event for the release of key.
After that you will want to go ahead and place in the following in
your code as well:
void gkh_KeyUp(object sender, KeyEventArgs e) //What happens on key release.
{
lstLog.Items.Add("Up\t" + e.KeyCode.ToString());
e.Handled = false; //Setting this to true will cause the global hotkeys to block all outgoing keystrokes.
}
void gkh_KeyDown(object sender, KeyEventArgs e) //What happens on key press.
{
lstLog.Items.Add("Down\t" + e.KeyCode.ToString());
e.Handled = false;
}
Once that is in place just put this little bit in the gkh_KeyDown to
get your keystrokes to send to another window of your choosing:
const uint WM_KEYDOWN = 0x100;
IntPtr hWnd = FindWindow(null, "Example1"); //Find window Example1 for application.
switch (e.KeyCode)
{
case Keys.A: //Makes it so it only sends that key when it's pressed and no other keys.
if(chkA.Checked == true)
{
PostMessage(hWnd, WM_KEYDOWN, (IntPtr)(Keys.A), IntPtr.Zero); //Sends to key A to new window assigned hWnd which equals Example1.
}
break;
}
}
The code that I have provided is setup so people can use checkbox's to tell the program which keys they want to send over to the second application.
If you have any questions regarding to this post just let me know, and I will do my best to walk you through the process. Hope this helps someone out later down the road.
My suggestion is to go with "mapped memory" (in operating system concepts: shared memory)
First process creates (may be your check state program) creates a mapped memory and writes values to it.
All other game process reads the value from memory map created by first process.
Here is a very nice example regarding how to do it.
https://msdn.microsoft.com/en-us/library/dd267552(v=vs.110).aspx
I am trying to make an application that sends keys to an external application, in this case aerofly FS. I have previously used the SendKeys.SendWait() method with succes, but this time, it doesn't quite work the way I want it to. I want to send a "G" keystroke to the application and testing it out with Notepad I do get G's. But in aerofly FS nothing is recieved at all. Pressing G on the keyboard does work though.
This is my code handling input data (from an Arduino) an sending the keystrokes,
private void handleData(string curData)
{
if (curData == "1")
SendKeys.SendWait("G");
else
{ }
}
I too have run into external applications where SendKeys didn't work for me.
As best I can tell, some applications, like applets inside a browser, expect to receive the key down, followed by a pause, followed by a key up, which I don't think can be done with SendKeys.
I have been using a C# wrapper to the AutoIt Library, and have found it quite easy to use.
Here's a link to quick guide I wrote for integrating AutoIt into a C# project.
Once you have the wrapper and references, you can send "G" with the following:
private void pressG()
{
AutoItX3Declarations.AU3_Send("{g}");
}
or with a pause,
private void pressG()
{
AutoItX3Declarations.AU3_Send("{g down}", 0);
AutoItX3Declarations.AU3_Sleep( 50 ); //wait 50 milliseconds
AutoItX3Declarations.AU3_Send("{g up}", 0);
}
AutoIt also allows you programmatically control the mouse.
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
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.
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.