c# - 您如何确定 Internet 连接是否可用于您的 WinForms 应用程序?

标签 c# .net winforms

确定 WinForms 应用程序是否有可用的 Internet 连接的最佳方法是什么。 (当然是编程方式)如果用户未连接到 Internet,我想禁用/隐藏某些功能。

最佳答案

以下将确定您是否已连接到网络,但这并不一定意味着您已连接到 Internet:

NetworkInterface.GetIsNetworkAvailable() 

这是 Steve 代码的 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); 

关于c# - 您如何确定 Internet 连接是否可用于您的 WinForms 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/194742/

相关文章:

c# - 如何使用 ajax 将嵌套的 json 对象发送到 mvc Controller

.net - 动态 LINQ 查询

c# - ASP.NET Web api 上的文件上传端点损坏文件

c# - IEnumerable.ElementAt - 值存在时参数超出范围异常

c# - 在 Excel 中更改 CellValue 中文本的字体颜色 - OpenXml

c# - 警告 : The optional WSDL extension element 'body' from namespace 'http://schemas.xmlsoap.org/wsdl/soap/' was not handled

c# - 无法在 .NET Standard 1.4 中使用 DBNull?

c# - WPF 相当于 Winform 的 KeyEventArgs - 使用特定键调用 KeyDown 事件

.net - 确定是否在没有System.Web的ASP.NET或WinForms/控制台中运行

c# - 正在运行的BackgroundWorker的处理