【问题标题】:Using same form for different scenario in windows form在 windows 窗体中对不同场景使用相同的窗体
【发布时间】:2011-11-10 14:12:06
【问题描述】:

我有一个 VS 解决方案,其中有多个项目。例如,其中一个标题为“管理”,另一个标题为“运行时”

如果我将 Management 设置为默认项目并运行它,则会打开一个名为 Scout 的应用程序。如果我将 Runtime 设置为默认项目并运行它,则会打开一个名为 PM 的应用程序。 需要使用登录表单,我的要求是,两个项目必须使用相同的登录表单,并且我必须在一个名为 Data 的新项目下创建登录表单,它可供其他项目(运行时和管理)使用)

我的疑问是,在运行程序时,我需要找出默认运行的是哪个项目,然后使用一些动态更新的控件加载登录表单(例如,如果先执行 Runtime proj,则登录表单应该有标签“Welcome to Runtime”),如果首先执行 Management proj,登录表单应该有一个标签“Welcome to Management”

我如何做到这一点?

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    我认为重用Form 是可能的。 首先,像这样创建您的登录表单。 (也许您应该在 DLL 中创建它,以便在不同的项目中重用它。)

        public partial class LoginForm : Form
    {
        //This constructor should only be called by the Designer.
        public LoginForm()
        {
            InitializeComponent();
        }
    
        public LoginForm(string title) : this()
        {
            TitleLabel.Text = title;
        }
        public Tuple<string, string> Login()
        {
            if (this.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                return new Tuple<string, string>(Username.Text, Password.Text);
            }
            else
            {
                return default(Tuple<string, string>);
            }
        }
    
        private void OKButton_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }
    
        private void CancelButton_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }
    }
    

    然后在不同的场景中使用它:

    var details = new LoginForm("Title here").Login();
    if (details.Item1 == "username" && details.Item2 == "Password")
    {
        //logged in.
    }
    

    【讨论】:

    • +1 在问题中,他应该创建一个包含此表单的新项目(显然称为Data)。然后 RunTime 和 Management 项目都可以显示表单并设置标签/标题。
    • @Shyc 如何找出正在运行的项目以显示相应的登录表单?
    • @HarishKumar 您不应该尝试检测在登录表单中运行的项目。只需在构造函数调用中将所需信息作为参数传递即可。
    • @HarishKumar 通过在不同项目的Program.cs 文件中编写不同的代码,您可以将不同的信息传递给LoginForm
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-04
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 2014-07-02
    • 2010-10-18
    • 1970-01-01
    相关资源
    最近更新 更多