keyboard Events - c#

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.

Related

C# Windows form delete key not responding

in my C# windows form application I want the user to be able to remove a node by pressing the delete key on their keyboard and have implemented the seemingly correct code but when the delete key is pressed nothing happens.
private void treeView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys .Delete)
{
if (treeView1.SelectedNode != null)
{
treeView1.SelectedNode.Remove();
}
}
This is the code I am attempting to use to implement the desired function.
The keyboard keycode check looks fine to me, which says to me that treeView1.SelectedNode is probably returning null.
I met the problem today and have tried many ways to address it. MSDN gives the answer actually. Here are the two codes that I put in public Form1()
this.KeyPreview = true;
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
I've just study C# this week, so I am trying to figure out the meaning of the codes. Just hope this approach will work for the people who needs.
If anyone can explain the code above, I will be very grateful.

How can I make the website react to key presses?

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.

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

Simulate key stroke in any application

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.

C# For how long was user inactive

Some background:
I am writing a application with several forms, etc. Users have to log in in order to use most of the features, and this worked fine until now. However, now, client has requested that the user would be logged out after a certain amount of inactive time. The problem is that the user can still be active on the computer, just not in my application,. To be clear, I have to log the user out when he is inactive in my application, even if he is still interacting with the desktop.
First I thought this would be fairly simple. Just remember the time of the last action, compare it continually in a timer with current time and log out the user if the time passed is greater than the allowed time. However I have realised that finding out the last action time may not be so simple...
Of course I could copy paste something like
Program.LastActionTime = DateTime.Now;
in every OnChange, OnClick, etc, event ... However not only that this would be a great amount of work because of the size of the application ... It would also be a very bad practice and I'm sure it would be forgot at least once, making the whole thing unreliable (And appear broken, the bug would be almost impossible to reproduce!)
So, is there a better way?
One approach that I've used in the past, create a MessageFilter on your application form and check for certain types of events that indicate user activity:
public class UserActivityFilter : IMessageFilter
{
// Define WinAPI window message values (see pinvoke.net)
private int WM_LBUTTONDOWN = 0x0201;
private int WM_MBUTTONDOWN = 0x0207;
private int WM_RBUTTONDOWN = 0x0204;
private int WM_MOUSEWHEEL = 0x020A;
private int WM_MOUSEMOVE = 0x0200;
private int WM_KEYDOWN = 0x0100;
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_LBUTTONDOWN || m.Msg == WM_MBUTTONDOWN || m.Msg == WM_RBUTTONDOWN || m.Msg == WM_MOUSEWHEEL || m.Msg == WM_MOUSEMOVE || m.Msg == WM_KEYDOWN)
{
//User activity has occurred
// Reset a flag / timer etc.
}
return false;
}
}
Then in the Main() method of the form, BEFORE the call to Run():
Application.AddMessageFilter(new UserActivityFilter());
One caveat, adding a complex message filter or adding multiple separate filters can slow down the responsiveness of your application.
In your Program.CS file, you can handle the Application.Idle event and reset your timer there. See:
http://msdn.microsoft.com/en-us/library/system.windows.forms.application.idle.aspx
You can override WndProc, update Program.LastActionTime on each relevant Keyboard/Mouse event message.
Hook an event handler on the MouseMove and KeyPressed events, and then check for focus inside that event?
In general it would be the best idea to derive this information from your application logic instead of raw user input, but I assume you have no flexible infrastructure (maybe using the command pattern) that could provide this information.
So I suggest just to register handlers with your main form - if you receive clicks or key events (enable Form.KeyPreview for this), your user is active and you can reset the inactivity time.
You could create a base class that all your window forms inherits from. In the base class you check and reset your timeout on every KeyPress or Click.

Categories