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?

4
  • 4
    My brain is suffering recursion as a result of this question Commented Feb 9, 2010 at 21:43
  • 3
    It is not clear what you want. Try to give a specific example of how you see this working. Commented Feb 9, 2010 at 21:46
  • he wants to take a runtime type and have it punch out Form form1 = new Form(); form1.Width = 800; form1.Height = 600; Commented Feb 9, 2010 at 21:51
  • 1
    Terrible wording, but the question is clear to me. Commented Feb 9, 2010 at 21:58

3 Answers 3

7

This MSDN magazine article should have everything you need.

Sign up to request clarification or add additional context in comments.

1 Comment

perfect "don't reinvent the wheel" answer ;)
0

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.

Comments

0

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

4 Comments

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.
I guess you do have a reason to re-invent the wheel.
Also, you can think of serializing a graph of UI controls into a custom format and re-creating it during runtime.
Doesn't the Emit class generate IL? I need actual C# code that I can add to a solution and compile.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.