15. using System;
using System.Text.RegularExpressions;
using System.Management;
namespace GetComDevices
{
class Program
{
static void Main(string[] args)
{
Regex check = new Regex("(COM[1-9][0-9]?[0-9]?)");
ManagementClass mc = new ManagementClass("Win32_PnPEntity");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
var namepv = mo.GetPropertyValue("Name");
if (namepv == null) continue;
string name = namepv.ToString();
if (check.IsMatch(name))
{
Console.WriteLine(name+"t"+check.Match(name));
}
}
}
}
}
.exeファイルはプロジェクトフォルダの直下に配置。
16. //イベントハンドラの設定
p.OutputDataReceived += OutputDataHandler;
p.EnableRaisingEvents = true;
p.Exited += Process_Exit;
//実行
p.Start();
p.BeginOutputReadLine();
}
//出力を受け取るとたたかれる
private void OutputDataHandler(object sender, DataReceivedEventArgs args)
{
if (!string.IsNullOrEmpty(args.Data))
{
if (args.Data.IndexOf(SearchWord) != -1)
{
PortNum = args.Data.Split('t')[1].Trim();
}
}
}
//出力が終わったらSerialHandlerの設定用メソッドをたたく
private void Process_Exit(object sender, EventArgs e)
{
sh.SetPortName(PortNum);
Process proc = (Process)sender;
proc.Kill();
}
}
using System;
using System.Diagnostics;
using System.IO;
using UnityEngine;
using Debug = UnityEngine.Debug;
public class SearchCom : MonoBehaviour
{
public SerialHandler sh;
public String SearchWord; //ハードウェア名(部分一致でおk)
private String PortNum;
void Awake() {
ProcessStart();
}
/// <summary>
/// プロセスをたたく
/// </summary>
void ProcessStart()
{
Process p = new Process
{
StartInfo =
{
FileName =Directory.GetCurrentDirectory() +
@"GetComDevices.exe",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = false,
RedirectStandardInput = false,
CreateNoWindow = true
}
};
SearchCom.cs – コンソールアプリを実行,SerialHandlerへの代入処理