Wednesday, May 21, 2008

Smat tags in runtime Windows.Forms

A very interesting topic aboutSmart tags in runtime on Windows.Forms. I just made a copy:

You have to create a DesignerOptions with UseSmartTags property set to true, add the DesignerOptions to DesignerOptionService, after which add this service to the DesignerSurface, I write the following sample which host a TextBox and a DataGridView control on the designer surface.

Code Snippet

namespace Sample25

{

public partial class Form2 : Form

{

public Form2()

{

InitializeComponent();

}



private void Form2_Load(object sender, EventArgs e)

{

myDesignSurface surface = new myDesignSurface();

IDesignerHost host = surface.GetService(typeof(IDesignerHost)) as IDesignerHost;



UserControl root = host.CreateComponent(typeof(UserControl)) as UserControl;

root.Width = this.panel1.Width - 30;

root.Height = this.panel1.Height - 30;



TextBox textbox = host.CreateComponent(typeof(TextBox)) as TextBox;

textbox.Location = new Point(100, 90);

textbox.Text = "textbox";

root.Controls.Add(textbox);



DataGridView dgv = host.CreateComponent(typeof(DataGridView)) as DataGridView;

dgv.Location = new Point(100, 130);

dgv.Text = "DataGridView";

root.Controls.Add(dgv);



Control c = surface.View as Control;

c.Dock = DockStyle.Fill;

c.BackColor = Color.White;

c.Parent = this.panel1;

}

}



class myDesignSurface : DesignSurface

{

public myDesignSurface()

{

MyDesignerOptionService optionService = new MyDesignerOptionService();

this.ServiceContainer.AddService(typeof(DesignerOptionService), optionService);

}

}



class MyDesignerOptionService : DesignerOptionService

{

protected override void PopulateOptionCollection(DesignerOptionCollection options)

{

if (options.Parent == null)

{

DesignerOptionCollection doc =
this.CreateOptionCollection(options, "WindowsFormsDesigner", null);

DesignerOptions doptions = new DesignerOptions();

doptions.UseSmartTags = true;

this.CreateOptionCollection(doc, "General", doptions);

}

}

}

}

No comments: