UserControl KeyDown Event Not Fire Against Revoke Of Windows Application KeyDown Event - c#

I have UserControl and facing problem of KeyDown Event. My UserControls will shows against revoke of windows forms keydown event like below:
User Control’s Event:
private void UserControl_KeyDown(object sender,KeyEventArgs e)
{
if ((Keys)e.KeyCode == Keys.Escape)
{
this.Visible = false;
}
}
The above event will have to hide the UserControl but the event not fire due to revoke of windows forms keydown as below:
Windows Form:
private void button1_Click(object sender, EventArgs e)
{
panel1.SendToBack();
panel2.SendToBack();
panel3.SendToBack();
panel4.SendToBack();
am.Focus();
this.KeyDown -= new KeyEventHandler(Form1_KeyDown);
}
This will shows the UserControls as the UserControls are added to windows forms by as below:
private UserControl.UserControl am = new UserControl.UserControl();
public Form1()
{
InitializeComponent();
this.Controls.Add(am);
}
I want to revoke the keydown event of winform against visible of UserControl and fire the keydown event of UserControl for hide the UserControl but it’s not doing well. The keydown event of UserControl event is not fire. Don’t know why?. How to do the same in proper way?.

Keyboard notifications are posted to the control with the focus. Which is almost never a UserControl, it doesn't want the focus. Even if you explicitly set the focus with the Focus() method, it will immediately pass it off to one of its child controls. UserControl was designed to be just a container for other controls.
Override the ProcessCmdKey() method instead. Paste this code into the control class:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == Keys.Escape) {
this.Visible = false;
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Beware that using the Escape key is not the greatest idea, the Form you put your user control on may well have a need for that key. Like a dialog.

Related

Catching F1 KeyEvent when form has focus.

I need to catch the F1 KeyEvent when it fires regardless of what has current focus. Currently I have a base class that defines the method that is intended to fire upon F1 keyup. In the child class I am listening for the .KeyUp event and will invoke the parent.
//Base class:
protected void GetHelp(String helpIndexParam)
{
// Logic
}
//Child Class:
//Declared in constructor of child class
KeyPreview = true;
this.KeyUp += new System.Windows.Forms.KeyEventHandler(KeyEvent);
private void KeyEvent(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.F1)
{
base.GetHelp("20");
}
}
Currently, a child form opens and I press F1, nothing happens. Only when I click on a control on the form and then press F1 does the GetHelp("") function execute.
Any suggestions appreciated. Cheers.
In this scenario, you may use ProcessCmdKey method in the parent form or each child form:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == Keys.F1) {
// Show help;
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Or since you are looking for F1 key, you can use the HelpRequest event:
public Form1() {
InitializeComponent();
this.HelpRequested += Form1_HelpRequested;
}
private void Form1_HelpRequested(object sender, HelpEventArgs hlpevent) {
// Show Help
}
I was able to get it working. I learned that because we're using an MDI, the MDI itself was apparently consuming any attempt of catching an F1 click in the child form. I basically had to set it up so that the KeyUp event was defined in the parent form as opposed to the child form, and the child form would simply populate the needed properties from the parent form. That's how I was able to pass a the necessary info to the parent. Also, I had to set focus on a control on the child form just so the whole thing could come together.
I appreciate all the help guys. You all pointed me down the right path in the long run. Cheers.

Assigning "escape" key to a button in windows form in C#

I have a simple windows form in C#. my form has a bottun which in Click event is several codes and tasks.
i want to assign escape key on keyboard to this button. how can i do this?
Your form has a property CancelButton. Assign your button to this property. You can easily do that in property window of Visual Studio. Then your button will be clicked when hitting escape.
Set KeyPreview = true; for the form and then override form's OnKeyDown method something like this:
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Modifiers == Keys.None && e.KeyCode == Keys.Escape)
//your button click event handler call here like button1_Click(null, null);
}

Get keydown event without a textbox

Im trying to do like that: If I press the key "P" a messagebox will open in the screen.But I need to do it without a textbox or other tool, I want to do that direct in the form.
I tried:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.P)
{ MessageBox.Show("Key P pressed"); }
}
Try with the KeyPress Event of the form. It just works fine.
Assuming this is Winforms, on the form you're trying to catch the event on, make sure to set
Form1.KeyPreview = true;
KeyPreview ensures that keyboard events anywhere on the particular form (such as to a textbox with focus) will still count as a keyboard event for the form itself.

How to get all KeyPress events as a UserControl in C#?

I've read quite some articles now about key press events but I can't figure out how to get them. I know that only the current control with keyboard focus gets the press events. But how can i ensure that my user control has it?
Tried this without luck:
public partial class Editor : UserControl
this.SetStyle(ControlStyles.Selectable, true);
this.TabStop = true;
...
//take focus on click
protected override void OnMouseDown(MouseEventArgs e)
{
this.Focus();
base.OnMouseDown(e);
}
...
protected override bool IsInputKey(Keys keyData)
{
return true;
}
And also this:
//register global keyboard event handlers
private void Editor_ParentChanged(object sender, EventArgs e)
{
if (TopLevelControl is Form)
{
(TopLevelControl as Form).KeyPreview = true;
TopLevelControl.KeyDown += FCanvas_KeyDown;
TopLevelControl.KeyUp += FCanvas_KeyUp;
TopLevelControl.KeyPress += FCanvas_KeyPress;
}
}
The latter gave me the key down and up events, but still no key press. Is there any other method i can use to just get every down/up/press events when my control inherits from UserControl?
Edit:
As there was a comment linking another SO question: It's important that I also get the KeyPress event, since it sends the correct character on every keyboard no matter which language. This is important for text writing. If you only get the individual keys you have to process them into the correct character on your own. But maybe there is a convenience method to transform the pressed keys into a localized character?
Set your parent form's (contains the usercontrol) KeyPreview property to true
Add a new KeyPress event to your parent form
Set the parent form keypress event to forward the event to your usercontrol:
private void parentForm_KeyPress(object sender, KeyPressEventArgs e)
{
// Forward the sender and arguments to your usercontrol's method
this.yourUserControl.yourUserControl_KeyPress(sender, e);
}
Replace the yourUserControl1_KeyPress method with your own method, which you want to run each time the user presses a button (the button is pressed down and then released).
You can also create a new KeyPress handler to your usercontrol, and forward the sender and KeyPressEventArgs objects there, as in this example.
Can you attach to form event.
Private Sub MyControl_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim f = Me.FindForm
If Not f.KeyPreview Then Throw New Exception("Form requires has Keypreview enabled")
AddHandler f.KeyUp, Sub(sender2 As Object, e2 As KeyEventArgs)
End Sub
End Sub

Sending keystrokes to control in .Net

My ActiveX control contains various shapes which are drawn. CTRL-A is used in the control to select all the objects. Similarly CTRL-C to copy, CTRL-V to paste etc.
However, when I insert this control within a Windows form in a .Net application, it does not receive these keyboard events. I tried adding a PreviewKey event, and this does allow certain keystrokes to be sent e.g. TAB, but not these modified keys.
Does anybody know how to redirect modified keystrokes to a user control?
Thanks.
It's possible that the ActiveX control doesn't have focus and is therefore not receiving the key events. You may want to handle the key events at the form level and then call the appropriate methods on your ActiveX control. If you set the KeyPreview property of your form to true your form will receive the key events for all controls on the form. That way, your shortcuts should work no matter what control currently has focus. Here is a quick example you can play with to test this out. Create a new form with several different controls on it and modify the code like so:
public Form1()
{
InitializeComponent();
KeyPreview = true; // indicates that key events for controls on the form
// should be registered with the form
KeyUp += new KeyEventHandler(Form1_KeyUp);
}
void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.Modifiers == Keys.Control)
{
switch (e.KeyCode)
{
case Keys.A:
MessageBox.Show("Ctrl + A was pressed!");
// activeXControl.SelectAll();
break;
case Keys.C:
MessageBox.Show("Ctrl + C was pressed!");
// activeXControl.Copy();
break;
case Keys.V:
MessageBox.Show("Ctrl + V was pressed!");
// activeXControl.Paste();
break;
}
}
}
No matter what control has focus when you enter the key combinations, your form's Form1_KeyUp method will be called to handle it.
You need to trap the keys and override the ProcessCmdKey method.
class MyDataGrid : System.Windows.Forms.DataGrid
{
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
...........
}
}
http://support.microsoft.com/kb/320584
KeyPreview is just the wrong method. Try using KeyUp or KeyDown, like this:
private void ControlKeyTestForm_KeyUp(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.A)
this.label1.Text = "Ctrl+A pressed";
}
If you want the containing form to deal with shortcut keys remember to set the KeyPreview property on the form to true then set the KeyDown or KeyUp handlers in the form.
Use Control.ModifierKeys Property to check for Modifier keys.
For example, to check for shift key,
try if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift) { }
Full example here:
http://msdn.microsoft.com/en-us/library/aa984219%28VS.71%29.aspx

Categories