确定WinForms应用程序是否有可用Internet连接的最佳方法是什么.(当然是以编程方式)如果用户未连接到Internet,我想禁用/隐藏某些功能.
sbe*_*kur 15
以下将确定您是否连接到网络,但这并不一定意味着您已连接到Internet:
NetworkInterface.GetIsNetworkAvailable() 
这是史蒂夫的代码的C#翻译似乎相当不错:
private static int ERROR_SUCCESS = 0;
public static bool IsInternetConnected() {
    long dwConnectionFlags = 0;
    if (!InternetGetConnectedState(dwConnectionFlags, 0))
        return false;
    if(InternetAttemptConnect(0) != ERROR_SUCCESS)
        return false;
    return true;
}
 [DllImport("wininet.dll", SetLastError=true)]
 public static extern int InternetAttemptConnect(uint res);
 [DllImport("wininet.dll", SetLastError=true)]
  public static extern bool InternetGetConnectedState(out int flags,int reserved); 
Jar*_*Par 10
sbeskur的回复在InternetGetConnectedState的翻译中存在错误.参数都是DWORD(第一个是LPDWORD).这两个都转换为C#中的int(技术上,uint但int适用于大多数场景).
正确翻译如下.
[DllImport("wininet.dll", SetLastError=true)] 
public static extern bool InternetGetConnectedState(out int flags,int reserved);
我不是ac#developer,但在C++中你可以使用Win32 API(特别是来自Wininet.dll),如下所示:
bool IsInternetConnected( void )
{
    DWORD dwConnectionFlags = 0;
    if( !InternetGetConnectedState( &dwConnectionFlags, 0 ) )
        return false;
    if( InternetAttemptConnect( 0 ) != ERROR_SUCCESS )
        return false;
    return true;
}
我认为这很简单地变成了c#
| 归档时间: | 
 | 
| 查看次数: | 6634 次 | 
| 最近记录: |