我已经获得了热键列表框的以下代码(此帖子缩写的数据集)。
我要做的是按下listview组件中的一个键(例如' 2')并将热键列表框设置为2.
感谢您的帮助。
private void listView_KeyPress(object sender, KeyPressEventArgs e)
{
// this line doesn't work !!!
listBoxHotKeys.SelectedItem = e.KeyChar.ToString();
e.Handled = true;
}
private List<HotKey> comboListHotKey = new List<HotKey>();
comboListHotKey.Add(new HotKey("0", 48));
comboListHotKey.Add(new HotKey("1", 49));
comboListHotKey.Add(new HotKey("2", 50));
comboListHotKey.Add(new HotKey("3", 51));
comboListHotKey.Add(new HotKey("4", 52));
listBoxHotKeys.DataSource = comboListHotKey;
listBoxHotKeys.DisplayMember = "TextName";
public class HotKey
{
public HotKey(string textName, uint keyCode)
{
TextName = textName;
KeyCode = keyCode;
}
public string TextName { get; set; }
public uint KeyCode { get; set; }
}
答案 0 :(得分:0)
尝试
private void listView_KeyPress(object sender, KeyPressEventArgs e)
{
int index = listBoxHotKeys.FindString(e.KeyChar.ToString(),-1);
if(index != -1) //-1 index means it did not find an item
listBoxHotKeys.SetSelected(index,true);
e.Handled = true;
}
这推荐在this MSDN文章
中答案 1 :(得分:0)
这是vb示例,但您可以转换它:
更新:(此工作正常)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim pp As New List(Of HotKey)
pp.Add(New HotKey("0", 48))
pp.Add(New HotKey("1", 49))
pp.Add(New HotKey("2", 50))
pp.Add(New HotKey("3", 51))
pp.Add(New HotKey("4", 52))
pp.Add(New HotKey("5", 53))
ListBox1.DataSource = pp
ListBox1.DisplayMember = "TextName"
ListBox1.ValueMember = "KeyCode"
End Sub
Private Sub ListBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ListBox1.KeyPress
For x = 0 To ListBox1.Items.Count - 1
Dim pp As HotKey = CType(ListBox1.Items(x), HotKey)
If Asc(e.KeyChar) = pp.KeyCode Then
ListBox1.SelectedIndex = x
e.Handled = True
Exit For
End If
Next
'or just use : ListBox1.SelectedValue = Asc(e.KeyChar) : e.Handled = True
End Sub
End Class
Public Class HotKey
Private _name As String
Private _key As Integer
Public Sub New(ByVal textName As String, ByVal keyCode As Integer)
_name = textName
_key = keyCode
End Sub
Public Property TextName As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Property KeyCode As Integer
Get
Return _key
End Get
Set(ByVal value As Integer)
_key = value
End Set
End Property
End Class
要认真,lamorach会为您提供正确答案,但需要进行一些转换,因为e.KeyChar
会返回char
值。
在每个人的解决方案中,使用e.KeyChar
功能无法将uint
转换为Asc
。或者,我认为在c#
你必须使用(int)e.KeyChar
(我不确定,不是用c#编程)。
答案 2 :(得分:0)
如果你有的话,我会通过更新所选的值来设置它。
private void listView_KeyPress(object sender, KeyPressEventArgs e)
{
listBoxHotKeys.SelectedValue = e.KeyChar;
e.Handled = true;
}
我也相信您需要将列表框的ValueMember设置为等于项目的keyCode。
listBoxHotKeys.ValueMember = "KeyCode";