0

I want to catch keyup event of parent form in a usercontrol. I use ProcessCmdKey but it just give me keydown event and it doesn't raise in keyup event. How can I do it?

Update: I want to catch keyup event of form. because Control.KeyUp raised when control is focused.

public partial class ExtendedButton : Button { const int WM_KEYDOWN = 0x100; public ExtendedButton() { InitializeComponent(); } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (msg.Msg == WM_KEYUP && keyData == (Keys.NumPad0)) { MessageBox.Show("hi"); } return base.ProcessCmdKey(ref msg, keyData); } } 
5
  • 1
    Why so complicated? See stackoverflow.com/questions/18604633/… Commented Sep 11, 2014 at 4:20
  • @user2864740 I want to use keyup event in usercontrol not in the form Commented Sep 11, 2014 at 4:23
  • 1
    There is Control.KeyUp .. still not sure what the complication is for. Commented Sep 11, 2014 at 4:24
  • @user2864740 I want to catch keyup event of of form. because Control.KeyUp raised when control is focused. Commented Sep 11, 2014 at 4:29
  • You might have keep a list of Controls you want to bubble down to. Kinda like how programs keeps all Windows' Title Bar active no matter which one has focus. Commented Sep 11, 2014 at 5:40

1 Answer 1

1

You can create handler for Parent Form KeyUp in UserControl's OnHandleCreated override method.

Try this code

Form parentForm = null; private void ParentForm_KeyUp(object sender, KeyEventArgs e) { MessageBox.Show("HI"); } protected override void OnHandleCreated(EventArgs e) { if (DesignMode) return; base.OnHandleCreated(e); object parent = this; while (true) { parent = ((Control)parent).Parent; if (parent.GetType().BaseType.Name == "Form") break; } parentForm = (Form)parent; parentForm.KeyUp -= new KeyEventHandler(this.ParentForm_KeyUp); parentForm.KeyUp += new KeyEventHandler(this.ParentForm_KeyUp); } 
Sign up to request clarification or add additional context in comments.

4 Comments

what is happening? Getting any error? Have you set the KeyPreview property of your parent form to true?
yes I set KeyPreview property. no error but keyup event doesn't raised.
have you tried to debug the code? Is OnHandleCreated event getting fired or not? user control unable to create handler for parent form key up event then it will not be fired. try to place break point on parentForm = (Form)parent; line and debug it what value in stored in parent object.
OnHandleCreated fired and and the value of parentForm is true. but events doesn't fire.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.