views:

105

answers:

3

I want to create a .NET Form at runtime, add buttons and other controls to that (also at runtime), and then be able to generate a something.designer.cs file from that form (which can then be added to a C# solution and compiled).

What I want to do is very similar to what the WinForm designer does. But instead of having a drag/drop interface for the user, I want to dynamically build the Form/Controls myself at runtime.

I was thinking I could just reuse what the WinForm designer is doing.

Is that possible?

A: 

It's really not as simple as it was pre-.NET as the visual version of the form you see in Visual Studio is actually the result of multiple files.

But in the simplest form you could simply just mirror what .NET does at the start of creating a new form:

  1. Create three files Form.cs, Form.Designer.cs and Form.resx (which is an XML file).
  2. Place the same default content in them that VS does
  3. Mimic the code generated when adding controls, code-behind and resources

It will be a tedious task, but it can be done. Adding resources however will be burdensome.

Nissan Fan
+6  A: 

This MSDN magazine article should have everything you need.

Hans Passant
perfect "don't reinvent the wheel" answer ;)
Thomas Levesque
A: 

Yes, you can do achieve this using Compiler Services (compiling c# code) or Emit class if you know building correct MSIL.

modosansreves
This is the direct answer. But I feel like the question you ask is about an obstacle on your way to solving a different problem I do not know.
modosansreves
I guess you do have a reason to re-invent the wheel.
modosansreves
Also, you can think of serializing a graph of UI controls into a custom format and re-creating it during runtime.
modosansreves
Doesn't the Emit class generate IL? I need actual C# code that I can add to a solution and compile.
NotDan