IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

Activer / désactiver le Bluetooth d'un poste Windows avec du code Csharp


Sujet :

C#

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Profil pro
    Inscrit en
    Octobre 2002
    Messages
    51
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2002
    Messages : 51
    Par défaut Activer / désactiver le Bluetooth d'un poste Windows avec du code Csharp
    Bonjour à tous,

    Pour une application Xaml Windows, je souhaite permettre à l'utilisateur d'activer le Bluetooth de son PC sans qu'il soit obligé de passer par les paramètres Windows.
    Un simple bouton pour activer le Bluetooth s'il n'est pas actif.

    Je pensais trouver rapidement la solution sur le web et bien non

    Pouvez-vous m'aider ?

  2. #2
    Expert confirmé
    Avatar de popo
    Homme Profil pro
    Analyste programmeur Delphi / C#
    Inscrit en
    Mars 2005
    Messages
    2 972
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Analyste programmeur Delphi / C#
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2005
    Messages : 2 972
    Par défaut
    Il existe des API Windows pour le faire.

    Ce lien contient la page des API Windows liée au Bluetooth :
    https://learn.microsoft.com/fr-fr/wi...ectedfrom=MSDN

    Ce lien contient la documentation sur l'API BluetoothSetServiceState qui est celle qui correspond à ton besoin :
    https://learn.microsoft.com/fr-fr/wi...etservicestate

    Ce code montre comment activer ou désactiver le Bluetooth avec BluetoothSetServiceState en tenant compte du fait que
    • BLUETOOTH_SERVICE_DISABLE = 0
    • BLUETOOTH_SERVICE_ENABLE = 1

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    BluetoothSetServiceState(pointer.Handle, ref deviceInfo, ref serviceRef, 0);
    BluetoothSetServiceState(pointer.Handle, ref deviceInfo, ref serviceRef, 1);
    Ce lien contient un exemple de code utilisant BluetoothSetServiceState :
    https://stackoverflow.com/questions/...ice-on-windows

  3. #3
    Membre averti
    Profil pro
    Inscrit en
    Octobre 2002
    Messages
    51
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2002
    Messages : 51
    Par défaut
    Citation Envoyé par popo Voir le message
    Il existe des API Windows pour le faire.

    Ce lien contient la page des API Windows liée au Bluetooth :
    https://learn.microsoft.com/fr-fr/wi...ectedfrom=MSDN

    Ce lien contient la documentation sur l'API BluetoothSetServiceState qui est celle qui correspond à ton besoin :
    https://learn.microsoft.com/fr-fr/wi...etservicestate

    Ce code montre comment activer ou désactiver le Bluetooth avec BluetoothSetServiceState en tenant compte du fait que
    • BLUETOOTH_SERVICE_DISABLE = 0
    • BLUETOOTH_SERVICE_ENABLE = 1

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    BluetoothSetServiceState(pointer.Handle, ref deviceInfo, ref serviceRef, 0);
    BluetoothSetServiceState(pointer.Handle, ref deviceInfo, ref serviceRef, 1);
    Ce lien contient un exemple de code utilisant BluetoothSetServiceState :
    https://stackoverflow.com/questions/...ice-on-windows
    Merci beaucoup.
    J'ai pourtant cherché un bout de temps, je tombais toujours sur les mêmes pages, à côté de mon problème.
    Je teste ça et je reviens passer en résolu ou bien relancer le sujet.

  4. #4
    Membre averti
    Profil pro
    Inscrit en
    Octobre 2002
    Messages
    51
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2002
    Messages : 51
    Par défaut
    Re bonjour,
    Je reviens aujourd'hui sur le sujet.
    En voulant faire un poc le plus simple possible (une Windows Form avec un bouton), je bloque très vite.
    La structure BLUETOOTH_DEVICE_INFO nécessite un en-tête bluetoothapis.h que je ne sais pas implémenter en C#.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
     
    using System.Runtime.InteropServices;
     
    namespace WinFormsApp1
    {
        internal static class Program
        {
            private const string bluetoothDll = "bthprops.cpl";
            /// <summary>
            ///  The main entry point for the application.
            /// </summary>
            [STAThread]
            [DllImport(bluetoothDll, ExactSpelling = true, SetLastError = true)]
            private static extern uint BluetoothSetServiceState(IntPtr hRadio, ref BLUETOOTH_DEVICE_INFO pbtdi, ref Guid pGuidService, uint dwServiceFlags);
     
            static void Main()
            {
     
                // To customize application configuration such as set high DPI settings or default font,
                // see https://aka.ms/applicationconfiguration.
                ApplicationConfiguration.Initialize();
                Application.Run(new Form1());
            }
        }
    }

  5. #5
    Expert confirmé
    Avatar de popo
    Homme Profil pro
    Analyste programmeur Delphi / C#
    Inscrit en
    Mars 2005
    Messages
    2 972
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Analyste programmeur Delphi / C#
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2005
    Messages : 2 972
    Par défaut
    Il suffit de suivre le lien fourni dans la doc.
    https://learn.microsoft.com/fr-fr/wi...ce_info_struct

    On peut alors constater qu'il s'agit d'une structure.
    Code C++ : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    typedef struct _BLUETOOTH_DEVICE_INFO {
      DWORD             dwSize;
      BLUETOOTH_ADDRESS Address;
      ULONG             ulClassofDevice;
      BOOL              fConnected;
      BOOL              fRemembered;
      BOOL              fAuthenticated;
      SYSTEMTIME        stLastSeen;
      SYSTEMTIME        stLastUsed;
      WCHAR             szName[BLUETOOTH_MAX_NAME_SIZE];
    } BLUETOOTH_DEVICE_INFO_STRUCT;

    Cette structure, il faut que tu la traduise en C#.
    Quelque chose comme :
    Code C# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    unsafe struct BLUETOOTH_DEVICE_INFO
    {
        public int dwSize;
        public BLUETOOTH_ADDRESS Address;
        public uint ulClassofDevice;
        public bool fConnected;   
        public bool fRemembered;  
        public bool fAuthenticated; 
        public SYSTEMTIME stLastSeen; 
        public SYSTEMTIME stLastUsed; 
     
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = BLUETOOTH_MAX_NAME_SIZE)]
        public string szName;
    }

    Il faudra bien évidemment suivre d'autres liens pour BLUETOOTH_ADDRESS, SYSTEMTIME et BLUETOOTH_MAX_NAME_SIZE.
    Ces liens sont tous fournis dans le menu à gauche de la documentation.
    https://learn.microsoft.com/fr-fr/wi...ase-systemtime
    https://learn.microsoft.com/fr-fr/wi...address_struct

  6. #6
    Membre averti
    Profil pro
    Inscrit en
    Octobre 2002
    Messages
    51
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2002
    Messages : 51
    Par défaut
    Merci pour votre aide, oui j'en étais là quand j'ai répondu.
    J'avais implémenté la structure en commentant tout ce qui ne passait pas à la compilation :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    [StructLayout(LayoutKind.Sequential)]
    public struct BLUETOOTH_DEVICE_INFO
    {
        public uint dwSize;
        public ulong Address;
        public uint ulClassofDevice;
        public bool fConnected;
        public bool fRemembered;
        public bool fAuthenticated;
        //public SYSTEMTIME stLastSeen;
        //public SYSTEMTIME stLastUsed;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 248)]
        public string szName;
        public uint ulFlags;
    }
     
    namespace WinFormsApp1
    {
        public partial class Form1 : Form
        {
     
     
            //private static extern uint BluetoothSetServiceState(IntPtr hRadio, ref BLUETOOTH_DEVICE_INFO pbtdi, ref Guid pGuidService, uint dwServiceFlags);
     
     
     
     
            public Form1()
            {
                InitializeComponent();
            }
     
            private void button1_Click(object sender, EventArgs e)
            {
                test();
            }
     
            private void test()
            {
                // [DllImport(bluetoothDll, ExactSpelling = true, SetLastError = true)] ;
                //[DllImport("bthprops.cpl"]
                //process.start("control", "bthprops.cpl");
                SetBluetooth(false);
            }
            [DllImport("Irprops.cpl", CharSet = CharSet.Auto, SetLastError = true)]
            static extern int BluetoothSetServiceState(IntPtr handle, ref BLUETOOTH_DEVICE_INFO deviceInfo, ref Guid guidService, uint serviceFlags);
     
            public static void SetBluetooth(bool enable)
            {
                BLUETOOTH_DEVICE_INFO deviceInfo = new BLUETOOTH_DEVICE_INFO();
                //deviceInfo.dwSize = Marshal.SizeOf(deviceInfo);
                //deviceInfo.Address = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
                //deviceInfo.ulClassofDevice = 0x200404;
                //deviceInfo.fConnected = false;
                //deviceInfo.fRemembered = false;
                //deviceInfo.fAuthenticated = false;
                //deviceInfo.szName = new byte[248];
                deviceInfo.ulFlags = 0;
     
                Guid serviceClass = new Guid(0x00001101, 0x0000, 0x1000, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB);
                uint serviceFlags = enable ? 1u : 0u;
     
                BluetoothSetServiceState(IntPtr.Zero, ref deviceInfo, ref serviceClass, serviceFlags);
            }
     
        }
    }
    Mais ce que je crois comprendre, c'est que BluetoothSetServiceState a pour objet de désactiver les périphériques Bluetooth connectés.
    Ce que je cherche à faire, c'est juste activer le Bluetooth du PC s'il n'est pas actif :
    Nom : bluetooth.png
Affichages : 300
Taille : 9,3 Ko

Discussions similaires

  1. Réponses: 2
    Dernier message: 11/04/2011, 19h30
  2. Récupérer le logon post-Windows 2000 dans l'active directory
    Par Tuizi dans le forum VB 6 et antérieur
    Réponses: 0
    Dernier message: 11/09/2007, 11h50
  3. Réponses: 10
    Dernier message: 30/12/2005, 20h08
  4. surveillance de mon poste windows
    Par zetta dans le forum Autres Logiciels
    Réponses: 3
    Dernier message: 28/11/2005, 17h03
  5. Activer le paver numérique au démarrage de Windows
    Par Furius dans le forum Windows XP
    Réponses: 17
    Dernier message: 19/10/2005, 07h05

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo