2012-12-21 31 views
0

我想写一个程序,点击它找到的具有特定颜色的第一个像素。不幸的是,似乎有时我的程序无法检测到屏幕上实际存在颜色。我正在截屏,然后使用GetPixel()方法查找每个像素的颜色。Color Clicker不准确

这里是我的方法,我用:

private static Point FindFirstColor(Color color) 
{ 
    int searchValue = color.ToArgb(); 
    Point location = Point.Empty; 

    using (Bitmap bmp = GetScreenShot()) 
    { 
     for (int x = 0; x < bmp.Width; x++) 
     { 
      for (int y = 0; y < bmp.Height; y++) 
      { 
       if (searchValue.Equals(bmp.GetPixel(x, y).ToArgb())) 
       { 
        location = new Point(x, y); 
       } 
      } 
     } 
    } 
    return location; 
} 

为了我的屏幕截图,我用:

private static Bitmap GetScreenShot() 
    { 
     Bitmap result = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb); 
     { 
      using (Graphics gfx = Graphics.FromImage(result)) 
      { 
       gfx.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); 
      } 
     } 
     return result; 
    } 

即使当我用一种颜色,我知道是在屏幕,它仍然返回Point.Empty。这是什么原因?

+1

可以请你提供什么样的'GetScreenShot()'究竟呢? :) –

+2

如果你需要第一个匹配的像素,为什么你没有摆脱循环后获得第一场比赛..? – Anujith

+0

我仍然有不准确的问题。当我运行它一次,它检测到的颜色;在其他时候,它不......我没有改变这些运行之间的任何代码。可能是什么问题呢? – user1594328

回答

1

刚刚复制你的方法,并用颜色找到Color.Black,它的工作没有任何问题。

当前在您的代码中可能不正确的唯一事情是您在找到第一个匹配点后不立即返回。相反,您只需继续遍历所有点,从而导致您将返回匹配颜色的最后一次出现。

为了避免这种情况,你可以改变你的代码:

private static Point FindFirstColor(Color color) 
{ 
    int searchValue = color.ToArgb(); 

    using (Bitmap bmp = GetScreenShot()) 
    { 
     for (int x = 0; x < bmp.Width; x++) 
     { 
      for (int y = 0; y < bmp.Height; y++) 
      { 
       if (searchValue.Equals(bmp.GetPixel(x, y).ToArgb())) 
       { 
        return new Point(x, y); 
       } 
      } 
     } 
    } 

    return Point.Empty; 
}