我想从Form2的Form1的控制 [英] I would like to control Form1 from Form2

查看:111
本文介绍了我想从Form2的Form1的控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想基本上用户在第一登录才能使用的其他形式。不过,我的困境是,登录框在窗体2,主要形式是Form1上。

So I want basically the user to login in first in order to use the other form. However, my dilemma is that the login box is in Form2, and the main form is Form1.

if ((struseremail.Equals(username)) && (strpasswd.Equals(password)))
{
  MessageBox.Show("Logged in");
  form1.Visible = true;
  form1.WindowState = FormWindowState.Maximized;
}
else
{
  MessageBox.Show("Wow, how did you screw this one up?");
}



不过,Form1中不可见,(因为我启动它作为visble = FALSE),他们在登录后有人能帮助

However, Form1 doesn't become visible, (since I launch it as visble = false) after they log in. Can someone help?

编辑:

辉煌的反应,但我的问题还在这里。我基本上要加载的Form2首先,(这是很容易我运行Form1上,并设置为隐藏),但是,当窗体2被关闭,我想Form1中被同时关闭。

Brilliant response, but my problem is still here. I basically want to load Form2 First, (which is easy I run Form1 and set it to hide) But when Form2 is closed, I want Form1 to be closed as well.

private void Form2_FormClosing(Object sender, FormClosingEventArgs e)
{
  Form1 form1 = new Form1();
  form1.Close();
  MessageBox.Show("Closing");
}

这似乎并没有工作...

this doesn't seem to work...

推荐答案

您需要一种形式的引用传递到另一个,以便它可以在其他形式使用。在这里,我给出如何两种不同形式可以相互通信的例子。本示例修改标签的一种形式,从另一种形式的文本。

You will need to pass the reference of one form to another, so that it can be used in the other form. Here I've given an example of how two different forms can communicate with each other. This example modifies the text of a Label in one form from another form.

为示例项目

Download Link for Sample Project

// 您的Form1中

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm = new Form2(this);
        frm.Show();
    }

    public string LabelText
    {
        get { return Lbl.Text; }
        set { Lbl.Text = value; }
    }
}



// 您的窗体2

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private Form1 mainForm = null;
    public Form2(Form callingForm)
    {
        mainForm = callingForm as Form1; 
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.mainForm.LabelText = txtMessage.Text;
    }

    //Added later, closing Form1 when Form2 is closed.
    private void Form2_FormClosed(object sender, FormClosedEventArgs e)
    {
        mainForm.Close();
    }
}



这篇关于我想从Form2的Form1的控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆