C#_用鼠标或键盘按下按钮



好的,所以在我的程序中,我尝试制作按钮,并为每个按下的按钮分配不同的方法。但我遇到了一个问题,我还希望用户使用他的键盘,并将键盘上按下的按钮分配到屏幕上的相同按钮中。然而,首先,我尝试了鼠标或键盘按下按钮,但该方法不允许在"EventArgs"中出现KeyEvents(这对我来说很好(,所以我创建了不同的方法,并创建了一个布尔变量,这样,如果在那个单独的方法中按下键,则使该变量为true,而在那个主方法中,如果为true,则执行代码,但是程序忽略了键盘变量,我不知道为什么。

然后我试着制作一个不同的课程,因为我认为这可能会有所帮助。现在我可以在里面调用那个类和方法,但不能传递参数,因为它说它是一个方法,所以它不能做任何其他事情,只能被调用。

如果你很好奇,下面是代码。。。

___
// the button '1' variable
bool pressOne = false;
___
// method for if that button is pressed
private void AnyNumberClick(object sender, EventArgs e)
{
Button btnSender = (Button)sender;
if (btnSender == btn_Num1 || pressOne)
{
// if button is pressed by either, perform code   
}
}
___
// method for detecting which key is pressed for certain bool variable into button's method
public void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.D1)
{
pressOne = true;
}
else
{
pressOne = false;
}
___
// Call another class inside 'From1_KeyDown' method
Class1 newclass = new Class1();
newclass.buttonused();
NumResult.Text = newclass.buttonused.num();

我不知道如何开始上课。我甚至不知道新课是否会对我有所帮助。我做了研究,但没有找到答案。我很感激从中得到的任何帮助。

试试这种方法。我设置了一个Dictionary<Keys, Button>来表示键和按钮之间的关系。然后,我已经覆盖了ProcessCmdKey()以捕获按键。如果按下的键存在于我们的查找中,那么我们用.PerformClick():点击它

public partial class Form1 : Form
{
private Dictionary<Keys, Button> btnLookups = new Dictionary<Keys, Button>();
public Form1()
{
InitializeComponent();
// make your key -> button assignments in here
btnLookups.Add(Keys.F1, button1); 
btnLookups.Add(Keys.F2, button2);
btnLookups.Add(Keys.F3, button3);
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
Button btn;
if (btnLookups.TryGetValue(keyData, out btn))
{
btn.PerformClick();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("button1");
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("button2");
}
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("button3");
}
}

您需要一个事件处理程序来绑定您的方法"AnyNumberClick";。这是在表单的Designer.cs部分中完成的。创建一个字符数组char[],并在按钮按下事件方法中创建一个函数,然后将按下的按钮与数组中的字符集进行比较。

private void txt_box_keypress(object sender, KeyPressEventArgs e)
{
char[] SomeArray = {'a','b','c', etc};
int LengthOfArray = SomeArray.Length;
for (int x = 0; x < LengthOfArray; x++)
{
if (txt_box.Text.Contains(SomeArray[x]))
{
'Your method event here'
}
}
}

最新更新