Perform an action when a specific USB device is attached?

Just starting out? Need help? Post your questions and find answers here.
Mistrel
Addict
Addict
Posts: 3415
Joined: Sat Jun 30, 2007 8:04 pm

Perform an action when a specific USB device is attached?

Post by Mistrel »

I have a friend who just got a USB headset. The problem he is having is that every time he plugs it in, he has to manually change the default sound device in Windows to it before he can hear sound.

Does anyone know a way to either detect what a specific USB device is attached or to enumerate the attached devices in a loop so that I can change this setting for him automatically?
TassyJim
Enthusiast
Enthusiast
Posts: 186
Joined: Sun Jun 16, 2013 6:27 am
Location: Tasmania (Australia)

Re: Perform an action when a specific USB device is attached

Post by TassyJim »

I forget who posted it originally but I use this to detect serial port changes:

Code: Select all

;GENERAL PROCEDURES

#WM_DEVICECHANGE=$219
#DBT_DEVICEARRIVAL=$8000 ; A device has been inserted
#DBT_DEVICEQUERYREMOVE=$8001 ; Permission is requested to remove a device or piece of media.
#DBT_DEVICEQUERYREMOVEFAILED=$8002 ; A request to remove a device or piece of media has been canceled.
#DBT_DEVICEREMOVEPENDING=$8003 ; A device or piece of media is about to be removed. Cannot be denied.
#DBT_DEVICEREMOVECOMPLETE=$8004; A device has been removed.
#DBT_DEVICETYPESPECIFIC=$8005  ; A device-specific event has occurred.
#DBT_DEVNODES_CHANGED=$0007    ; A device has been added to or removed from the system.
#DBT_QUERYCHANGECONFIG=$0017   ; Permission is requested to change the current configuration (dock or undock).
#DBT_USERDEFINED=$FFFF ; The meaning of this message is user-defined.
#DBT_DEVTYP_DEVICEINTERFACE = 5
#DBT_DEVTYP_HANDLE = 6
#DBT_DEVTYP_OEM = 0
#DBT_DEVTYP_PORT = 3
#DBT_DEVTYP_VOLUME = 2
#DBTF_MEDIA = 1
#DBTF_NET = 2

Procedure GetDeviceEvent(WindowID,Message,wParam,lParam)
   ;Callback procedure to catch a removable device event
   Protected ValidEvent = #False
   result = #PB_ProcessPureBasicEvents
   If Message=#WM_DEVICECHANGE
      result = #True
      Select wParam
         Case #DBT_DEVICEARRIVAL
            AddGadgetItem(5, -1,"WM_DEVICECHANGE "+"DBT_DEVICEARRIVAL")
            ValidEvent = #True
         Case #DBT_DEVICEREMOVECOMPLETE
            AddGadgetItem(5, -1,"WM_DEVICECHANGE "+"DBT_DEVICEREMOVECOMPLETE")
            ValidEvent = #True
            Default
            AddGadgetItem(5, -1,"WM_DEVICECHANGE "+StrU(wParam))
      EndSelect
      If ValidEvent = #True
         *pDBHDR.DEV_BROADCAST_HDR=lParam
         Select *pDBHDR\dbch_devicetype
            Case #DBT_DEVTYP_OEM
               *pDBO.DEV_BROADCAST_OEM=lParam
               oemID = *pDBO\dbco_identifier
               AddGadgetItem(5, -1,"Device Change Info "+"dbco_identifier: " + Str(oemID))
            Case #DBT_DEVTYP_PORT
               *pDBP.DEV_BROADCAST_PORT=lParam
               portName$ = PeekS(*pDBP + OffsetOf(DEV_BROADCAST_PORT\dbcp_name))
               AddGadgetItem(5, -1,"Device Change Info "+"dbcp_name : " + portName$)
            Case #DBT_DEVTYP_VOLUME
               *pDBV.DEV_BROADCAST_VOLUME=lParam
               Select *pDBV\dbcv_flags
                  Case #DBTF_MEDIA
                     AddGadgetItem(5, -1,"Device Change Info "+"DBTF_MEDIA")
                  Case #DBTF_NET
                     AddGadgetItem(5, -1,"Device Change Info "+"DBTF_NET")
               EndSelect
            Case #DBT_DEVTYP_DEVICEINTERFACE
               AddGadgetItem(5, -1,"Device Change Info "+"#DBT_DEVTYP_DEVICEINTERFACE")
            Case #DBT_DEVTYP_HANDLE
               AddGadgetItem(5, -1,"Device Change Info "+"#DBT_DEVTYP_HANDLE")
         EndSelect
       EndIf
        SendMessage_(GadgetID(5), #EM_SETSEL, -1, -1)
   EndIf
   ProcedureReturn result 
EndProcedure


;MAIN WINDOW AND CONTROLS
;Main window flags
Flags=#PB_Window_SystemMenu|#PB_Window_ScreenCentered
Flags=Flags|#PB_Window_MinimizeGadget|#PB_Window_MaximizeGadget


;Open the main window
If OpenWindow(0,0,0,600,400,"Removable device test",Flags)
   EditorGadget(5, 8, 8, 500, 350)
EndIf


;Set the callback to catch a removable device event
SetWindowCallback(@GetDeviceEvent())


;MAIN WINDOW EVENT LOOP
Repeat
   event=WaitWindowEvent()
   Select event
      Case #PB_Event_CloseWindow
         ;Program closed
         Exit=1
   EndSelect
Until Exit
Jim
jak64
Enthusiast
Enthusiast
Posts: 625
Joined: Sat Aug 15, 2020 5:02 pm
Location: Ciboure (France)

Re: Perform an action when a specific USB device is attached?

Post by jak64 »

Hello,
Thank you for your response, but I may have expressed myself incorrectly:

On my external disk, I have a program (.exe) which displays all the films contained on this same disk.

This external disk can be lent to a friend so that he can play the movies on his computer, without installing or running anything on his computer.

I would like, when he connects the external disk to his computer, that the program I wrote and which is on this disk, runs automatically without installing anything on his computer (a kind of boot on this disk).
User avatar
Kwai chang caine
Always Here
Always Here
Posts: 5494
Joined: Sun Nov 05, 2006 11:42 pm
Location: Lyon - France

Re: Perform an action when a specific USB device is attached?

Post by Kwai chang caine »

Works nice TASSYJIM, thanks for sharing 8)
ImageThe happiness is a road...
Not a destination
ZX80
Enthusiast
Enthusiast
Posts: 365
Joined: Mon Dec 12, 2016 1:37 pm

Re: Perform an action when a specific USB device is attached?

Post by ZX80 »

Hi, jak64

Have you already resolved the issue or not yet :?:
jak64
Enthusiast
Enthusiast
Posts: 625
Joined: Sat Aug 15, 2020 5:02 pm
Location: Ciboure (France)

Re: Perform an action when a specific USB device is attached?

Post by jak64 »

Hi,
No, but eventually, I will ask my friend to run the program annually by double clicking on it.
ZX80
Enthusiast
Enthusiast
Posts: 365
Joined: Mon Dec 12, 2016 1:37 pm

Re: Perform an action when a specific USB device is attached?

Post by ZX80 »

Hello, jak64.

I really wanted to help you, but...
I still don't like how it works (about my version), so for now without code. No, of course there is some result. But it's not exactly what I wanted. It's still not cleaned up here, so I can't say for sure if there will be a publication. There are nuances associated with assigning drive letters. If your target in the system had the letter H, and then another disk occupied it, then the target disk will be remapped when reconnected. So you catch unnecessary events: turn off/turn on to change drive letter. The operating system will do this automatically(without asking you). Unfortunately, there is no separate event for this. I figured out how to get around this (to distinguish between letter reassignment and full eject events). Thinking out loud: might be worth checking the registry (another point/approach). Do not know.
There are some serious coders here (not me). Perhaps they can help you in that direction. Unfortunately I don't have enough experience for that yet.
Good luck!

P.S. I am also interested in this topic (with good intentions).
Marc56us
Addict
Addict
Posts: 1600
Joined: Sat Feb 08, 2014 3:26 pm

Re: Perform an action when a specific USB device is attached?

Post by Marc56us »

You cannot run autorun if the user has disabled it.
On the other hand, if you can intervene once on the PC, you can configure a task so that Windows launches a program when it detects the connection of a USB key. It is therefore Windows that will launch the program and not the autorun. (so can decide if this this the good program)
Indeed, the scheduler (taskschd.msc) can launch a program not only according to the time, but also according to a system event (it remains to be seen in the logs event (eventvwr) which event it is, search for something like upnp I think)
jak64
Enthusiast
Enthusiast
Posts: 625
Joined: Sat Aug 15, 2020 5:02 pm
Location: Ciboure (France)

Re: Perform an action when a specific USB device is attached?

Post by jak64 »

Thank you for your feedback.

I was looking for this, actually, it's to help a visually impaired little boy.

1) I put a lot of cartoons on an external drive.

2) I wrote a small program in PureBasic that will read the movie titles and display the list in large yellow characters on a black background. (I scan all drive letters from A:\ to J:\ to find cartoon directory)

I wanted this program to run automatically when the drive is plugged in.

What's unfortunate on Windows is that you can't put a very, very big icon on the desktop (I displayed large icons, set the resolution to 150% but I would have liked bigger still. ..).
AZJIO
Addict
Addict
Posts: 2175
Joined: Sun May 14, 2017 1:48 am

Re: Perform an action when a specific USB device is attached?

Post by AZJIO »

You need to use the code I gave, it's better than this as it can recognize all logical drives on the same physical drive that are currently connected. And the above code will just show you that the flash drive is connected and nothing else.
You need to make an installer for the program to install it in the "AppData\Roaming" folder (%AppData%) and register it in Startup, either in a folder or in the registry.
jak64
Enthusiast
Enthusiast
Posts: 625
Joined: Sat Aug 15, 2020 5:02 pm
Location: Ciboure (France)

Re: Perform an action when a specific USB device is attached?

Post by jak64 »

Thank You.
ZX80
Enthusiast
Enthusiast
Posts: 365
Joined: Mon Dec 12, 2016 1:37 pm

Re: Perform an action when a specific USB device is attached?

Post by ZX80 »

Hello, jak64.

If you are still interested in another version, then can you give me more information about your program?
Such as:
1. Location on the disk of your program (full path, including the name of the exefile). Hope your program name is always constant.
2. The text in the title of the main window and the class of the main window of your program (if it's possible).
I also need the following information from you regarding the disk where your program is located:
1. Usb storage type: FLASH or HDD

2. USB storage label (aka Volume name)
Check it in the drive properties window from "My Computer" or in the command line (see point 4)

3. FileSystem: FAT32 or NTFS (or some other).
Check it in the drive properties window from "My Computer"

4. Serial number of usb storage
8 letters and numbers, separated by the "-" symbol (four each).
Don't worry, it's not too big of a secret :)
I need from you the serial number not of the device as a whole, but only of a specific section.

Check it in the command line by selecting the desired drive and running the 'dir' command.
You will find it in the listing. The serial number is assigned To the drive when it is formatted.
Hope I didn't ask too much.
But this is the minimum by which I am going to separate the target disk from all the others. And yes, this is really necessary information. I wanted to add another check for the size of the disk, but I think that this is still superfluous (at least for now).

My code is still in testing...
Yes, I'm still working on it. I hope that tomorrow I will be able to devote more time to it. Today time is up :(
I wanted to write your data in the code so that you just have to run it and watch the reaction. Also I wanted to add some extra checks before running your program.
That's all.
ZX80
Enthusiast
Enthusiast
Posts: 365
Joined: Mon Dec 12, 2016 1:37 pm

Re: Perform an action when a specific USB device is attached?

Post by ZX80 »

Hello, Marc56us.

Thanks for your comment on this issue. I'm not arguing that what you said is not true. I just have my own perspective/point on this issue. Perhaps you will say that there are extra movements. But I have already talked about unnecessary events during reconnections (when changing the drive letter). At least that's how I see it. And we don't know in advance which disks will be in the system, do we?

With my code, I'm no longer interested in what settings the system autostart has.
jak64
Enthusiast
Enthusiast
Posts: 625
Joined: Sat Aug 15, 2020 5:02 pm
Location: Ciboure (France)

Re: Perform an action when a specific USB device is attached?

Post by jak64 »

Hello and thank you all for your help.

For ZX80 (an old memory, I knew this computer), I will collect the information and post it to you as soon as possible.
ZX80
Enthusiast
Enthusiast
Posts: 365
Joined: Mon Dec 12, 2016 1:37 pm

Re: Perform an action when a specific USB device is attached?

Post by ZX80 »

Hello, AZJIO.

If your comment is for me, then thank you for it too. Sorry, but I have not looked at your code yet, as I was completely immersed in my development. And so far it suits me perfectly. I can only say that searching for a marker is not so reliable in my opinion. Sorry, but this is my opinion. Other partitions may contain copies of this program. Then you will get a false target when the other drive letter precedes the target drive letter. And as a result, not the action that jak64 originally wanted.
You start enumerating disks from A to Z every time, right?

P.S. Let's assume that the full paths of the program being launched differ only by a letter.
Post Reply