以编程方式创建ToolStrip按钮 [英] Programmatically create ToolStrip buttons
本文介绍了以编程方式创建ToolStrip按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试根据文件夹的内容创建工具条按钮,到目前为止,我是这样的:
//Collect list of files<br /> string dir = "C:\\Documents and Settings\\Herr Xandor\\Desktop\\Toolbar";<br /> string[] files = System.IO.Directory.GetFiles(dir);<br /> //Format string array<br /> int x = 0;<br /> int index = 0;<br /> foreach (string temp in files)<br /> {<br /> index = temp.LastIndexOf(''\\'');<br /> files[x] = temp.Substring(index + 1);<br /> x += 1;<br /> }<br />
我的问题是,如何基于数组的内容创建按钮.我知道我需要另一个foreach循环,该循环为每个按钮运行必要的命令,但是如何控制命名和onClick方法?我不知道如何使用变量来命名对象.我很确定我可以通过使用按钮数组来创建按钮,但是该如何创建事件处理程序呢?
解决方案
此 [ string[] files = System.IO.Directory.GetFiles(dir);<br /> //Format string array<br /> int x = 0;<br /> int index = 0;<br /> foreach (string temp in files)<br /> {<br /> index = temp.LastIndexOf(''\\'');<br /> files[x] = temp.Substring(index + 1);<br /> x += 1;<br /> }<br />
My question is, how can I create buttons based on the contents of the array. I understand that I need another foreach loop that runs the necessary commands for each button but how can I control the naming and the onClick methods? I know of no way to use a variable to name an object. I''m pretty sure I can get it to create the buttons by using an array of buttons, but then how can I create the event handlers?解决方案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())); } } } }
This [^] thread might help.
这篇关于以编程方式创建ToolStrip按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文