C# 在c中以编程方式添加工具栏及其内容#

C# 在c中以编程方式添加工具栏及其内容#,c#,winforms,C#,Winforms,我是一个简单问题(c#)的绝对初学者。我想在运行时创建一个工具栏及其事件。我使用visual studio 2008、.net framework 3.5、c#。例如,在窗体类中,您可以制作如下内容: ToolStrip toolStrip2 = new ToolStrip(); toolStrip2.Items.Add(new ToolStripDropDownButton()); toolStrip2.Dock = DockStyle.Bottom; this.Controls.Add(to

我是一个简单问题(c#)的绝对初学者。我想在运行时创建一个工具栏及其事件。我使用visual studio 2008、.net framework 3.5、c#。例如,在窗体类中,您可以制作如下内容:

ToolStrip toolStrip2 = new ToolStrip();
toolStrip2.Items.Add(new ToolStripDropDownButton());
toolStrip2.Dock = DockStyle.Bottom;
this.Controls.Add(toolStrip2);
使用系统;
使用System.IO;
使用System.Windows.Forms;
命名空间DynamicToolStrip
{
静态类程序
{
[状态线程]
静态void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Run(新的DynamicToolStripForm());
}
类DynamicToolStripForm:Form
{
ToolStrip m_ToolStrip=新ToolStrip();
公共DynamicToolStripForm()
{
控件。添加(m_toolstrip);
AddToolStripButtons();
}
void AddToolStripButtons()
{
常量int iMAX_文件=5;
字符串[]astfiles=Directory.GetFiles(@“C:\”);
对于(int i=0;i
好的,那么是什么阻止了您?您尝试了什么?只需将设计器创建的代码复制到运行时事件中,然后继续操作,直到成功。
using System;
using System.IO;
using System.Windows.Forms;
namespace DynamicToolStrip
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new DynamicToolStripForm());
        }
        class DynamicToolStripForm : Form
        {
            ToolStrip m_toolstrip = new ToolStrip();
            public DynamicToolStripForm()
            {
                Controls.Add(m_toolstrip);
                AddToolStripButtons();
            }
            void AddToolStripButtons()
            {
                const int iMAX_FILES = 5;
                string[] astrFiles = Directory.GetFiles(@"C:\");
                for (int i = 0; i < iMAX_FILES; i++)
                {
                    string strFile = astrFiles[i];
                    ToolStripButton tsb = new ToolStripButton();
                    tsb.Text = Path.GetFileName(strFile);
                    tsb.Tag = strFile;
                    tsb.Click += new EventHandler(tsb_Click);
                    m_toolstrip.Items.Add(tsb);
                }
            }
            void tsb_Click(object sender, EventArgs e)
            {
                ToolStripButton tsb = sender as ToolStripButton;
                if (tsb != null && tsb.Tag != null)
                    MessageBox.Show(String.Format("Hello im the {0} button", tsb.Tag.ToString()));
            }
        }
    }
}