1. /// <summary>
    2. /// 遍历窗体子控件和孙控件,将所有控件置于allCtrls
    3. /// </summary>
    4. private static Queue<Control> allCtrls = new Queue<Control>();
    5. private static void CheckAllCtrls(Control item)
    6. {
    7. for (int i = 0; i < item.Controls.Count; i++)
    8. {
    9. if (item.Controls[i].HasChildren)
    10. {
    11. CheckAllCtrls(item.Controls[i]);
    12. }
    13. else
    14. {
    15. allCtrls.Enqueue(item.Controls[i]);
    16. }
    17. }
    18. }
    19. /*然后一定注意在窗体的构造函数中写!!!*/
    20. public SysSetting()
    21. {
    22. InitializeComponent();
    23. CheckAllCtrls(this);//表示生成子窗体的时候已经遍历窗体的所有控件和子控件
    24. }
    25. /*使用举例:想要找到设置窗体中的文本框并保存其中的数据*/
    26. public void saveSet(string filePath)
    27. {
    28. //string newset = "#系统设置";
    29. StreamWriter sw = new StreamWriter(filePath,false);
    30. sw.Write("");
    31. string newset = "#系统设置";
    32. foreach (Control c in allCtrls)
    33. {
    34. if ((c is TextBox) && (c.Text != null))
    35. {
    36. newset += "\r\n" + c.Name + "=" + c.Text;
    37. //File.AppendText(newset);
    38. }
    39. if (c is CheckBox && (((CheckBox)c).Checked == true))
    40. {
    41. newset += "\r\n" + c.Name + "=" + "1";
    42. // File.AppendText(newset);
    43. }
    44. if (c is CheckBox && (((CheckBox)c).Checked == false))
    45. {
    46. newset += "\r\n" + c.Name + "=" + "0";
    47. //File.AppendText(newset);
    48. }
    49. //File.AppendText(newset);
    50. }
    51. sw.Write(newset);
    52. sw.Flush();
    53. sw.Close();
    54. }