Windows Command Processor หรือ Command Prompt (cmd.exe) คือ แอพพลิเคชันตัวแปลบรรทัดคำสั่ง (command line interpreter) ทำงานบนระบบปฎิบัติการ Windows สามารถสั่งงานให้ Windows ทำงานได้โดยตรง เช่น เปิดไฟล์ เปิดเว็ปไซต์ ปิดคอม ฯลฯ เรียกได้ว่าทุกอย่างที่เราทำได้จากการคลิ๊กเมาส์ใน Windows
สำหรับการเขียนแอพพลิเคชัน .NET ในที่นี่จะยกตัวอย่างเป็นภาษา vb ซึ่งเขียนด้วยโปรแกรม Visual Basic Studio 2019 เรามาเริ่มกันเลย…
1. ความสอดคล้อง
ภาษา vb จะใช้ Process Class เพื่อสั่งงาน Windows เช่นเดียวกับ Command Prompt ตัวอย่าง
Command Prompt:
ping www.google.com
Process Class:
Filename = ping
Arguments = www.google.com
2. การใช้งาน

เนื่อหาของโค๊ด
Public Class Form1
Private psi As ProcessStartInfo
Private cmd As Process
Private Delegate Sub InvokeWithString(ByVal text As String)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
cmd.Kill()
Catch ex As Exception
End Try
psi = New ProcessStartInfo(cbFile.Text, cbArg.Text)
Dim systemEncoding = System.Text.Encoding.UTF8
System.Text.Encoding.GetEncoding(Globalization.CultureInfo.CurrentUICulture.TextInfo.OEMCodePage)
With psi
.UseShellExecute = False
.RedirectStandardError = True
.RedirectStandardOutput = True
.RedirectStandardInput = True
.CreateNoWindow = True
.StandardOutputEncoding = systemEncoding
.StandardErrorEncoding = systemEncoding
End With
txtResult.Clear()
cmd = New Process With {.StartInfo = psi, .EnableRaisingEvents = True}
AddHandler cmd.ErrorDataReceived, AddressOf Async_Data_Received
AddHandler cmd.OutputDataReceived, AddressOf Async_Data_Received
Try
cmd.Start()
cmd.BeginOutputReadLine()
cmd.BeginErrorReadLine()
Catch ex As Exception
txtResult.AppendText(ex.ToString & Environment.NewLine)
txtResult.ScrollToCaret()
End Try
End Sub
Private Sub Async_Data_Received(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
Me.Invoke(New InvokeWithString(AddressOf Sync_Output), e.Data)
End Sub
Private Sub Sync_Output(ByVal text As String)
' text is null?
If IsNothing(text) Then
'Console.WriteLine("text is null")
Return
End If
' Print result
txtResult.AppendText(text & Environment.NewLine)
txtResult.ScrollToCaret()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'File Name Example
cbFile.Items.Add("netsh")
'Arguments
cbArg.Items.Add("wlan show profile")
cbArg.Items.Add("wlan show interfaces")
End Sub
End Class

การทดสอบ

3. สรุป
หัวใจสำคัญของการใช้ Command Prompt ใน vb คือ Filename และ Argument ที่ป้อนให้กับ Process Class ซึ่งเราสามารถอ่านค่าได้จากคำสั่งที่ใช้กับ Command Prompt โดย Filename จะอยู่ต้นคำสั่งเสมอ ดังรูป

การใช้ Command Prompt ในแอพพลิเคชัน .NET ช่วยทำให้เราสร้างแอพพลิเคชันที่เข้าถึงความสามารถของ Windows ได้ง่ายมากขึ้น และแอพพลิเคชันมีขนาดเล็กลง
4. ดาวน์โหลด
Command Line Project
Command Line Installer
5. อ้างอิง
https://stackoverflow.com/a/47148088
https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process?view=netframework-4.8