C# -如何从winforms应用程序中的另一个类引用Form 1的当前示例?

cvxl0en2  于 2022-11-25  发布在  C#
关注(0)|答案(2)|浏览(134)

如果这没有意义,我很抱歉!这是一个新的WinForms,这是一个uni评估。我的主窗体如下所示,其中有我想在另一个类中调用的方法。我已经将Form 1重命名为LoginPage。

public partial class LoginPage : Form
    {
        public LoginPage()
        {
            InitializeComponent();
            Customer.LoadCustomerDB();
        }

        public string PinText
        {
            get { return PINNumTxt.Text; }
            set { PINNumTxt.Text = value; }
        }
    }

我的另一个类将验证我使用上面的函数访问的PinText。

class BankCard
    {
        // Attributes
        private Customer customer;
        private int pinAttempts = 0;
        private bool cardUnusable = false;

        // Member functions
        public void VerifyPIN()
        {
            LoginPage loginPage = new LoginPage();
            foreach (Customer c in Customer.customers)
            {
                if (c.GetID().ToString() == loginPage.AccountNum())
                {
                    customer = c;
                }
            }

            if (cardUnusable == true)
            {
                MessageBox.Show("This card is currently blocked. Please contact your bank.");
                Environment.Exit(0);
            }
            else if (loginPage.PinText == customer.GetPIN())
            {
                MessageBox.Show("Success!");
            }
            else if (pinAttempts < 2)
            {
                MessageBox.Show("Incorrect PIN attempt " + (pinAttempts + 1) + "/3");
                loginPage.PinText = "";
                pinAttempts += 1;
            }
            else
            {
                MessageBox.Show("3 failed PIN attempts. Please contact your bank.");
                cardUnusable = true;
                Environment.Exit(0);
            }
        }
    }

我的问题是,我有以下:

LoginPage loginPage = new LoginPage();

这将创建一个新的主页示例,使加载的CustomerDB加倍,并导致VerifyPin()函数出错。
问题是我需要以某种方式让LoginPage loginPage = LoginPage的当前示例吗?如果是这样,我该如何编写代码呢?
谢谢你的帮助

i2byvkas

i2byvkas1#

Wyck的评论让它运行起来没有任何错误。我必须做的是:

LoginPage loginPage = Application.OpenForms.OfType<LoginPage>().FirstOrDefault();

谢谢大家

6kkfgxo0

6kkfgxo02#

在大多数winforms项目中,都有一个Program类,其中包含Application.Run(new Form1());(或者主窗体的名称,在本例中为LoginPage)。在Program类中,您可以创建一个静态变量public static LoginPage loginPage;,然后在Main函数中:

static void Main()
{
    loginPage = new LoginPage();
    Application.Run(loginPage);
}

那么当你想在你的任何类中引用loginPage时,你可以使用Program.loginPage

相关问题