日期:2014-05-19  浏览次数:20815 次

.net关于两个窗体调用的问题,有点难!
现在有两个同级的Form1,Form2(不是子窗体)Form1中有一个button,Form2中有一个Edit,现在两个窗体都已经显示了,两个窗体间没有直接的联系,我现在想在Form1中按下button,Form2成为活动窗体,并且Edit具有焦点,这个该怎么办呢,
粗略估计可能要用SendMessage什么的,但是不太清楚有没有什么好方法!

------解决方案--------------------
定义一个中间类。假如一个变量a。和2个form对象
当a变化时。调用form对象的函数实现你的功能
------解决方案--------------------
Form1的Button_Click
Form2.Activate();
Form2的事件
private void Form2_Activated(object sender, EventArgs e)
{
this.Edit.Focus();
}
------解决方案--------------------
同意楼上的,SendMessage是进程间通信,你两个窗口都是一个application的
------解决方案--------------------
定义一个中间的方法不就可以了,有那么麻烦吗
------解决方案--------------------
用委托和事件!用在两个窗体间的信息传递,这是一个不错的选择!我经常这样做!
------解决方案--------------------
楼主可参考如下代码:
例:Form1 中调用 Form2:
[Form1]中代码:
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
public delegate void sendMessage();
public static event sendMessage sendMessageEvent;//注意此处一定为static 静态,否则Form2中无法订阅

/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;

public Form1()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();


}

/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(80, 48);
this.button1.Name = "button1 ";
this.button1.TabIndex = 0;
this.button1.Text = "button1 ";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(292, 268);
this.Controls.Add(this.button1);
this.Name = "Form1 ";
this.Text = "Form1 ";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void button1_Click(object sender, System.EventArgs e)
{
if(sendMessageEvent != null) sendMessageEvent();
}

private void Form1_Load(object sender, System.EventArgs e)
{
Form2 fm2 = new Form2();
fm2.Show();
}
}
[Form2]中代码:
public class Form2 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox textBox1;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;