Hướng dẫn lập trình xuất dữ liệu từ câu lệnh command prompt vb.net
Hôm nay, mình tiếp tục hướng dẫn các bạn cách lấy dữ liệu từ câu lệnh ms-dos trong VB.NET Ví dụ: trong nhiều trường hợp bạn muốn viết một ứng dụng ping đơn giản, để kiểm tra kết nối internet, bạn có thể thực hiện theo bài viết mình hướng dẫn bên dưới ...
Hôm nay, mình tiếp tục hướng dẫn các bạn cách lấy dữ liệu từ câu lệnh ms-dos trong VB.NET
Ví dụ: trong nhiều trường hợp bạn muốn viết một ứng dụng ping đơn giản, để kiểm tra kết nối internet, bạn có thể thực hiện theo bài viết mình hướng dẫn bên dưới để lấy kết quả.
Hoặc các bạn muốn lấy serial number của ổ cứng, từ câu lệnh MS-DOS. Bạn cũng có thể lấy và xuất dễ dàng.
Giao diện Demo ứng dụng:

Bài viết demo ở trên:
Các sử dụng 3 công cụ:
- Một textbox để nhập câu lệnh ms-dos
- Một Richtextbox để hiển thị kết quả
Và một button để thực hiện câu lệnh.
Source code ứng dụng:
Imports System.IO
Public Class Form1
Private psi As ProcessStartInfo
Private cmd As Process
Private Delegate Sub InvokeWithString(ByVal text As String)
Public Sub runCMD()
Try
cmd.Kill()
Catch ex As Exception
End Try
rtbResult.Clear()
If txtCmd.Text.Contains(" ") Then
psi = New ProcessStartInfo(txtCmd.Text.Split(" ")(0), txtCmd.Text.Split(" ")(1))
Else
psi = New ProcessStartInfo(txtCmd.Text$)
End If
Dim systemencoding As System.Text.Encoding
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
cmd = New Process With {.StartInfo = psi, .EnableRaisingEvents = True}
AddHandler cmd.ErrorDataReceived, AddressOf Async_Data_Received
AddHandler cmd.OutputDataReceived, AddressOf Async_Data_Received
cmd.Start()
cmd.BeginOutputReadLine()
cmd.BeginErrorReadLine()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnRun.Click
runCMD()
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)
rtbResult.AppendText(text & Environment.NewLine)
rtbResult.ScrollToCaret()
End Sub
End Class
CHÚC CÁC BẠN THÀNH CÔNG!
DOWNLOAD SOURCE CODE