Determine color of a pixel in a winforms application

前端 未结 3 1674
说谎
说谎 2021-01-06 15:16

I\'d like to be able to determine the backgroundcolor of a winform at a certain point on the screen, so I can take some action depending on that particular color. Sadly the

3条回答
  •  无人及你
    2021-01-06 15:56

    Assuming you want to stay away from the Win32 API, you can use Graphics.CopyFromScreen() to draw the content of your screen to a Bitmap object. From there, you just need to use Bitmap.GetPixel() to retrieve a Color object with the right color.

    Here's some code you can use to retrieve the complete desktop (works with multiple monitors):

    public Image GetScreenshot()
    {
        int screenWidth = Convert.ToInt32(System.Windows.SystemParameters.VirtualScreenWidth);
        int screenHeight = Convert.ToInt32(SystemParameters.VirtualScreenHeight);
        int screenLeft = Convert.ToInt32(SystemParameters.VirtualScreenLeft);
        int screenTop = Convert.ToInt32(SystemParameters.VirtualScreenTop);
    
        Image imgScreen = new Bitmap(screenWidth, screenHeight);
        using (Bitmap bmp = new Bitmap(screenWidth, screenHeight, PixelFormat.Format32bppArgb))
        using (Graphics g = Graphics.FromImage(bmp))
        using (Graphics gr = Graphics.FromImage(imgScreen))
        {
            g.CopyFromScreen(screenLeft, screenTop, 0, 0, new Size(screenWidth, screenHeight));
            gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            gr.DrawImage(bmp, new Rectangle(0, 0, screenWidth, screenHeight));
        }
    
        return imgScreen;
    }
    

提交回复
热议问题