Control c = this.Parent; //定义c为自定义控件的Parent while(!c is Form) //如果c不是窗体,则继续获取控件c的Parent(你的自定义控件有可能 c = c.Parent; //在Panel中),故通过此While语句,最终得到你的自定义控件所在的窗体 MessageBox.Show("OK " + c.Name); //获取c.Name也就是自定义控件所在的窗体的窗体名称
button 的属性里 Modifiers 改成 Public 相互指向 比较简单
Control c = this.Parent; while(!c is Form) c = c.Parent; if(c.name==A) console.Writeline("{0}",1+1); if(c.name==B) console.Writeline("{0}",2+2);
Control c = this.Parent;
while(!c is Form)
c = c.Parent;
MessageBox.Show("OK " + c.Name);
{
MessageBox.Show("Ok " + this.FindForm().Name);
}
MessageBox要在点击自定义控件中按钮时才show出来,show出来的字符不一定是"OK..",我的意思是在点击自定义控件中按钮时处理相应的事情,但在另一个窗体中点击又会处理别的事情
这个代码应放在哪里呢? 我这里是Message,要是改为其它的逻辑程序呢?
比如在A窗体中执行1+1
在B窗体中分行2+2
Control c = this.Parent; //定义c为自定义控件的Parent
while(!c is Form) //如果c不是窗体,则继续获取控件c的Parent(你的自定义控件有可能
c = c.Parent; //在Panel中),故通过此While语句,最终得到你的自定义控件所在的窗体
MessageBox.Show("OK " + c.Name); //获取c.Name也就是自定义控件所在的窗体的窗体名称
while(!c is Form)
c = c.Parent;
if(c.name==A) console.Writeline("{0}",1+1);
if(c.name==B) console.Writeline("{0}",2+2);
比如在A窗体中点击时,执行1+1
在B窗体中点击时,执行2+2
如果还有C窗体,点击时,执行 100-29
......
鼠标的双击 ,单击,Down,Up
键盘的KeyPress 都是事件
你把你点击的逻辑写在事件里面就是了
写好了就可以触发这个事件了
{
public UButton()
{
InitializeComponent();
}
public event DoSomethingDelegate DoSomethingEvent; private void button1_Click(object sender, EventArgs e)
{
if (DoSomethingEvent != null)
{
DoSomethingEvent();
}
}
}调用窗体Form1,注册控件事件。public Form1()
{
InitializeComponent();
this.uButton1.DoSomethingEvent += new DoSomethingDelegate(this.Form1_DoSomething);
}private void Form1_DoSomething()
{
MessageBox.Show("Form1 do something");
}
简单的事件就是private void button1_Click(object sender, EventArgs e)
{
//逻辑部分
}
在逻辑部分里面,想写啥就写啥!
当你鼠标双击这个Button1 的时候,就触发了这个Click 事件
他里面的逻辑部分 就会执行!