Tuesday, September 15, 2009

How to know if your code is run by the visual studio designer?

While developing a windows application in .net (using c# or VB) we generally use the design view to add and position controls, thanks to the great interface provided by Microsoft.

But many a times while working with custom controls or user controls, you may want the designer to behave in a different way in the design view than while running the application.

For example, say that you have created a custom control extending System.Windows.Forms.Button control to MyButton and specifying that all the buttons created using this class must have same background and same image.

Now say that you a created a from with 100 buttons created using the MyButton class. The design view would take a lot of time to load the 100 buttons and their corresponding images.

As you have created buttons from the MyButton class, you already know the image that would be set and the background color. So you always need not have both the image and the background color set while designing the form, this can be done in the runtime , so that your designer would load quickly.

The .NET framework provides a way to do this. The System.Windows.Forms.Control has a property "DesignMode", this property tells us if the control is in design mode or is in runtime.

But this property may not always be accurate. While using custom controls, this property may not behave as expected.

So how do we actually know if the code is running in Visual Studio or is in runtime?

I stumped over an idea that the base process for the design to be displayed should be visual studio, so a conditional statement can be used to check if the current process is visual studio. This can be done by using the System.Diagnostics.Process.GetCurrentProcess.ProcessName, this property gives the name of the current running process. This can be checked with the visual studio process name ( which is devenv).

So we can check if the code is being run by visual studio designer or by the application by using the following code:

VB:

if System.Diagnostics.Process.GetCurrentProcess.ProcessName <> "devenv" then
' code if not run in visual studio
else
' code when run in visual studio.
end if

c#
if(System.Diagnostics.Process.GetCurrentProcess.ProcessName != "devenv")
{
// code if not run in visual studio
}
else
{
// code if run in visual studio.
}



Hope this helps.

No comments:

Post a Comment