1

I have a vb.net question. How can a warning msgbox be shown when the USB serial/serial port is unplugged?

David Medinets
  • 5,160
  • 3
  • 29
  • 42
  • 1
    You can override a Form [WndProc](https://msdn.microsoft.com/en-us/library/system.windows.forms.form.wndproc%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396). When the Message (`m.Msg`) is `WM_DEVICECHANGE = &H219`, see if `m.WParam` is `DBT_DEVICEARRIVAL = &H8000` or `DBT_DEVICEREMOVECOMPLETE = &H8004`. You can then extract from `m.LParam` (`Marshal.ReadInt32(m.LParam, 4)`) the type of device. e.g. a Flash Drive will be `DBT_DEVTYP_VOLUME = &H2`. Some Google search on these keywords, will return some useful information. – Jimi Jul 13 '18 at 03:21
  • I changed the title and description to be more concise. – David Medinets Jul 13 '18 at 03:46
  • This sort of project is a real, real hassle. Check out my related question here: https://stackoverflow.com/a/8003897/362536 – Brad Jul 13 '18 at 03:53
  • Forgot to mention that you probably have to disable AutoPlay. You need [RegisterWindowMessage](https://msdn.microsoft.com/en-us/library/windows/desktop/ms644947%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396) for this (`Dim MessageID as Integer = RegisterWindowMessage("QueryCancelAutoPlay")`) (in `Form.New()`, possibly). Then, in your `WndProc`, you have to acknowledge the registration, returning `m.Result = New IntPtr(1)` when you receive your `MessageID`. If you don't get any answers in the meanwhile (and the question is not closed), tomorrow I will post something. – Jimi Jul 13 '18 at 05:07
  • It is pretty much automatic, your program is quite likely to crash when you unplug the cable. Commonly in an internal thread that generates the events, you cannot put try/catch around it. This happens before you could ever put up a message box. Serial ports do not support plug & play, you must always use the "Safely remove hardware" tray icon. Not something users are ever likely to do, but they'll stop messing with the cable when they find out what happens next. – Hans Passant Jul 13 '18 at 08:35

0 Answers0