c# 重建是我程序的 运行ning 部分(加载用户控件),单击播放会导致重建 运行 两次

c# rebuilding is running part of my program(loading a user control), and clicking play can cause a rebuild and run it twice

我的程序有问题,我已设法将其缩小为一些示例代码。

添加注释- http://ge.tt/7paP1Gj2 <--- a link 到我的代码 70KB zip 文件。

c# 重建是我程序的 运行ning 部分(加载用户控件),单击播放会导致重建 运行 两次。有时双击窗体也可以将其关闭。我会详细说明我的意思。

我的程序是按以下方式创建的。

我右键单击该项目,然后单击添加...用户控件

所以我有了表单和用户控件。

我在表单加载中有以下代码,在用户控件中有以下代码

    private void Form1_Load(object sender, EventArgs e)
    {
        // any time i change this e.g. change the string e.g. change "loaded" to "loaddddd" and click Form1 in solution explorer. then the "uc loaded" messagebox comes up
        MessageBox.Show("form loadeddd");

    }

以及用户控件中的以下内容

    private void UserControl1_Load(object sender, EventArgs e)
    {
        MessageBox.Show("uc loaded");

        // any time i change this string then rebuild,  then the "uc loaded" message box comes up.
        string a="abc";

    }

现在我点击播放。 "uc loaded"出现两次,"form loaded"出现一次。

如果我再次点击播放,(不更改任何代码),然后 "uc loaded" 出现一次,"form loaded" 出现一次。

如果我在解决方案资源管理器中双击 Form1,则不会出现 st运行ge 行为。表格刚刚出现。没有消息框被触发。

现在假设我更改了 "form loaded" 消息框字符串,例如"form loaded" 到 "form loadedd" 然后我在解决方案资源管理器中双击 Form1,出现一个消息框,上面写着 "uc loaded"。对我来说,这似乎是 st运行ge。如果我再次单击 Form1,则 "uc loaded" 不会出现。如果我再次更改字符串并双击 Form1,则会出现 "uc loaded" 消息框。如果我再次单击 Form1,则它不会出现。

现在假设我单击“播放”。然后我得到 "uc loaded" 出现两次。好像它可能首先进行了重建(这对 运行 用户控件加载方法来说似乎很烦人),(好像它 运行 那样)然后 运行 程序。如果我再次单击“播放”,则 "uc loaded" 只会出现一次。如果我更改 "form loaded" 字符串,然后单击播放,然后 "uc loaded" 会出现两次。再次点击播放,出现一次。

如果我更改 "form loaded" 字符串或 "uc loaded" 字符串或其他字符串,则 "uc loaded" 在我单击播放时会出现两次。

添加了注释我的代码开始时有更多内容,我复制了文件夹并将其删除并复制了文件夹并删除了它,然后再将其变小因为它仍然产生行为。但是如果这种行为不是那么容易重现.. 我在我的缩减示例代码中包含了一个 link ,当我尝试它时它会非常整齐地显示错误。

这是由于您直接将 UserControl 放在表单上造成的。

这个问题有 2 个解决方案:

在运行上添加控件:
您可以将面板用作用户控件的 "placeholder",您可以在 运行 时添加它,如下所示:

NameOfUserControl userControl = new NameOfUserControl();
nameOfPanel.Controls.Add(userControl);  

检查设计模式:
在您的用户控件的加载功能中,您可以检查它是否处于设计模式或 运行ning。

if(Application.ExecutablePath.IndexOf("devenv.exe", StringComparison.OrdinalIgnoreCase) == -1) 
{ 
    //Not in designer mode use > to check for designer mode
    MessageBox.Show("uc loaded"); 
}