views:

1008

answers:

3

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...

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

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 WinForm constructor doesn't actually create the file at design time...

Can someone either help? Explanation? Reference?

Thanks.

A: 

There are some things you shouldn't do with the designer. I don't have any hard evidence, but I found that the Winforms designer hates it when you take away the default constructor from him. Just go ahead and create new overloads, but leave the empty constructor in place.

Also try to avoid doing Form_Load events in Base classes you inherit from.

Tigraine
+3  A: 

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

Here is a quick example:

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.

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!");
            }
        }
    }
}

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

I hope this helps.

-jeremy

+1  A: 

You could also use this to check if VS Designer is running the code:

public static bool DesignMode
{
    get {  return (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv"); }
}

Then in Form_Load:

if (!DesignMode)
{
    // Run code that breaks in VS Designer (like trying to get a DB connection)
}

However, this is less elegant than using the LicensManager.UsageMode but it works. (until MSFT changes the name of the proc VS runs under :)

tzup
Man, your "less elegant" method is the only one that works.The LicensManager.UsageMode doesn't work e.g. when the designer is invoking a 'property get' method of a user control.
Soonts