vb.net用代码向另一个窗体添加命令按钮

2024-11-22 07:46:41
推荐回答(2个)
回答(1):

先得到目标窗体的 handle (句柄) 或整个对象, 然后实例化一个button 并加入到窗体对象中. 如: 在 form2 点击 add 按钮后, form1 会新添加一个按钮,单击显示hello , 下面是两个窗口类. public class form1 inherits system.windows.forms.form '这是一个什么都没有的空窗体 public sub new() me.size=new size(200,200) end subend class public class form2 inherits system.windows.forms.form private button1 as button '添加按钮 private frm as form public sub new() me.size=new size(200,200) button1= new button() '实例化 button1.text="add" '名字就叫 add button1.location=new point(50,50) addhandle button1.click, addressof add_click me.controls.add(button1) end sub '用于记录form1对象的属性 public property form1() as form get return frm end get set (byval value as form) frm = value end set end property '添加按钮 private sub add_click(byval o as object, byval e as eventargs) '当form1属性被指定,向form1 添加按钮 if frm isnot nothing then dim btn as button = new button() btn.text ="new button" btn.location=new point(50,50) addhandle btn.click, addressof button_click frm.controls.add (btn) else msgbox ("未指定form1") end if end sub '新按钮的单击事件 private sub button_click(byval o as object, byval e as eventargs) msgbox("hello!") end subend class 两个窗体类完成了,然后在模块写如下代码,程序设置为从模块启动:public module module1 public sub main() dim frm1= new form1() dim frm2 = new form2() frm2.form1=frm1 frm2.show() frm1.show() application.run(frm2) end subend module

回答(2):

问题表述的不明确,说具体点 命令按钮?