C# 将击键发送到其他控件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1264227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:23:40  来源:igfitidea点击:

Send keystroke to other control

c#forwardingkeystroke

提问by vIceBerg

Easy one for you guys.

给你们一个简单的。

I have a textbox on top of a listbox.

我在列表框顶部有一个文本框。

The textbox is use to filter ther data in the listbox.

文本框用于过滤列表框中的数据。

So... When the user type in the textbox, I would like to "trap" the down/up/pagedown/pageup keystrokes and fowarding them to the listbox.

所以......当用户在文本框中键入时,我想“捕获”向下/向上/翻页/翻页键击并将它们转发到列表框。

I know I could use the Win32 API and send the WM_KeyDown message. But there's must be some .NET way to do this.

我知道我可以使用 Win32 API 并发送 WM_KeyDown 消息。但是必须有一些 .NET 方法来做到这一点。

采纳答案by adatapost

SendKeys.Send() Method.

SendKeys.Send() 方法。

 private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            listBox1.Focus();
            SendKeys.Send(e.KeyChar.ToString());
        }

Here is code through which you can select a list item.

这是您可以选择列表项的代码。

private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            textBox1.AutoCompleteSource=AutoCompleteSource.CustomSource;
            string[] ar = (string[])(listBox1.Items.Cast<string>()).ToArray<string>();
            textBox1.AutoCompleteCustomSource.AddRange(ar);
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            listBox1.Text  = textBox1.Text;
        }

回答by Jacob Seleznev

You can use Data Binding

您可以使用数据绑定

            listBox1.DataBindings.Add("DataSource", textBox1, "Text", true, DataSourceUpdateMode.OnPropertyChanged).
            Format += (sender, e) =>
            {
                e.Value = _strings.FindAll(s => s.StartsWith((string) e.Value));
            };

回答by Eric

In our wpf app we have a textbox that filters a listbox, we use the previewkeyup event. Inside the code, we can check what key was pressed (don't have my code in front of me, it's something like e.Key == Key.UpArrow, either way there's a built in class in C# for this). If it's one of the hot keys, we manipulate the user control accordingly.

在我们的 wpf 应用程序中,我们有一个过滤列表框的文本框,我们使用 previewkeyup 事件。在代码中,我们可以检查按下了什么键(不要在我面前放我的代码,它类似于 e.Key == Key.UpArrow,无论哪种方式,C# 中都有一个内置类)。如果它是热键之一,我们会相应地操纵用户控件。

For the listbox we tossed it into a user control and implemented an interface, called it NavigateableListbox or something like that, forced it to implement MoveUp(), MoveDown(), PageUp(), PageDown() etc so the textbox event just says if e.Key = Key.UpArrow { mylistbox.MoveUp() }

对于列表框,我们将其放入用户控件并实现了一个接口,称为 NavigateableListbox 或类似的东西,强制它实现 MoveUp()、MoveDown()、PageUp()、PageDown() 等,因此文本框事件只是说如果e.Key = Key.UpArrow { mylistbox.MoveUp() }

回答by Stacey Richards

    private void textBox_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        if (e.KeyCode == Keys.PageUp || e.KeyCode == Keys.PageDown || e.KeyCode == Keys.Up || e.KeyCode == Keys.Down)
        {
            // Setting e.IsInputKey to true will allow the KeyDown event to trigger.
            // See "Remarks" at https://msdn.microsoft.com/en-us/library/system.windows.forms.control.previewkeydown(v=vs.110).aspx
            e.IsInputKey = true;
        }
    }

    private void textBox_KeyDown(object sender, KeyEventArgs e)
    {
        string send = "";
        if (e.KeyCode == Keys.PageUp)
        {
            send = "PGUP";
        }
        else if (e.KeyCode == Keys.PageDown)
        {
            send = "PGDN";
        }
        else if (e.KeyCode == Keys.Up)
        {
            send = "UP";
        }
        else if (e.KeyCode == Keys.Down)
        {
            send = "DOWN";
        }
        if (send != "")
        {
            // We must focus the control we want to send keys to and use braces for special keys.
            // For a list of all special keys, see https://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.send(v=vs.110).aspx.
            listBox.Focus();
            SendKeys.SendWait("{" + send + "}");
            textBox.Focus();
            // We must mark the key down event as being handled if we don't want the sent navigation keys to apply to this control also.
            e.Handled = true;
        }
    }

回答by schlebe

SendKeys.Send()method does'nt work in all situations because Send()method can be addressed to another Control !

SendKeys.Send()方法并非在所有情况下都有效,因为Send()方法可以寻址到另一个 Control !

In 2020, the best solution to be sure at 100% is to use SendMessage() function.

在 2020 年,确保 100% 的最佳解决方案是使用 SendMessage() 函数。

In VB.Net, I use following code

在 VB.Net 中,我使用以下代码

Public Declare Auto Function SendMessage Lib "user32.dll"
    ( ByVal hWnd As IntPtr
    , ByVal wMsg As Int32
    , ByVal wParam As Int32
    , ByVal s As Int32
    ) As Int32

Private Const WM_CHAR As Int32 = &H102

SendMessage(txtInput.Handle, WM_CHAR, AscW(sValue.Chars(0)), 0)

Where txtInputis a sample Textboxcontrol.

txtInput样品Textbox对照在哪里。

In my case, I click on html <div>element defined in a WebViewcontrol that changes color when I click on it or when mouse move over. When I click on this <div>a ScriptNotify() VB.Net method is called to enter some characters in Textboxusing SendMessage()function.

在我的例子中,我点击<div>了一个WebView控件中定义的html元素,当我点击它或鼠标移过它时会改变颜色。当我点击这个<div>ScriptNotify() VB.Net 方法被调用以在TextboxusingSendMessage()函数中输入一些字符。

In old solution, I think that sometimes, WebViewgain focus before SendKeys.Send()method is called so that propagated key is not send to txtInputTextbox.

在旧的解决方案中,我认为有时WebViewSendKeys.Send()调用方法之前获得焦点,以便传播的密钥不会发送到txtInput文本框。

You can use old solution, but be certain that one day, SendKeys.Send() function will send what you want to another Handle.

您可以使用旧的解决方案,但请确保有一天,SendKeys.Send() 函数会将您想要的内容发送到另一个句柄。