首先引入命名空间:
using System.Runtime.InteropServices;
再定义如下:
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);
定义一个判断网络连接的函数:
private bool IsConnected()
{
int I = 0;
bool state = InternetGetConnectedState(out I, 0);
return state;
}
在按钮里写以下代码:
if (IsConnected())
{
MessageBox.Show("状态:网络畅通!");
}
else
{
MessageBox.Show("状态:与目标网络无连接!");
}