C#如何调用父窗体的按钮
有一个父窗体Form1,有一个子窗体Form2。在父窗体中有2个按钮botton1和botton2,想法是:在子窗体中用swicth语句来判断父窗体按下了哪个按钮,来控制父窗体按下某个按钮后,子窗体运行相应的程序。。如何实现,高手帮忙,在线等!!!,最好有代码,小弟好学习,谢谢了
有一个父窗体Form1,有一个子窗体Form2。在父窗体中有2个按钮botton1和botton2,想法是:在子窗体中用swicth语句来判断父窗体按下了哪个按钮,来控制父窗体按下某个按钮后,子窗体运行相应的程序。。如何实现,高手帮忙,在线等!!!,最好有代码,小弟好学习,谢谢了
答案:父窗体:public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Form2 from2 = new Form2();//初始化子窗口
private static string _str;//声明一个静态变量
public static string str//声明一个静态属性
{
get { return _str; }
set { _str = value; }
}
private void Form1_Load(object sender, EventArgs e)
{
from2.Show();//我这里是在窗体加载的时候,就把子窗体显示出来,具体的按你的需求定
}private void button1_Click(object sender, EventArgs e)
{
_str = "a";//点第一个按钮的时候给他附一个值
}private void button2_Click(object sender, EventArgs e)
{
_str = "b";//点第而个按钮的时候给他附另外一个个值
}
}
子窗体:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{}
private void button1_Click(object sender, EventArgs e)
{
switch (Form1.str)//这个就是你要的用 switch来判断了,具体要做什么,你自己改
{
case "a": label1.Text = "a"; break;
case "b": label1.Text = "b"; break;}
添加一个静态类,如:
}
}
public static class GlobalVariable
{
public static bool Button1 = false;
public static bool button2 = false;
}
Form1的button_Click事件:
//button1被按下
private void button1_Click(object sender, EventArgs e)
{
GlobalVariable.Button1 = true;
}
//button2被按下
private void button2_Click(object sender, EventArgs e)
{
GlobalVariable.Button2 = true;
}
Form2里就可以:
if (GlobalVariable.Button1 == true)
{
//添加你自己的代码
}可以写个方法(在父窗体里面),方法就是用switch判断一个参数,比如整型参数,然后运行相应的程序。。
然后在父窗体里的两个按钮点击事件里调用这个方法,只是传递的参数不一样。。
button1:
this.Exe(1);
button2:
this.Exe(2);
方法:
Exe(int x){
switch(x){
case 1:
//运行相应程序
break;
case 2:
//运行相应程序
break;
}
}
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 Form1 : Form
{
public Form1()
{
InitializeComponent();
f2 = new Form2();
f2.Show();
f2.button1.Click += new EventHandler(b_Click);
}private void button2_Click(object sender, EventArgs e)
{
OD = od.老子;
}
private enum od
{
老子,
儿子
}
private Form2 f2;
private od OD;
private void b_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
switch (OD)
{
case od.老子:
MessageBox.Show("老子");
break;
case od.儿子:
MessageBox.Show("儿子");
break;
}
&nbs
上一个:C#编程的2个小问题
下一个:请问哪里有c#下载啊