views:

33

answers:

1

I want to create a custom control in C# which I will use multiple times in my application, but will not likely use in any other applications. I have seen several websites which explain how to create a custom control and add it to the Visual Studio toolbox. They instruct you to create a project with the custom control which compiles to a DLL, then create a new project for the application and add a reference to that DLL in the toolbox. However, I'd rather have my application be a single executable that is not dependent on a DLL. Is there a way to put the custom control and the application in one project and still have the custom control appear in the Visual Studio toolbox? Or, if it's not possible to add the control to the toolbox, is there another way to view the control in the application's designer?

+2  A: 

The technique is in:

  1. To develop your project you may use your component as usual (means adding it as DLL into toolbox and reference to it in your project).

  2. To use your dll internally in one exe file you should add it (either raw or deflated) to resources of your project.

  3. In Main method subscribe to AppDomain.AssemblyResolve event:

    public static void Main( string[] args )
    {            
        AppDomain.CurrentDomain.AssemblyResolve += AppDomain_AssemblyResolve;    
    }
    
  4. In event handler you should resolve an assembly with your component:

    private static Assembly AppDomain_AssemblyResolve( object sender, ResolveEventArgs args )
        {
            if( args.Name.Contains( "YourComponent" ) )
            {           
                using( var resource = new MemoryStream( Resources.YourComponent ) )
                    return Assembly.Load( resource.GetBuffer() );
            }
    
    
    
        return null;
    }
    

Then your App will use this assembly extracted from your exe, but you still be able to use component from toolbox while developing.

Notice that you should update it in resources every time your component will be changed.

Eugene Cheverda