我目前正在尝试检测中心屏幕像素的颜色变化。但不知怎的,它总会返回第一个变化。
我目前的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace pixelChange
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Color startingColor;
// Get center pixel color rbg once the form loaded
private void Form1_Load(object sender, EventArgs e)
{
startingColor = GetPixelColor(Screen.PrimaryScreen.Bounds.Width / 2, Screen.PrimaryScreen.Bounds.Height / 2);
}
// Timer which calls the GetPixelColor to check for a difference
private void timer1_Tick(object sender, EventArgs e)
{
checkForColorDifference(startingColor);
}
// Get pixel color function
public Color GetPixelColor(int x, int y)
{
Bitmap snapshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
using (Graphics gph = Graphics.FromImage(snapshot))
{
gph.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
}
return snapshot.GetPixel(x, y);
}
// Function to check if the color of the center pxiel changed
public void checkForColorDifference(Color start)
{
Color starting = start;
Color currentColor = GetPixelColor(Screen.PrimaryScreen.Bounds.Width / 2, Screen.PrimaryScreen.Bounds.Height / 2);
if (starting != currentColor)
{
MessageBox.Show("Color: " + start + " changed to:" + currentColor.ToString() + ".", "Color change response");
startingColor = currentColor;
}
}
}
}
到目前为止代码的工作原理:
但是代码总会返回相同的错误响应(第一个响应)。我做错了什么?
问题的屏幕截图:https://i.gyazo.com/0162e404a3ecef2820024e4f93678d2a.png
答案 0 :(得分:0)
我认为使用ToString()比较颜色是一个坏主意...显示this答案,知道如何正确地做到这一点:
你必须比较argb值。
答案 1 :(得分:0)
禁用计时器,直到您确认显示的消息框。代码将在MessageBox.Show()行中“停止”,直到您单击“确定”。因此,在单击“确定”之后才会设置新颜色。与此同时,由于相当神秘的winforms逻辑,计时器仍在运行。
public void checkForColorDifference(Color start)
{
Color starting = start;
Color currentColor = GetPixelColor(Screen.PrimaryScreen.Bounds.Width / 2, Screen.PrimaryScreen.Bounds.Height / 2);
if (starting != currentColor)
{
timer1.Enabled = false;
MessageBox.Show("Color: " + start + " changed to:" + currentColor.ToString() + ".", "Color change response");
startingColor = currentColor;
timer1.Enabled = true;
}
}
奖金修复,用于一次性位图:
public Color GetPixelColor(int x, int y)
{
using (Bitmap snapshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb))
using (Graphics gph = Graphics.FromImage(snapshot))
{
gph.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
return snapshot.GetPixel(x, y);
}
}