System.Windows.Forms.Screen.DeviceName gives garbage in Windows XP

My .NET Framework program handles multiple monitors, so I use Screen.DeviceName to distinguish between different monitors (do not just compare links to instances of the Screen object - different instances can refer to the same screen).

The program does not work on Windows 7, but on Windows XP Service Pack 3 (SP3) with all the .NET frameworks installed, it will randomly do strange things, as if it did not understand that the two screens indicated are actually the same screen. must be able to recognize, because they must have identical DeviceName s.

What is the problem and how to fix it?

+8
c # screen windows-xp winforms
source share
1 answer

It seems that the error is present in the framework or in Windows XP.

If you Screen.DeviceName under Windows 7, you will get something like

  \\. \ DISPLAY1
 \\. \ DISPLAY2 

But if you do the same in Windows XP, you will get something like

  \\. \ DISPLAY1 ???? A ?? M? ↕? ☺?
 \\. \ DISPLAY2 ???? ☺?  ☺ ????? 

Obviously, Microsoft was aware of the error, so they added a note to:

This string may contain non-printable characters.

And that would be great if the printable characters were not the same every time.
But they are not , because in fact it is garbage, the contents of random memory that comes after the terminating null character.

If you create only one cached instance of the Screen object and call its DeviceName property several times, the garbage will be the same because the Screen object caches the name on its own. But if you create a new instance of the Screen object for each request, then the garbage will probably be different for these instances, even if they refer to the same device:

 System.Windows.Forms.Screen s = null; System.Drawing.Point p = new System.Drawing.Point(0,0); Console.WriteLine("Using same instance of Screen:"); s = System.Windows.Forms.Screen.FromPoint(p); for (int i = 0; i < 5; ++i) { Console.WriteLine(s.DeviceName); } Console.WriteLine(); Console.WriteLine("Using new instance of Screen:"); for (int i = 0; i < 5; ++i) { Console.WriteLine(System.Windows.Forms.Screen.FromPoint(p).DeviceName); } 

If you run this snippet on Windows XP, you will get something like:

enter image description here

Please note that here you have at least three versions of DeviceName .

In Windows 7, in contrast, part of the garbage will be deleted.

That's why the code does not recognize screens - device names are different every time.

To fix this, DeviceName string after the first character '\0' .

+13
source share

All Articles