I asked this question yesterday
and I thought I received a solution, but I did not.
I ran the code on my laptop that had an external monitor attached. When I ran the code, the PrimaryDevice (my laptop screen) showed a DeviceID of 1. When the lid was closed, it showed an DID of 0.
I thought this was perfect. But, it turns out that when I removed the external monitor, the DeviceID stays 5 and persists no matter the state of the monitor.
I tried this on 5 notebooks. All had the same info. No information changed and this has become very frustrating. So I'm hoping someone can can help me come up with a solution. I've attached the code I'm using.