Posted on

Fighting Floods and Untangling USB Mayhem

Flooding USB Bald Banner

I’m sitting here looking at the time on my computer.   1:13AM.  A late night and I got almost NOTHING done when it comes to the code and projects I wanted to wrap up today.  Why?   Well a lot of things.

Flood Fighting…

First the flood.   Even though the main event was a week ago, I have been continually side-tracked every day since.   You’d think a minor amount of water damage wouldn’t be so disruptive but damned if it hasn’t consumed at least 20+ hours out of my past 6 days.    Today was mostly spent on the phone with contractors to get quotes on fixing the damage so I can go back and battle the insurance company and their ludicrously low quotes.   That meant hours of conversations followed by hours of on-site visits all just so I can spend hours arguing with the insurance company about how impossible it is to get the job done less than half the rate any competent contractor has quoted.

If only the insurance adjusters were required to take the discrepancies out of their salaries.    Even better,  take the average of 3 competitive quotes submitted in a blind bid.  Lowest contractor wins the job BUT the price difference between what the insurance company put on the quote and the real cost of the job is DOUBLED and paid to the contractor (or homeowner).    I guarantee the $10k “estimates” and ensuing check the insurance company offers for a $25k job would stop in a hurry!


Untangling USB

To add some excitement, the flood problems gave way to some complex technical issues to deal with.    I decided tonight was as good a night as any to  learn a TON of stuff about USB ports and protocols.    Stuff that I don’t think will EVER relate to WordPress plugin programming.   At least I hope  not.

Why did I take this side diversion into USB protocols?   Because my mouse would not work at the same time as my keyboard.    That REALLY makes it difficult to program.    The odd part is it WAS working just fine before I plugged my phone into my computer.   Which I’ve done a million times before.

Turns out it happened to be a perfect timing issue that triggered a latent problem in the USB hubs on my computer.     My 3 new HPZR2440W monitors (which I LOVE for coding & surfing BTW) have 4-port USB2 hubs.  That is great as it really reduced the clutter on my desk.    What is NOT great is that the entire USB stack turns out to be a lot less stable than we’d all like to believe.    Very cool stuff if anyone remembers the old serial port days and having to disconnect devices any time you wanted to do anything.    But it turns out some people thought that USB2 sucked.

In a way it kind of does, only because it is very slow compared to some things like Firewire or other high-speed communication ports.    USB wanted to compete with the new shiny high-speed Apple protocols.     So they came out with USB3.      WAY faster.    Same physical ports as USB2 other than the blue color.  And FULLY backward compatible with USB2.

Turns out that last part… it’s a bold-faced lie.    Sure it works MOST of the time.  Well, OK, SOME of the time.   But in the real world it is not always compatible with USB2.

I already knew this from the days of trying to code Android apps.    Turns out a LOT of Android phones simply will not work when in developer mode and trying to communicate with a PC.     Plug the phone into a USB3 port and all hell breaks loose.     The sucky part is that SOMETIMES it works.     Often it does not.    For those of you that do ANY kind of programming you know that inconsistent, especially inexplicably inconsistent, results are the worst.    It is far easier to deal with something that fails all-the-time or at least after a predictable series of steps than something completely random.

For the non-coders, a simple analogy:

Imagine you are typing an email at your computer.   Every-so-often, at random times, someone wanders by your cube (or your couch, or wherever you sit when typing) and hits a few random keys on your keyboard.  While you are typing.    And it happens a half-dozen times while writing one short email.     That would drive most people insane.   By the 5th visit you’d probably stab that person in the hand with whatever semi-sharp instrument you could find.

That is much like what my night was like tonight.    As it turns out the USB2 hubs in the HP monitors DO NOT work on USB3 ports like in my HP laptop.    The bad part is they work SOMETIMES.    Then just “freak the hell out”.     Even worse than that, somehow the extra load of the cell phone in conjunction with who-knows-what… the phase of the moon maybe… made the problem far worse tonight than ever before.   Because I have been using this same setup for a month now with no problems I went down a LOT of other paths before I found the right solution.

Install the latest windows upgrades?  Check!

Get pissed off because they installed some new crappy apps I didn’t want (what the hell is this new SkyDrive thing anyway)?  Check!

Uninstall the crappy new apps that slow down my computer. Check!

Unplug the phone.   Check for un-confirmed firmware updates or other updates.  Yup.  Did that too.

Swap the mouse in case the cord was pinched or otherwise mangled.  Sure.  Didn’t help.

Swap the keyboard.  Again, no help.

Start unplugging every device until I was back to the bare-bones laptop.  Yup.   Start plugging everything  back in.  Sure.   Stuff freaks out again as soon as I plug in the last device.  Uh-huh.     Only this time the last devices was  a printer!  WTF!

You can literally hear the last few follicles of hair LEAPING from my head at this very moment, can’t you?

USB Conquered

At the end of 3 hours of “scratching my bald head” (normally I’d be tearing my hair out… but that hair was gone many tech dilemma’s ago) I finally found the solution.   Just 12 hours away from having the HP on-site repair tech at my door (yeah, I had HP support online as well).    For those of you going insane with random problems with your HP ZR2440W USB devices or a Logitech Illuminated keyboard, here are some short rules that will hopefully keep more hair on your head than a polished bowling-ball:

1) HPZR2440W monitors ONLY work 100% of the time when connected to a USB2 port.    Avoid USB3 on the host machine as your primary connection.

2) HPZR2440W monitors cannot daisy chain beyond 1 monitor.   In other words you cannot go from PC to Monitor 1 then Monitor 1 out to Monitor 2 in then Monitor 2 in to Monitor 3 in.   Instead do a “Y” configuration with PC to Monitor 1, then Monitor 1 out to Monitor 2, and another Monitor 1 out to Monitor 3.

3) The Logitech Illuminated Keyboard, among many other illuminated keyboards, DO NOT WORK WITH MOST HUBS.    Yes, they work with SOME hubs but not all.   It has something to do with the way they register as TWO USB devices instead of one.   I’m guessing so they have enough power to do the background lighting on the keys but that is just a guess on my part.

4) If you happen to have a 3-monitor setup like I have, do NOT plug anything to the other ports on the first monitor.  The “base of the Y”.   The other 2 monitors will not always play nice with the USB devices attached to them.

At Least SLP 3.11.12 Shipped

Luckily Store Locator Plus 3.11.12 shipped before all this happened.  I did not finish the post on what was fixed in that release because of the USB fiasco. By the time I sorted it out I needed to vent, which is why THIS post is here first.      I did get something accomplished today in the 3 hours between insurance battles and computer battles.  Somehow, though, I feel I just got my butt kicked today as I approach hour number 18 and have less than 3 hours of work and a very small patch on Store Locator Plus to show for it.

Hopefully tomorrow will be better even though it starts out with 5 hours of non-code related meetings.

At least I shouldn’t have any “tweaking out keyboards and reluctant mice” to deal with when I get back in front of this evil machine of doom and despair.

Posted on

Detecting USB Insertion/Removal in C# .Net 4.0

We need your help!

Cyber Sprocket is looking to qualify for a small business grant so we can continue our development efforts. We are working on a custom application builder platform so you can build custom mobile apps for your business. If we reach our 250-person goal have a better chance of being selected.

It is free and takes less than 2 minutes!

Go to
Click on the “Login and Vote” button.
Put “Cyber Sprocket” in the search box and click search.
When our name comes up click on the vote button.


And now on to our article…

C# Programming


While coding a new Windows desktop app for a client we ran into something that we thought we be fairly simple.  It has turned out to be a rather complex task. The goal: detect when a SmartDongle USB key was being inserted or removed & update our application interface at that time.

Our assumption was that a few minutes of searching the Internet and we’d find a dozen examples of people that have done it already or we’d just use the .Net 4.0 classes for device detection. Wrong on both counts. As ubiquitous as USB devices are these days, it appears that .Net 4.0 still does not have direct support via easy-to-use classes that you can just hook into. Searches of the Internet turned up a lot more people asking questions than viable answers. The few answers we found were outdated or half-answers.

Now that we’ve got basic USB insertion/removal detection working we decided we’d share that part of the solution. Our next challenge is to determine that we’ve inserted the SmartDongle and not some other USB device such as a keyboard, mouse, flash drive, or other USB item. Unfortunately the message handler we’ve got thus far only tells us that a device has changed (windows message WM_DEVICECHANGED), but does not hand off the parameters that would let us query the message stack to find out WHICH device changed. That will be a solution for another post I guess.

Our Environment

We are coding in C# using Visual Studio 2010 (VS2010) with the .Net 4.0 framework helping us along. We are coding a WPF main window, not a form, which can make a difference.

Our Solution

Here is the simplified way to detect that a USB device was inserted or removed from the system, and our call to a ReadDongle method that we wrote to get information from the dongle header (or not, if it was removed). You can call whatever function you’d like, or put your processing loop right inside the windows process handler.

using System.Windows.Interop;
public partial class MainWindow : Window
    public MainWindow()


    private const int WM_DEVICECHANGE = 0x0219;  // int = 537
    private const int DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = 0x00000004; 

    /// <summary>
    /// </summary>
    /// <param name="e"></param>
    protected override void OnSourceInitialized(EventArgs e)
        HwndSource source = PresentationSource.FromVisual(this) as HwndSource;

    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        if (msg == WM_DEVICECHANGE)
        return IntPtr.Zero;



That’s it, now we know when a device is inserted or removed. We are overriding the OnSourceInitialized method for our main window, which basically is saying “hey, when the window is initialized and ready to accept external messages from the operating system, add a hook that latches onto the window’s message processing method (WndProc). We can then perform operations by sniffing out specific types of messages like “device changed” (WM_DEVICECHANGE) and doing our thing. When the WndProc override is done it drops back to the default method for further processing. We could override that by setting handled to true, but we don’t want to do that in our app… not yet anyway.

Hope our article helps provide a quick shortcut for someone that is googling stuff like “C# wpf usb insertion/removal”.