Activar y desactivar bluetooth

Esta sección es para preguntas sobre programación/scripting usando AutoHotkey.

Moderator: Flipeador

imloza
Posts: 2
Joined: 28 Dec 2022, 07:28

Activar y desactivar bluetooth

27 Feb 2024, 04:23

Hola buenas, tengo este codigo y necesito que cuando lo vuelva a ejecutar me desactive el bluetooth, he probado otros metodos, pero directamente no lo activaba ni desactivaba, este si me activa el bluetooth, pero cuando lo vuelvo a ejecutar me dice que el bluetooth esta activado, lo que yo quiero es que lo desactive, es decir si lo activo manualmente, detecte que lo tiene que desactivar.

Muchas gracias de antemano.
Attachments
Nuevo AutoHotkey Script.ahk
(5.12 KiB) Downloaded 13 times
garry
Posts: 3771
Joined: 22 Dec 2013, 12:50

Re: Activar y desactivar bluetooth

27 Feb 2024, 16:21

un ejemplo breve y sencillo para probar

Code: Select all

;Run,ms-settings:bluetooth  ;- ahk_V1
;exitapp
;-
Run("ms-settings:bluetooth") ;- ahk_V2
ExitApp()
F8/F9 > ON/OFF

Code: Select all

#Requires AutoHotkey v2
;--
$F8::
{
RadioModule('Bluetooth').SetState('On')
; or RadioModule('Bluetooth').State := 'On'
Run("ms-settings:bluetooth")
return
}
;---
$F9::
{
RadioModule('Bluetooth').SetState('Off')
; or RadioModule('Bluetooth').State := 'Off'
Run("ms-settings:bluetooth")
return
}
garry
Posts: 3771
Joined: 22 Dec 2013, 12:50

Re: Activar y desactivar bluetooth

28 Feb 2024, 08:32

F7 > toggle ON/OFF

Code: Select all

;- Activar y desactivar bluetooth 
;- https://www.autohotkey.com/boards/viewtopic.php?f=40&t=126581&p=560889#p560889

#Requires AutoHotkey v2
;Run("ms-settings:bluetooth")

;- toggle
$F7:: 
{
static toggled := false
if toggled := !toggled
   RadioModule('Bluetooth').SetState('On')
else
   RadioModule('Bluetooth').SetState('Off')
return
}
;---
esc::exitapp()
;----
class RadioModule
{
    ; Docs: https://tinyurl.com/ynr9mkz4
    ; Header: windows.devices.radios.h
    RadioKind         := ['Other', 'WiFi', 'MobileBroadband', 'Bluetooth', 'FM']
    RadioState        := ['Unknown', 'On', 'Off', 'Disabled']
    RadioAccessStatus := ['Unspecified', 'Allowed', 'DeniedByUser', 'DeniedBySystem']
    ; kind can be 'WiFi', 'MobileBroadband', 'Bluetooth', 'FM'
    __New(kind) {
        radios := IReadOnlyList( RadioModule.Await(IRadioStatics.GetRadiosAsync()) )
        Loop radios.Count {
            radio := IRadio(radios.Item[A_Index - 1])
        } until this.RadioKind[radio.Kind + 1] = kind && this.module := radio
        if !this.HasOwnProp('module') {
            MsgBox kind . ' not found', 'Not found', 0x30
            ExitApp
        }
        this.kind := kind
    }
    ; state can be 'On' or 'Off'
    SetState(state) {
        accessStatus := ''
        if !(state ~= 'i)^(On|Off)$') {
            MsgBox 'Only "On" and "Off" states are supported', 'State not supported', 0x30
        } else if this.State = state {
            MsgBox this.kind . ' is already turned ' . StrLower(state), ' ', 0x40
        } else {
            pIAsyncOperation := this.module.SetStateAsync(state = 'On' ? 1 : 2)
            accessStatus := this.RadioAccessStatus[RadioModule.Await(pIAsyncOperation) + 1]
            if accessStatus != 'Allowed' {
                MsgBox 'Failed to turn ' . StrLower(state) . ' ' . this.kind . '.`nAccess status: ' . accessStatus, 'Error', 0x10
            }
			else
			{
			MsgBox 'BLUETOOTH now TURNED to >  ' . StrLower(state)
			}
        }
        return accessStatus = 'Allowed'
    }
    State {
        get => this.RadioState[this.module.State + 1]
        set => this.SetState(value)
    }
    Name => WrtString(this.module.Name).GetText()
    static Await(pIAsyncOperation) {
        static AsyncStatus := ['Started', 'Completed', 'Canceled', 'Error']
        AsyncOperation := IAsyncOperation(pIAsyncOperation)
        AsyncInfo := IAsyncInfo(AsyncOperation.QueryIAsyncInfo())
        Loop {
            Sleep 10
            status := AsyncStatus[AsyncInfo.Status + 1]
        } until status != 'Started'
        if (status != 'Completed') {
            throw OSError('AsyncInfo error, status: "' . status . '"', A_ThisFunc)
        }
        return AsyncOperation.GetResults()
    }
}
class IRadioStatics {
    static __New() {
        static IID_IRadioStatics := '{5FB6A12E-67CB-46AE-AAE9-65919F86EFF4}'
             , VT_UNKNOWN := 13, runtimeClass := 'Windows.Devices.Radios.Radio'
        DllCall('Ole32\CLSIDFromString', 'Str', IID_IRadioStatics, 'Ptr', CLSID := Buffer(16))
        this.comObj := ComValue(VT_UNKNOWN, WrtString(runtimeClass).GetFactory(CLSID))
        this.ptr := this.comObj.ptr
    }
    static GetRadiosAsync() => (ComCall(6, this, 'PtrP', &pIAsyncOperation := 0), pIAsyncOperation)
}
class IRadio extends InterfaceBase
{
    SetStateAsync(state) => (ComCall(6, this, 'Int', state, 'PtrP', &pIAsyncOperation := 0), pIAsyncOperation)
    State => (ComCall( 9, this, 'IntP', &state   := 0), state)
    Name  => (ComCall(10, this, 'PtrP', &hString := 0), hString)
    Kind  => (ComCall(11, this, 'IntP', &kind    := 0), kind)
}
class IReadOnlyList extends InterfaceBase
{
    Item[index] => (ComCall(6, this, 'Int', index, 'PtrP', &pItem := 0), pItem)
    Count => (ComCall(7, this, 'UIntP', &count := 0), count)
}
class IAsyncOperation extends InterfaceBase
{
    QueryIAsyncInfo() => ComObjQuery(this, IID_IAsyncInfo := '{00000036-0000-0000-C000-000000000046}')
    GetResults() => (ComCall(8, this, 'PtrP', &pResult := 0), pResult)
}
class IAsyncInfo extends InterfaceBase
{
    Status => (ComCall(7, this, 'PtrP', &status := 0), status)
}
class InterfaceBase
{
    __New(ptr) {
        this.comObj := ComValue(VT_UNKNOWN := 0xD, ptr)
        this.ptr := this.comObj.ptr
    }
}
class WrtString
{
    __New(stringOrHandle) {
        if Type(stringOrHandle) = 'Integer'
            this.ptr := stringOrHandle
        else {
            DllCall('Combase\WindowsCreateString', 'Str', stringOrHandle, 'UInt', StrLen(stringOrHandle), 'PtrP', &HSTRING := 0)
            this.ptr := HSTRING
        }
    }
    __Delete() => DllCall('Combase\WindowsDeleteString', 'Ptr', this)
    GetText() => DllCall('Combase\WindowsGetStringRawBuffer', 'Ptr', this, 'Ptr', 0, 'Str')
    
    GetFactory(riid) {
        hr := DllCall('Combase\RoGetActivationFactory', 'Ptr', this, 'Ptr', riid, 'PtrP', &pInterface := 0)
        if (hr != 0)
            throw OSError(WrtString.SysError(hr), A_ThisFunc)
        return pInterface
    }
    static SysError(nError := '') {
        static flags := (FORMAT_MESSAGE_ALLOCATE_BUFFER := 0x100) | (FORMAT_MESSAGE_FROM_SYSTEM := 0x1000)
        (nError = '' && nError := A_LastError)
        DllCall('FormatMessage', 'UInt', flags, 'UInt', 0, 'UInt', nError, 'UInt', 0, 'PtrP', &pBuf := 0, 'UInt', 128)
        err := (str := StrGet(pBuf)) = '' ? nError : str
        DllCall('LocalFree', 'Ptr', pBuf)
        return err
    }
} 
;=====================================================================


Return to “Pedir Ayuda”

Who is online

Users browsing this forum: No registered users and 13 guests