c# - 尝试使用位图捕获屏幕

c# - Trying to capture screen using bitmap

我在 visual studio 2019 年使用 windows Forms 应用程序。除此之外从未真正使用过 c#,但我正在尝试在鼠标坐标中显示像素的颜色。 然而,rgb 始终等于 0。

public static Point GetMousePositionWindowsForms()
{
    System.Drawing.Point point = Control.MousePosition;
    return new Point(point.X, point.Y);
}

public static string Getcolor()
{
    Bitmap screen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
    Color getcolor = screen.GetPixel(GetMousePositionWindowsForms().X-1, GetMousePositionWindowsForms().Y-1);
    return Convert.ToString(getcolor);
}

您必须在获取颜色之前捕获屏幕。试试这个:

public static string Getcolor()
{
    Bitmap screen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
    Graphics captureGraphics = Graphics.FromImage(screen);
    captureGraphics.CopyFromScreen(0, 0, 0, 0, new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height));
    Color getcolor = screen.GetPixel(GetMousePositionWindowsForms().X-1, GetMousePositionWindowsForms().Y-1);
    return Convert.ToString(getcolor);
}