.NET Windows窗体设计时间规则 [英] .NET Windows Forms design time rules

查看:109
本文介绍了.NET Windows窗体设计时间规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个启动线程,打开文件并等待其他类输入的对象。接收到输入后,它将其写入磁盘。基本上,这是线程安全的数据记录类...

I have an object that starts a thread, opens a file, and waits for input from other classes. As it receives input, it writes it to disk. Basically, it's a thread safe data logging class...

这是一个很奇怪的部分。当我在设计器(Visual Studio 2008)中打开使用该对象的表单时,便会创建文件。显然,它是在设计时虚拟主机流程下运行的。

Here's the weird part. When I open a form in the designer (Visual Studio 2008) that uses the object the file gets created. It's obviously running under the design time vhost process...

奇怪的是,我无法在另一个项目中重现该问题。我不确定在设计器中执行的代码和未在设计器中执行的代码的规则是什么。例如,在Windows Forms构造函数中创建文件实际上并没有在设计时创建文件...

The odd thing is I've not been able to reproduce the issue in another project. I'm not sure what the rules are for code that gets executed in the designer and code that does not. For example, creating a file in a Windows Forms constructor doesn't actually create the file at design time...

解释是什么?有参考吗?

What is the explanation? Is there a reference?

推荐答案

您可以检查LicenseManager的UsageMode,以检查代码是否在设计时。

You can check the UsageMode of the LicenseManager, to check if the code is in design time or not.

System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime

System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime

这是一个快速示例:

using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace Test
{
    public class ComponentClass : Component
    {
        public ComponentClass()
        {
            MessageBox.Show("Runtime!");
        }
    }
}

此组件何时添加到您在设计器中的表单,您将立即得到一个消息框。

When this component gets add to your form in the designer, you will immediatly get a message box.

为防止这种情况,您可以添加一个简单的if语句来检查代码是否不在设计时

To prevent this you can add a simple if statement to check if the code is not in design time

using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace Test
{
    public class ComponentClass : Component
    {
        public ComponentClass()
        {
            if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
            {
                MessageBox.Show("Runtime!");
            }
        }
    }
}

之后添加if语句后,通过设计器将组件添加到表单时,消息框将不再出现。

After adding the if statement, the messagebox no longer appears when the component is added to the form via the designer.

我希望这会有所帮助。

-杰里米

这篇关于.NET Windows窗体设计时间规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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