C#2019 获取鼠标所在位置的颜色无效!
同样原代码在C#2003 32位系统上能正常运行,生成执行文件后拷贝到win10/11 可正常获取到颜色。
问题同上,同样原代码在C# 2003 32位机上运行成功,但在64位2019下同样代码却不生效。所取出来的RGB值均为255.
```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
//可以得到鼠标位置,但是不能获取颜色
namespace getcolor
{
public partial class Form1 : Form
{
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("gdi32.dll")]
private static extern int GetPixel(IntPtr hdc, Point p);
public static Color getColor(Point p)
{
// Point p = new Point(MousePosition.X, MousePosition.Y);//取置顶点坐标
IntPtr hdc = GetDC(new IntPtr(0));//取到设备场景(0就是全屏的设备场景)
int c = GetPixel(hdc, p);//取指定点颜色
int r = (c & 0xFF);//转换R
int g = (c & 0xFF00) / 256;//转换G
int b = (c & 0xFF0000) / 65536;//转换B
// pictureBox1.BackColor = Color.FromArgb(r, g, b);
return Color.FromArgb(r, g, b);
}
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.BackColor = getColor(MousePosition);
}
}
}
```
你应该使用 Graphics.CopyFromScreen 方法获取屏幕像素而不是用过时的 gdi
c# 用的是 gdi+