好的,我希望这样做,因为单击按钮的数量有限,因为多个框打开导致我的应用程序崩溃〜:(
这是我的表格代码,我希望阻止它开放给很多人不要误会我想要多个盒子并不多:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
this.KeyPreview = true;
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
}
private void pictureBox1_Click(object sender, EventArgs e)
{
var myForm = new Form2();
myForm.Show();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt && e.KeyCode == Keys.A)
{
Form3 f3 = new Form3();
f3.ShowDialog();
}
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
}
答案 0 :(得分:3)
使用私人柜台。每次用户单击按钮时,递增计数器,并在显示新表单之前检查计数器。
private int clickCounter = 0;
private void pictureBox1_Click(object sender, EventArgs e)
{
this.clickCounter++;
if (this.clickCounter < 10) // arbitrary number
{
var myForm = new Form2();
myForm.Show();
}
}
这将有助于确保用户不会滥用表单的单个实例上的按钮。要确保相同的计数器适用于表单的所有实例,请将其设置为静态:
private static int clickCounter = 0;
private void pictureBox1_Click(object sender, EventArgs e)
{
clickCounter++;
if (clickCounter < 10) // arbitrary number
{
var myForm = new Form2();
myForm.Show();
}
}
如果您希望在表单因 Junior Programmer 建议而关闭时减少计数器,则可以绑定到Closing
事件。这将有效地限制可以打开的新表单的数量(而不仅仅是限制按钮可以被点击的次数)。这适用于本地和静态计数器版本:
myForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
clickCounter--;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if (clickCounter < 10) // arbitrary number
{
clickCounter++;
var myForm = new Form2();
myForm.Closing += myForm_Closing;
myForm.Show();
}
}
答案 1 :(得分:0)
这是另一种解决方案,它与p.s.w.g
的答案没有多大区别;
public class Form1 : Form {
private static int count = 0;
public Form1(){
InitializeComponent();
button1.Click += click;
}
private void click(object sender, EventArgs e){
count++;
if(count > 20) {
button1.Click -= click;
count = 0;//If you want to reset
}
}
}
答案 2 :(得分:0)
只需创建一个全局静态int计数变量并将其设置为0.每次单击该按钮时,增加count(count ++)的值。
因此,当单击该按钮时,将所有事件处理放在下面的语句if而不是我的注释
中if(count<5)
{
count++;
//run your code for the button event
}
else
{
MessageBox.Show("You have pressed the button too many times");
}
所以使用上面的代码,你的决赛应该是这样的
public partial class Form2 : Form
{
public static int count=0;
public Form2()
{
InitializeComponent();
this.KeyPreview = true;
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if(count<5)
{
count++;
var myForm = new Form2();
myForm.Show();
}
else
{
MessageBox.Show("You have pressed the button too many times");
}
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt && e.KeyCode == Keys.A)
{
Form3 f3 = new Form3();
f3.ShowDialog();
}
}
private void Form2_Load(object sender, EventArgs e)
{
}
}