gpt4 book ai didi

c# - System.Windows.Forms.Screen.DeviceName 在 Windows XP 上产生垃圾

转载 作者:太空狗 更新时间:2023-10-29 18:18:48 24 4
gpt4 key购买 nike

我的 3.5 .NET Framework 程序处理多个显示器,所以我使用 Screen.DeviceName区分不同的监视器(不能只比较对 Screen 对象实例的引用——不同的实例可以引用同一个屏幕)。

该程序在 Windows 7 上运行没有问题,但在安装了所有 .NET 框架的 Windows XP SP3 上它会随机做一些奇怪的事情,就好像它没有意识到给定的两个屏幕实际上是同一个屏幕,它应该能够识别,因为它们应该具有相同的 DeviceName

问题是什么,我该如何解决?

最佳答案

框架或 Windows XP 中似乎存在错误。

如果你在 Windows 7 下转储 Screen.DeviceName,你会得到类似的东西

\\.\DISPLAY1\\.\DISPLAY2

但是如果你在 Windows XP 上做同样的事情,你会得到类似的东西

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

显然微软已经意识到这个错误,所以他们在 documentation 中添加了注释:

This string may contain non-printable characters.

如果非打印字符每次都相同,那就完全没问题了。
但它们不是,因为实际上,它们是垃圾,在终止空字符之后的随机内存内容。

如果您只创建 Screen 对象的一个​​缓存实例并多次调用其 DeviceName 属性,则每次垃圾都会相同,因为 Screen 对象将名称缓存在自身中。但是如果您为每个请求创建一个新的 Screen 对象实例,那么这些实例的垃圾很可能是不同的,即使它们指的是同一个设备:

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);
}

如果您在 Windows XP 上运行此代码段,您将得到如下内容:

enter image description here

请注意您如何在此处拥有至少三个版本的 DeviceName

相反,在 Windows 7 上,垃圾部分将被剥离。

这就是代码无法识别屏幕的原因——每次设备名称都不同。

要解决此问题,请在第一个 '\0' 字符后裁剪 DeviceName 字符串。

关于c# - System.Windows.Forms.Screen.DeviceName 在 Windows XP 上产生垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12319903/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com