2013-04-01 20 views
6

Tôi gặp sự cố khi tôi cần bật thẻ đã bị tắt và người tìm kiếm trên WMI NetworkAdapter không trả lại đối tượng.Cách sử dụng C# để bật thẻ mạng không dây bị vô hiệu

Tôi có thể nghĩ ra một cách có thể để làm điều này nhưng tôi không thể làm cho nó hoạt động, đó là tạo một managedObject sử dụng tên này làm tên hàm dựng. nhưng điều này chỉ ném ngoại lệ

{\\.\root\CIMV2:Win32_NetworkAdapter.NetConnectionID='Wireless Network Connection'}

Một cách khác là để bao một netsh và cho phép các thiết bị, mà là loại xấu xí, hoặc sử dụng shell32/dll "Bật" để làm như vậy, một lần nữa, cả hai chỉ truyền tên. Tôi đã nhận được tên từ một đăng ký quét trên HKLM\SYSTEM\CurrentControlSet\Network và tìm kiếm MediaType = 2 để có được một danh sách chuỗi các thiết bị không dây. Tất cả đều tốt nếu tôi chạy ứng dụng trong khi bộ điều hợp được bật vì tôi có thể lấy networkObject cho thiết bị không dây nhưng tất cả đều đổ xuống nếu ứng dụng khởi động trong khi thiết bị không dây bị tắt.

Cảm ơn

Edit:. Đây là đoạn code mà tôi rất thích làm việc nhưng không đi :(

using System; 
using System.Management; 
class Sample 
{ 
    public static int Main(string[] args) 
    { 
     ManagementObject mObj = new ManagementObject("\\\\.\\root\\CIMV2:Win32_NetworkAdapter.NetConnectionID=\"Wireless Network Connection\""); 
     mObj.InvokeMethod("Enable", null); 
     return 0; 
    } 
} 

Trả lời

1

Phương pháp này chủ yếu được sử dụng C# để tận dụng WMI và Win32_NetworkAdapter Lớp Nó cần phải có phương pháp xây dựng vào cho:

  • Enable
  • Disable

Vì vậy, bạn có thể thực hiện lệnh của mình trên giao diện Đã chọn.

Bạn có thể đạt được điều đó theo cách này:

SelectQuery query = new SelectQuery("Win32_NetworkAdapter", "NetConnectionStatus=2"); 
ManagementObjectSearcher search = new ManagementObjectSearcher(query); 
foreach(ManagementObject result in search.Get()) 
{ 
    NetworkAdapter adapter = new NetworkAdapter(result); 

    // Identify the adapter you wish to disable here. 
    // In particular, check the AdapterType and 
    // Description properties. 

    // Here, we're selecting the LAN adapters. 
    if (adapter.AdapterType.Equals("Ethernet 802.3")) 
    { 
     adapter.Disable(); 
    } 
} 

Có một blog that actually outlines such a task; nó định nghĩa cách tạo Wrapper quanh lớp WMI.

Khác solution may be to also use số ControlService (advapi32).

[DllImport("advapi32.dll", SetLastError=true)] 
[return: MarshalAs(UnmanagedType.Bool)] 
public static extern bool ControlService(IntPtr hService, SERVICE_CONTROL dwControl, ref SERVICE_STATUS lpServiceStatus); 

Hy vọng rằng một trong những cách giúp ..

+1

Cảm ơn bạn đã trả lời! Những gì tôi không thể có vẻ để làm cho nó là Bật một adapter bị vô hiệu hóa như là một tìm kiếm không trả lại bất cứ điều gì cho một thiết bị vô hiệu hóa. Vô hiệu hóa thiết bị thực sự dễ dàng nhưng cho phép một thiết bị mà bạn không thể có được đối tượng, là bit mà Im gặp sự cố. Lý tưởng nhất, đây là những gì tôi đang cố gắng để làm việc – pedigree

+0

Vâng, nếu bạn truy vấn giao diện chính xác nó sẽ cho phép bạn thực hiện trong phương thức 'enable'. Liệu nó không, khi tôi thử nó- nó hoạt động. – Greg

+0

@Grey - bạn có tắt chức năng không dây (trong trình quản lý thiết bị) trước khi gọi không? Nếu vậy, bạn đang sử dụng hệ điều hành/.NET nào? – pedigree

0
  using System; 
      using System.Collections.Generic; 
      using System.ComponentModel; 
      using System.Data; 
      using System.Drawing; 
      using System.Linq; 
      using System.Text; 
      using System.Windows.Forms; 
      using System.Diagnostics; 
      using System.Security.Principal; 

      namespace WifiRouter 
      { 
       public partial class Form1 : Form 
       { 
        bool connect = false; 
        public Form1() 
        { 

         InitializeComponent(); 
        } 

        public static bool IsAdmin() 
        { 
         WindowsIdentity id = WindowsIdentity.GetCurrent(); 
         WindowsPrincipal p = new WindowsPrincipal(id); 
         return p.IsInRole(WindowsBuiltInRole.Administrator); 
        } 
        public void RestartElevated() 
        { 
         ProcessStartInfo startInfo = new ProcessStartInfo(); 
         startInfo.UseShellExecute = true; 
         startInfo.CreateNoWindow = true; 
         startInfo.WorkingDirectory = Environment.CurrentDirectory; 
         startInfo.FileName = System.Windows.Forms.Application.ExecutablePath; 
         startInfo.Verb = "runas"; 
         try 
         { 
          Process p = Process.Start(startInfo); 
         } 
         catch 
         { 

         } 

         System.Windows.Forms.Application.Exit(); 
        } 
        private void button1_Click(object sender, EventArgs e) 
        { 
         string ssid = textBox1.Text, key = textBox2.Text; 
         if (!connect) 
         { 
          if (String.IsNullOrEmpty(textBox1.Text)) 
          { 
           MessageBox.Show("SSID cannot be left blank !", 
           "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); 
          } 
          else 
          { 

           if (textBox2.Text == null || textBox2.Text == "") 
           { 
            MessageBox.Show("Key value cannot be left blank !", 
            "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); 
           } 
           else 
           { 
            if (key.Length >= 6) 
            { 
             Hotspot(ssid, key, true); 
             textBox1.Enabled = false; 
             textBox2.Enabled = false; 
             button1.Text = "Stop"; 
             connect = true; 
            } 
            else 
            { 
             MessageBox.Show("Key should be more then or Equal to 6 Characters !", 
             "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); 
            } 
           } 
          } 
         } 
         else 
         { 
          Hotspot(null, null, false); 
          textBox1.Enabled = true; 
          textBox2.Enabled = true; 
          button1.Text = "Start"; 
          connect = false; 
         } 
        } 
        private void Hotspot(string ssid, string key,bool status) 
        { 
         ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe"); 
         processStartInfo.RedirectStandardInput = true; 
         processStartInfo.RedirectStandardOutput = true; 
         processStartInfo.CreateNoWindow = true; 
         processStartInfo.UseShellExecute = false; 
         Process process = Process.Start(processStartInfo); 

         if (process != null) 
         { 
          if (status) 
          { 
           process.StandardInput.WriteLine("netsh wlan set hostednetwork mode=allow ssid=" + ssid + " key=" + key); 
           process.StandardInput.WriteLine("netsh wlan start hosted network"); 
           process.StandardInput.Close(); 
          } 
          else 
          { 
           process.StandardInput.WriteLine("netsh wlan stop hostednetwork"); 
           process.StandardInput.Close(); 
          } 
         } 
        } 

        private void Form1_Load(object sender, EventArgs e) 
        { 
         if (!IsAdmin()) 
         { 
          RestartElevated(); 
         } 
        } 

        private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
        { 
         Hotspot(null, null, false); 
         Application.Exit(); 
        } 
       } 
      } 
+1

Tôi tin rằng, một số giải thích về mã sẽ rất hữu ích – olyv

Các vấn đề liên quan