4

I have the following problem:

I made a user control library (DLL), which just has an enabled Timer. When I try to use this control in an application, as soon as I drag it to the Form in design mode, it starts to count! Even if the application is not running.... How can I avoid that?

My objective is that the Timer starts counting as soon as the application is launched, but not in Design Mode... because the Timer uses some external functions that cause the crash in the Design Mode.

Thank you in advanced!

Dario

1
  • Try to remove your created user control and create a new one again
    – jhyap
    Nov 19, 2013 at 9:29

6 Answers 6

3

You can check the DesignMode property of Control:

if (!this.DesignMode) {
    // its not in design mode.. so do stuff.
}

Or perhaps neater:

yourTimer.Enabled = !this.DesignMode;
0
2
Timer_Tick(object sender, EventArgs e)
{
    if(this.DesignMode)
       return;
    //Rest of your code here
}
1

Check if Timer is not started in control's constructor - that is the most possible reason of such behavior.

1

Besides adding new user control from the form, you can also create your user control by coding at Form1.Designer.cs

using System.Windows.Forms;

public class MyTimer : Timer
{
    public MyTimer()
    {
        // Set your custom timer properties here.
        this.Enabled = false;
    }
}
1

Probably you Start your Timer outside the GUI Thread and now it's ticking. I suggest this happens in the constructor of your Control. Change this to a separate method or post some Code to make a clear view of your Problem.

2
0

Like many people have said, you can check if the control is in design mode.

The problem you might face is that the Control.DesignMode property doesn't work properly for nested controls; it always returns false.

Here is a fixed version that you can use instead:

public static bool IsDesignMode(Control control)
{
    if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)  // Initial quick check.
    {
        return true;
    }

    while (control != null)
    {
        System.ComponentModel.ISite site = control.Site;

        if ((site != null) && (site.DesignMode))
            return true;

        control = control.Parent;
    }

    return false;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.