Sign in to follow this  

[.net] Forcing a key press on a control

This topic is 3303 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

So I have some code where I want to force either the up or down key on a control. I am able to do this:
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
                    SendKeys.Send("{TAB}"); //sends the tab to the next control
                    
                    //process the up/down key
                    if (keyData == Keys.Up)
                        SendKeys.Send("{UP}");
                    else if (keyData == Keys.Down)
                        SendKeys.Send("{DOWN}");

                    base.ProcessCmdKey(ref msg, keyData);

                    //go back to the original control
                    SendKeys.Send("+{TAB}");
        }
This relies on the fact that the tabs are set up correctly. I would rather do something like this:
                    
                    controlThatNeedsInput.Focus();
                    
                    //process the up/down key
                    if (keyData == Keys.Up)
                        SendKeys.Send("{UP}");
                    else if (keyData == Keys.Down)
                        SendKeys.Send("{DOWN}");

                    base.ProcessCmdKey(ref msg, keyData);

                    originalControl.Focus();

This doesn't work however. The focus appears to change in code but the SendKeys never fires off in the control that just received focus. Any ideas on how to fix this or if there's a better way?

Share this post


Link to post
Share on other sites
I think you'll have better luck with sending messages directly to the controls message pump. You can use the Win32 API SendMessage function to do that: http://pinvoke.net/default.aspx/user32/SendMessage.html.

Construct a WM_KEYDOWN/WM_KEYUP message pair and send them to your control. Then you don't need to mess with focus.

Share this post


Link to post
Share on other sites

This topic is 3303 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this