Csharp/C#教程:将键击发送到其他控件分享


将键击发送到其他控件

对你们来说很容易。

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

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

所以…当用户输入文本框时,我想“陷阱”向下/向上/向下/向下翻页击键并将它们发送到列表框。

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

SendKeys.Send()方法。

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

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

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

您可以使用数据绑定

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

  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; } } 

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

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

上述就是C#学习教程:将键击发送到其他控件分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1014426.html

(0)
上一篇 2021年12月30日
下一篇 2021年12月30日

精彩推荐