i wanna trigger a keyup event just by calling the form and not pressing a key
Heres my code:
if (dr.HasRows)
{
FrmQty fqty = new FrmQty(this);
fqty.ProductDetails(dr["ProductID"].ToString(), float.Parse(dr["ProductPrice"].ToString()), lblTransno.Text);
fqty.txtQty.Text = "1";
fqty.txtQty_KeyUp();//i wanna trigger it here by pressing "Enter" key. its an event from FormQty
fqty.ShowDialog();
}
You can do:
private void myForm_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
MyEnterKeyDownFunc();
else
{
//your other keys management
}
}
public void MyEnterKeyDownFunc()
{
//do your enter key down stuff here
// if you want to modify anything on the UI, you should make sure it
// is invoked in the GUI thread. Maybe something like:
if (aControl.InvokeRequired)
{
aControl.BeginInvoke((MethodInvoker)delegate ()
{
// GUI modifications
});
}
else
{
// GUI modifications
}
}
Now you can call MyEnterKeyDownFunc() from outside your class
One (probably better) solution is to make a handler function public and simple call it.
Another may be a simulation of key press using SendKeys:
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.sendkeys?view=net-5.0
Related
In my program I would need that an action is perfomed while a key is pressed. I have already searched but the solutions either were not for c#, neither for forms or I couldnt understand them.
Is there a proper and easy solution to this?
EDIT: I am using WinForms and I want that while the form is focussed and a key is pressed an action is repeatedly performed.
First off, you need to provide a bit more information and if possible some code you already tried. But nevertheless I'll try. The concept is relatively easy, you add a timer to your form, you add key_DOWN and key_UP events (not key pressed). You make a bool that resembles if key is currently pressed, you change its value to true on keydown and false on keyup. It will be true while you hold the key.
bool keyHold = false;
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (keyHold)
{
//Do stuff
}
}
private void Key_up(object sender, KeyEventArgs e)
{
Key key = (Key) sender;
if (key == Key.A) //Specify your key here !
{
keyHold = false;
}
}
private void Key_down(object sender, KeyEventArgs e)
{
Key key = (Key)sender;
if (key == Key.A) //Specify your key here !
{
keyHold = true;
}
}
**If you're trying to make a simple game on forms and you're struggling with the input delay windows has (press and hold a key, it will come up once, wait and then spam the key) This solution works for that (no pause after the initial press).
You can try this.
In the Key down event you set the bool 'buttonIsDown' to TRUE and start the method 'DoIt' in an Separate Thread.
The code in the While loop inside the 'DoIt' method runs as long the bool 'buttonIsDown' is true and the Form is on Focus.
It stops when the Key Up event is fired or the Form loose the focus.
There you can see the 'buttonIsDown' is set to false so that the While loop stops.
//Your Button Status
bool buttonIsDown = false;
//Set Button Status to down
private void button2_KeyDown(object sender, KeyEventArgs e)
{
Key key = sender as Key;
if (key == Key.A)
buttonIsDown = true;
//Starts your code in an Separate thread.
System.Threading.ThreadPool.QueueUserWorkItem(DoIt);
}
//Set Button Status to up
private void button2_KeyUp(object sender, KeyEventArgs e)
{
Key key = sender as Key;
if (key == Key.A)
buttonIsDown = false;
}
//Method who do your code until button is up
private void DoIt(object dummy)
{
While(buttonIsDown && this.Focused)
{
//Do your code
}
}
I have a program containing multiple C# Forms TextBoxes. I've set up Hotkeys for the entire form activating certain functions. My problem is that my Hotkeys have been set onto the Form KeyDown event and they activate if I write something on a TextBox.
Example: One Hotkey might be I. Everytime I write the letter onto a textbox the Hotkey activates.
Alterior solutions and problems: I've thought about putting a Key in front of the Hotkey like CTRL+Hotkey, but these also present problems as CTRL+C is Windows Copy command etc. SHIFT is an UpperKey button.
Question: Can I prevent Hotkeys from activating when I am writing onto a TextBox without having to go through all of them in the form?
EDIT: Some code as requested. The button codes come from a stored XML file or the Hotkeys Form+Class (separate) where I've set up a window for them.
public Hotkeys hotkeysForm = new Hotkeys();
void Form1_KeyDown(object sender, KeyEventArgs e)
{
toggleInformation = hotkeysForm.toggleInformation;
if (e.Control && e.KeyCode == toggleInformation)
{
showInfo(true);
}
else if (e.KeyCode == toggleInformation)
{
if (!isInfoActive)
showInfo();
else
hideInfo();
}
}
You can disable hotkeys while texbox is an active control. Add the Enter and Leave events for all textboxes:
private void textBox_Enter(object sender, EventArgs e)
{
KeyPreview = false;
}
private void textBox_Leave(object sender, EventArgs e)
{
KeyPreview = true;
}
You should try this hack, if it could solve your problem,
Create a Extented TextBox and use it in your code. you can handle whether to write the pressed key in textbox or not in hotkeyPressed check.
public class ETextBox : System.Windows.Forms.TextBox
{
protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e)
{
if (hotKeyPressed) // this is the condition when you don't want to write in text.
{
//Do whatever you want to do in this case.
}
else
{
base.OnKeyDown(e);
}
}
}
I have a problem that I'm struggling with..
I want to move an image using my keyboard to the left, right, up or down and in a diagonal way.
I searched the web and found, that to use 2 diffrent keys I need to remember the previous key, so for that I'm using a bool dictionary.
in my main Form class this is how the KeyDown event looks like:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
baseCar.carAccelerate(e.KeyCode.ToString().ToLower());
carBox.Refresh(); //carbox is a picturebox in my form that store the image I want to move.
}
My KeyUp event:
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
baseCar.carBreak(e.KeyCode.ToString().ToLower());
}
My Paint event:
private void carBox_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(Car, baseCar.CharPosX, baseCar.CharPosY); // Car is just an image
}
And my baseCar class:
private Dictionary KeysD = new Dictionary();
// there is a method to set the W|A|S|D Keys, like: KeysD.Add("w",false)
public void carAccelerate(string moveDir)
{
KeysD[moveDir] = true;
moveBeta();
}
public void moveBeta()
{
if (KeysD["w"])
{
this.CharPosY -= this.carMoveYSpeed;
}
if (KeysD["s"])
{
CharPosY += carMoveYSpeed;
}
if (KeysD["a"])
{
CharPosX -= carMoveXSpeed;
}
if (KeysD["d"])
{
CharPosX += carMoveXSpeed;
}
}
public void carBreak(string str)
{
KeysD[str] = false;
}
Anyway it works, but my problem is that I can't get back to the first pressed key for example:
I pressed W to move up and then the D key to go diagonal, how ever when I release the D key it wont go Up again because the KeyDown event is "dead" and wont call the carAccelerate() method again..
and I can't figure out how to fix it..
Can any one help me please?
Maybe there is a better way to handle the keys? im open to any ideas!
And I hope you can understand it, my english isnt the best :S
Store all keystates and don't animate on keypress, but for example using a timer.
Then:
KeyDown(key)
{
KeyState[key] = true;
}
KeyUp(key)
{
KeyState[key] = false;
}
Timer_Tick()
{
Animate();
}
Animate()
{
if (KeyState["W"])
{
// Accelerate
}
if (KeyState["S"])
{
// Decelerate
}
}
Then in the KeyDown method you can check for conflicting keys (what if accelerate + decelerate are pressed at the same time, and so on).
I WPF I need to set a boolean variable (and additionally perform some other actions) while a key is pressed. I.e. to set on the key is pressed, and to reset on the key is released. Something that I can do by just event handlers:
this.KeyDown += new KeyEventHandler(MyModuleView_KeyDown);
this.KeyUp += new KeyEventHandler(MyModuleView_KeyUp);
bool MyFlag = false;
void MyModuleView_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Space)
{
MyFlag = false;
...
}
}
void MyModuleView_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Space)
{
MyFlag = true;
...
}
}
But I suspect in WPF it can be done in a more correct way.
I'm trying to use a command approach, but in the way I do it I can only set a variable on the fact of pressing a key but not while a key is pressed.:
private static RoutedUICommand mymode;
InputGestureCollection inputs = new InputGestureCollection();
inputs.Add(new KeyGesture(Key.Space, "Space"));
mymode = new RoutedUICommand("MyMode", "MyMode", typeof(InterfaceCommands), inputs);
public static RoutedUICommand MyMode
{
get { return mymode; }
}
...
private void MyModeCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
MyFlag = true;
...
}
How to correctly track the state of a key in WPF for turning on something (for example selection mode of a cursor) while the key is pressed?
Commands will not help you here, your approach with events is a right way to go. If you don't like to have a code-behind - you can create a custom attached property, which would be responsible for events wiring.
Have a look at AttachedCommandBehavior library and examples provided
I have a C# form with 5 buttons. The users enters the information and depending on the press of a function key, a specific action is performed. F9-Execute Order, F6-Save, F3-LookUp.
I have added the foolowing code:
OnForm_Load
this.KeyUp += new System.Windows.Forms.KeyEventHandler(KeyEvent);
and
private void KeyEvent(object sender, KeyEventArgs e) //Keyup Event
{
if (e.KeyCode == Keys.F9)
{
MessageBox.Show("Function F9");
}
if (e.KeyCode == Keys.F6)
{
MessageBox.Show("Function F6");
}
else
MessageBox.Show("No Function");
}
but nothing happens
Thanks
You need to set
KeyPreview=True
for your form. Otherwise key press is swallowed by the control that has focus.