Solve của bạn Duong_Act chỉ chạy đúng khi máy không có Virtual Network Interface. Bạn có thể dùng class System.Net.NetworkInformation.Ping
để kiểm tra.
using System;
using System.Drawing;
using System.Net.NetworkInformation;
using System.Windows.Forms;
namespace CheckInternet
{
public partial class Form1 : Form {
Timer timer;
public Form1() {
InitializeComponent();
timer = new Timer();
timer.Interval = 5000;//Tự check lại mỗi 5 giây
timer.Tick += Timer_Tick;
timer.Start();
}
private async void Timer_Tick(object sender, EventArgs e)
{
bool status = false;
try
{
Ping ping = new Ping();
int timeout = 1000;
string host = "google.com";
var pingReply = await ping.SendPingAsync(host,timeout);
status = pingReply.Status == IPStatus.Success;
}
catch (Exception)
{
status = false;
}
ShowNetworkConnection(status);
}
private void ShowNetworkConnection(bool conn) {
if (conn) {
lblConnect.Text = "Connected";
lblConnect.ForeColor = Color.Green;
} else {
lblConnect.Text = "Disconnet";
lblConnect.ForeColor = Color.Red;
}
}
}
}