【发布时间】:2014-01-23 06:55:37
【问题描述】:
我有一个自定义类,它使用 WMI 处理我的串行 COM 端口的收集,它按预期工作。现在,我想将 WMI 查询值传递给我在不使用类时已经完成的组合框。但是,我正在尝试清理我的代码并将部分放入一个类中。我现在正试图通过传递组合框所在的 Form 对象,将组合框传递给位于单独的 .cs 文件中的类方法。我试过:public void getSerialPorts(Form f),但是当我按 f 时。我在 Visual Studio 创建的下拉列表中看不到我的组合框。我认为我的组合对象没有正确传递。有人可以举一个简单的例子来说明如何将表单控件对象传递给类方法以便以后操作它们吗?
代码段:
Form1.cs
private void computerButton_Click(object sender, EventArgs e)
{
bsetup.getSerialPorts(this);
}
setup.cs
public void getSerialPorts(Form f)
{
try
{
string wmiresult;
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Caption like '%mbed% %Serial% %Port% %(COM%'");
foreach (ManagementObject queryObj in searcher.Get())
{
wmiresult = queryObj["Caption"].ToString();
// Here we call Regex.Match.
Match match = Regex.Match(wmiresult, @"\bCOM\d+\b");
// Here we check the Match instance.
if (match.Success)
{
//combo.Add(queryObj["Caption"].ToString(), match.Value);
//comboBox1.Items.Add();
MessageBox.Show(match.Value);
}
}
}
catch (ManagementException er)
{
MessageBox.Show("An error occurred while querying for WMI data: " + er.Message);
}
}
工作示例
private void computerButton_Click(object sender, EventArgs e)
{
var ports = bsetup.getSerialPorts();
comboBox1.DataSource = ports;
//MessageBox.Show(ports.Count.ToString());
}
public IList<string> getSerialPorts()
{
List<string> serialPortResult = new List<string>();
try
{
string wmiresult;
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Caption like '%mbed% %Serial% %Port% %(COM%'");
foreach (ManagementObject queryObj in searcher.Get())
{
wmiresult = queryObj["Caption"].ToString();
// Here we call Regex.Match.
Match match = Regex.Match(wmiresult, @"\bCOM\d+\b");
// Here we check the Match instance.
if (match.Success)
{
//combo.Add(queryObj["Caption"].ToString(), match.Value);
//comboBox1.Items.Add();
MessageBox.Show(match.Value);
serialPortResult.Add(match.Value);
}
}
}
catch (ManagementException er)
{
MessageBox.Show("An error occurred while querying for WMI data: " + er.Message);
}
return serialPortResult;
}
【问题讨论】:
-
你问的是
//combo.Add(queryObj["Caption"].ToString()部分吗?
标签: c# winforms class object controls