I want to write simple program that send my user and password in some places for example when I want to log in to website and i found this project that listening to keyboard.
SO i have this function:
private void HookManager_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
}
private void HookManager_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
}
private void HookManager_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
}
And when i press key for example a i have this pice of result:
int value = e.KeyValue; // 65
Keys key = e.KeyCode; // A
So i wondoer how to catch specific keyboard combination and not only one key for example Ctrl + l ?
You can use code like this for KeyDown:
if(e.KeyCode == Keys.F1 && (e.Alt || e.Control || e.Shift))
{
}
Based on the KeyEventArgs documentation from MSDN:
A KeyEventArgs, which specifies the key the user pressed and whether any modifier keys (CTRL, ALT, and SHIFT) were pressed at the same time, is passed with each KeyDown or KeyUp event.
The KeyDown event occurs when the user presses any key. The KeyUp
event occurs when the user releases the key. Duplicate KeyDown events
occur each time the key repeats, if the key is held down, but only one
KeyUp event is generated when the user releases the key.
The KeyPress event also occurs when a key is pressed. A
KeyPressEventArgs is passed with each KeyPress event, and specifies
the character that was composed as a result of each key press.
Overriding the ProcessDialogKey() method is the generic solution:
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == (Keys.Control | Keys.I))
{
MessageBox.Show("Ctrl+I");
return true;
}
return base.ProcessDialogKey(keyData);
}
Related
How do I set the keyboard shortcut character for a Windows Forms button with no text?
I have a Windows Forms app with some buttons with images but no text. Normally for a button, the shortcut is specified with the ampersand character (&). But what does one do when there's no text?
I know there are tricks, such as leading spaces to push the text off to the right or down. Or play with the font, forecolor, etc. But I don't like such tricks because they sometimes backfire.
Should I consider handling the shortcuts for all controls through the Key events of the form? How would this sort out which control is selected? Are form Key events filtered through the form before they're sent on to the Key events of the controls? I'm not sure what to do if I went this way.
Should I consider handling the shortcuts for all controls through the Key events of the Form?
You sure can, overriding ProcessCmdKey() in your Form(s). As you can read in the docs, it's kind of made for this (to provide additional handling of main menu command keys and MDI accelerators)
To associate a Button to a bitwise combination of Keys (the Windows Forms Keys enumerator is decorated with the [Flags] attribute), you can use a map, often a Dictionary that associates a Key to something else.
In this case, it could be a Button Control or an Action. For example:
private Dictionary<Keys, Button> accelerators = null;
protected override void OnLoad(EventArgs e) {
accelerators = new Dictionary<Keys, Button>() {
[Keys.Alt | Keys.A] = someButton,
[Keys.Alt | Keys.Control | Keys.B] = otherButton
};
base.OnLoad(e);
}
In the ProcessCmdKey override, test whether the map (Dictionary) contains the combination of keys pressed and raise the Click event of the associated Button if it's a match:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (accelerators.ContainsKey(keyData)) {
accelerators[keyData].PerformClick();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
VB.Net version (since it's tagged):
Private accelerators As Dictionary(Of Keys, Button) = Nothing
Protected Overrides Sub OnLoad(e As EventArgs)
accelerators = New Dictionary(Of Keys, Button)() From {
{Keys.Alt Or Keys.A, someButton},
{Keys.Alt Or Keys.Control Or Keys.B, otherButton}
}
MyBase.OnLoad(e)
End Sub
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
If accelerators.ContainsKey(keyData) Then
accelerators(keyData).PerformClick()
Return True
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
This is how I do it.
set the KeyPreview to true for the form to capture keys.
then check the keys on KeyDown event on the form and trigger button1.PerformClick();
public Form1()
{
InitializeComponent();
KeyPreview = true;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("you pressed Ctrl + S");
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.S)
{
button1.PerformClick();
}
}
Hope this can help you.
Set your Form KeyPreview Property to true.
Subscribe to the KeyDown Event of the Form as below:
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
Handle the KeyDown event of Form as below:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.S)
MessageBox.Show("Ctrl + S pressed!");
}
Complete Code:
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.S)
MessageBox.Show("Ctrl + S pressed!");
}
I'm trying to run some functions in my app when the Enter key is pressed on the keyboard, but I'm having problems in doing that.
KeyboardControl is in the KeyDown of my textbox.
Key.Enter is not recognized as a function, and I don't know what to do.
// When a key is pressed on the keyboard
private void KeyboardControl(object sender, KeyEventArgs e)
{
if (e.KeyStatus == Key.Enter)
{
PercentCalc();
PercentageValue.Text = Convert.ToString(result, new CultureInfo("en-US")) + "%";
}
}
Attach KeyDown event to your TexBox like this :
<TextBox KeyDown="Box_KeyDown" />
at the backend keydown event check if the pressed key is Enter and then execute your code in that if condition.
private async void Box_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Enter)
{//execute code here
PercentCalc();
PercentageValue.Text = Convert.ToString(result, new CultureInfo("en-US")) + "%";
}
}
you were trying to check the KeyStatus which is not required in your usecase, instead you should be checking which key is pressed.
I have to catch the event when I pressed on Shift Tab in TextBox to write some code. It is possible to do that? I tried with that test on KeyUp event :
private void txtJustifTampon_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab && Control.ModifierKeys == Keys.ShiftKey)
{
//do stuff
}
}
One of the possible ways out is to use PreviewKeyDown instead of KeyUp since
Some key presses, such as the TAB, RETURN, ESC, and arrow keys, are
typically ignored by some controls because they are not considered
input key presses
private void txtJustifTampon_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) {
// If Shift + Tab pressed (i.e. Tab with Shift modifier)
if (e.KeyCode == Keys.Tab && e.Modifiers == Keys.Shift) {
//TODO: put relevant code here (do stuff)
}
}
Please, notice that we should use Keys.Shift (not Keys.ShiftKey) as the modifier and we should apply modifier to the event argument (e.Modifiers)
I would like to perform some actions when the user presses Ctrl + K on a textbox.
private void subject_TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.K)
MessageBox.Show("!");
}
Nothing happens when I run it.
When I debug I can see that e.Control is true (this means I pressed Ctrl) but the e.KeyCode is not equivalent to K.
Any ideas?
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.K) && focusedTextbox == subject_TextBox)
{
//Some Code
}
}
private TextBox focusedTextbox = null;
private void subject_TextBox_KeyDown(object sender, KeyEventArgs e)
{
MethodName(e.KeyCode)
}
private void MethodName(Keys keys)
{
focusedTextbox = (TextBox)sender;
}
Use this code, this should work i have tested it myself and it will work, you will want to run the 'MethodName' method in each textbox, or if you can find a better way to change the 'focusedTextBox' field then do that hope this helped.
In the KeyDown event, you just ask for the 'state' of the keyboard.
You might want to check out this topic:
Capture multiple key downs in C#
Really don't know what is the problem reason.
May the event is fired as soon as the Ctrl is pressed, without waiting to the K to be pressed as well.
However, when I use the same code in the TextBox_KeyUp event, it works fine.
Despite me working with C# (Windows Forms) for years, I'm having a brain fail moment, and can't for the life of me figure out how to catch a user typing Ctrl + C into a textbox.
My application is basically a terminal application, and I want Ctrl + C to send a (byte)3 to a serial port, rather than be the shortcut for Copy to Clipboard.
I've set the shortcuts enabled property to false on the textbox. Yet when the user hits Ctrl + C, the keypress event doesn't fire.
If I catch keydown, the event fires when the user presses Ctrl (that is, before they hit the C key).
It's probably something stupidly simple that I'm missing.
Go ahead and use the KeyDown event, but in that event check for both Ctrl and C, like so:
if (e.Control && e.KeyCode == Keys.C) {
//...
e.SuppressKeyPress = true;
}
Also, to prevent processing the keystroke by the underlying TextBox, set the SuppressKeyPress property to true as shown.
Key events occur in the following order:
KeyDown
KeyPress
KeyUp
The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.
Control is a noncharacter key.
You can check with this line of code:
if (e.KeyData == (Keys.Control | Keys.C))
I had a problem catching Ctrl + C on a TextBox by KeyDown. I only got Control key when both Control and C were pressed. The solution was using PreviewKeyDown:
private void OnLoad()
{
textBox.PreviewKeyDown += OnPreviewKeyDown;
textBox.KeyDown += OnKeyDown;
}
private void OnPreviewKeyDown( object sender, PreviewKeyDownEventArgs e)
{
if (e.Control)
{
e.IsInputKey = true;
}
}
private void OnKeyDown( object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.C) {
textBox.Copy();
}
}
D'oh! Just figured it out. Out of the three possible events, the one I haven't tried is the one I needed! The KeyUp event is the important one:
private void txtConsole_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyData == (Keys.C | Keys.Control))
{
_consolePort.Write(new byte[] { 3 }, 0, 1);
e.Handled = true;
}
}
If you want to catch such combinations of keys in KeyPress Event look at this table here:
http://www.physics.udel.edu/~watson/scen103/ascii.html
in Non-Printing Characters section you can see the Dec numbers for each combination.
For example, Dec number for Ctrl + C is 3. So you can catch it in KeyPress Event like this:
private void btnTarget_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != 3) // if it is not Ctrl + C
{
// do something
}
}
Try the following: capture the up arrow and down arrow events. When you detect down arrow for CTRL, set a flag; when you detect up arrow, reset the flag. If you detect the C key while the flag is set, you have Ctrl+C.
Edit. Ouch... Jay's answer is definitely better. :-)
I don't know if it's because some change in newer version or because I am trying to use this on ListBox, but there is no e.Control in KeyEventArgs e that I get from KeyDown.
I had to work around solution, I came up with this (it's not the prettiest one, but it works fine):
private List<Key> KeyBuff = new List<Key>();
private void ListBox_KeyDown(object sender, KeyEventArgs e)
{
if (!KeyBuff.Exists(k => k == e.Key))
KeyBuff.Add(e.Key);
if (KeyBuff.Exists(k => k == Key.LeftCtrl || k == Key.RightCtrl) &&
KeyBuff.Exists(k => k == Key.C))
{
// Desired detection
Clipboard.SetText(SelectedText);
}
}
private void ListBox_KeyUp(object sender, KeyEventArgs e)
{
KeyBuff.Clear();
}
For me, it's not working with KeyDown event so I tried with PreviewKeyDown and it's worked.
private void txt_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.Control == true && e.KeyCode == Keys.C)
{
Clipboard.SetText(txt.SelectedText);
}
}