2013-04-01 25 views
6

Ho un problema in cui è necessario abilitare una scheda che è già stata disabilitata e un ricercatore su WMI NetworkAdapter non restituisce l'oggetto.Come utilizzare C# per abilitare una scheda di rete wireless disabilitata

Posso pensare a un modo possibile per farlo, ma non sono riuscito a farlo funzionare, questo è creare un oggetto ManagementObject usando questo come nome del costruttore. ma questo solo genera eccezioni

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

L'altro modo è stato quello di sborsare un netsh e attivare il dispositivo, che è una specie di brutto, o per usare shell32/dll "Enable" a fare lo stesso, ancora una volta, sia passando solo il nome. Sto ottenendo il nome da una scansione del registro su HKLM\SYSTEM\CurrentControlSet\Network e cercando MediaType = 2 per ottenere una lista di stringhe di dispositivi wireless. Tutto va bene se eseguo l'applicazione mentre l'adattatore è abilitato in quanto posso ottenere networkObject per il dispositivo wireless ma tutto cade se l'applicazione si avvia mentre il dispositivo wireless è disabilitato.

Grazie

Edit:. Questo è il codice che mi piacerebbe lavorare, ma non andare :(

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; 
    } 
} 

risposta

1

Questo metodo essenzialmente sta utilizzando C# per sfruttare la WMI e Win32_NetworkAdapter Classe E dovrebbe avere metodi incorporati a:

  • Abilita
  • Disabilita

Quindi è possibile eseguire il comando su un'interfaccia selezionata.

È possibile ottenere che in questo modo:

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'è una blog that actually outlines such a task; definisce come creare un wrapper attorno alla classe WMI.

Altro solution may be to also use il 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); 

Speriamo che uno di questi modi aiuto ..

+1

Grazie per la risposta! Quello che non riesco a fare è abilitare un adattatore che è disabilitato come una ricerca non restituisce nulla per un dispositivo disabilitato. Disabilitare il dispositivo è davvero semplice, ma abilitare un dispositivo per il quale non si può ottenere l'oggetto, è il poco che sto avendo problemi con. Idealmente, questo è quello che sto cercando di far funzionare – pedigree

+0

Bene, se interrogate quell'interfaccia esatta dovrebbe permetterti di implementare nel metodo 'enable'. Non è così, quando ci provo, funziona. – Greg

+0

@Grey - hai disattivato il wireless (in Gestione dispositivi) prima di chiamare? In tal caso, quale OS/.NET stai scegliendo come target? – 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

Credo che qualche spiegazione del codice sarebbe molto utile – olyv

Problemi correlati