我正在开发一个Windows窗体C#应用程序,我需要启用一个button4按钮,当且仅当单击所有三个按钮(button1,button2,button3)时。我正在努力实现这一点。帮我解决一些想法和样本。提前致谢。
答案 0 :(得分:0)
点击3个按钮是不可能的,因为你不能同时用鼠标按这三个按钮。
如果您的意思是他们已被点击,请查看以下代码。
int index = 0;
button1.Click(object sender, eventargs e)
{
index = index + 1;
button1.enabled = false;
}
button2.Click(object sender, eventargs e)
{
index = index + 1;
button2.enabled = false;
}
button3.Click(object sender, eventarfs e)
{
index = index + 1;
button3.enabled = false;
}
//And now the button to see if all buttons have been clicked:
button4.Click(object sender, eventargs e)
{
if (index == 3)
{
Messagebox.Show("All buttons have been clicked.")
}
else
{
Messagebox.Show("Not all buttons have been clicked")
}
}
答案 1 :(得分:0)
我认为你要找的是一个CheckBox。您可以使用以下代码使CheckBox看起来像按钮:
var checkBox1 = new System.Windows.Forms.CheckBox();
var checkBox2 = new System.Windows.Forms.CheckBox();
var checkBox3 = new System.Windows.Forms.CheckBox();
var checkBox4 = new System.Windows.Forms.CheckBox();
checkBox1.Appearance = System.Windows.Forms.Appearance.Button;
checkBox2.Appearance = System.Windows.Forms.Appearance.Button;
checkBox3.Appearance = System.Windows.Forms.Appearance.Button;
checkBox4.Appearance = System.Windows.Forms.Appearance.Button;
然后做你想做的事情:
if (checkBox1.Checked && checkBox2.Checked && checkBox3.Checked)
checkBox4.Enabled = true;
else
checkBox4.Enabled = false;
或者你可以一行:
checkBox4.Enabled = checkBox1.Checked && checkBox2.Checked && checkBox3.Checked;
答案 2 :(得分:0)
Dictionary<string, bool> buttonClicked = new Dictionary<string, bool>();
private void button123_Clicked(object sender, EventArgs e)
{
string buttonName = (sender as Button).Name;
if (!buttonClicked.ContainsKey(buttonName))
{
buttonClicked.Add(buttonName, true);
}
if (buttonClicked.Count == 3) button4.Enabled = true;
}
将其添加为前3个按钮的OnClick
事件,它应该可以解决问题。
答案 3 :(得分:0)
将此列表添加到您的班级&#39;根:
List<Button> pressedButtons = new List<Button>();
然后将此方法添加到您的1,2和3按钮&#39; &#34;点击&#34; -event(对所有3使用相同的方法):
private void button_Click(object sender, EventArgs e)
{
// Add the clicked button to the list
pressedButtons.Add((Button)sender);
// If all 3 are on the list, enable button4
if (pressedButtons.Count == 3) { button4.Enabled = true; }
}
您应该查看&#34; CheckBox &#34; -element,因为它可以与Button-appeareance一起使用(通过设置&#34; Appeareance &#34; -property。这样你就可以拥有一个具有切换开关功能的按钮。
答案 4 :(得分:0)
您可以将按钮放在List或数组中,并使用Button的Tag属性。所有3个按钮都有一个click事件处理程序代码:
//Create a list
List<Button> buttons = new List<Button>(){button1,button2,button3};
单击3个按钮的事件处理程序
private void buttons_Click(object sender, EventArgs e)
{
//Update Tag value
if (((Button)sender).Tag == null || (bool)((Button)sender).Tag == false)
((Button)sender).Tag = true;
//Check state of all buttons
foreach (Button btn in buttons)
{
//One of the buttons wasn't clicked
if ((bool)btn.Tag == false)if (((Button)sender).Tag == null || (bool)((Button)sender).Tag == false)
return;
}
//All buttons were clicked
button4.Enabled = true;
}