我正在尝试编写一个小型Windows窗体GUI,它将接收WMI查询的文本,并将该WMI查询的输出/结果显示在窗体上的文本框中。
为了证明一切正常,我试图让GUI将WMI输出写入命令行控制台,但到目前为止我没有运气显示输出。
我哪里出错了(我是C#的新手,所以这将是一个很长的名单!)?
这是我正在使用的表单背后的代码......
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Management;
namespace WMI_Form1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_runQuery_Click(object sender, EventArgs e)
{
string _userName = textBox1_userName.Text;
string _passWord = textBox2_password.Text;
string _serverName = textBox3_serverName.Text;
string _wmiQuery = textBox4_queryInput.Text;
EnumServices(_serverName, _userName, _passWord);
}
static void EnumServices(string host, string username, string password)
{
string ns = @"root\cimv2";
string query = "SELECT * FROM Win32_LogicalDisk";
//string query = "select * from Win32_Service";
ConnectionOptions options = new ConnectionOptions();
if (!string.IsNullOrEmpty(username))
{
options.Username = username;
options.Password = password;
}
ManagementScope scope =
new ManagementScope(string.Format(@"\\{0}\{1}", host, ns), options);
scope.Connect();
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, new ObjectQuery(query));
ManagementObjectCollection retObjectCollection = searcher.Get();
foreach (ManagementObject mo in searcher.Get())
{
Console.WriteLine("Trying to output the results...");
Console.WriteLine(mo.GetText(TextFormat.Mof));
}
}
}
}
答案 0 :(得分:1)
由于您的项目是“Windows”应用程序而不是“控制台”应用程序,因此您没有显示/附加的控制台窗口....因此Console.WriteLine
输出无处可去。
而不是为您的GUI应用程序创建“控制台”(例如通过AllocConsole
- http://msdn.microsoft.com/en-us/library/windows/desktop/ms682528(v=vs.85).aspx),而这将允许您看到Console.WriteLine
输出。 ..在这种情况下没有必要...因为最终你将输出到ListBox ...而你只是想快速“看到”数据。
最快的方法是使用“Trace”或“Debug”输出语句:
(What’s the difference between the Debug class and Trace class?):
所以:
System.Diagnostics.Trace.WriteLine("Trying to output the results...");
System.Diagnostics.Trace.WriteLine(mo.GetText(TextFormat.Mof));
或
System.Diagnostics.Debug.WriteLine("Trying to output the results...");
System.Diagnostics.Debug.WriteLine(mo.GetText(TextFormat.Mof));
如果从中运行程序的“debug”版本,输出将出现在Visual Studio的“输出”窗口中。
如果在Visual Studio之外启动程序,则可以使用DebugView(http://technet.microsoft.com/en-gb/sysinternals/bb896647.aspx)查看调试输出。
确认它正常工作后,您可以输入逻辑,将输出添加到ListBox
中。