C#检测网络的连接状态
1. 方法定义
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState( out int connectionDescription, int reservedValue ) ;
2.
方法说明
参数:
connectionDescription : 连接说明
reservedValue : 保留值
返回值:
true: On Line
false: Off Line
3. 调用方法
a. 你必须在你的code里引用System.Runtime.InteropServices,否则,会有编译错误
b. 定义一个变量 int I = 0;
c. 调用bool = InternetGetConnectedState(out I,0);
完整的代码:
using System.Runtime.InteropServices;
namespace internet
{
public class Class1
{
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState( out int connectionDescription, int reservedValue ) ;
public Class1(){}
/// <summary>
/// 检测本机是否联网
/// </summary>
/// <returns></returns>
public static bool IsConnectedInternet()
{
int i = 0;
if (InternetGetConnectedState(out i, 0))
{
//已联网
return true;
}
else
{
//未联网
return false;
}