問題陳述:
確定捕獲特定顏色的方法屏幕像素並根據偵測到的觸發事件
解決方案:
最有效的技術是捕捉遊標位置的像素,確保跨多個顯示器的兼容性。
具體實現:
using System; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; using System.Windows.Forms; namespace ScreenPixelReader { public partial class Form1 : Form { [DllImport("user32.dll")] static extern bool GetCursorPos(ref Point lpPoint); [DllImport("gdi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] public static extern int BitBlt(IntPtr hDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop); public Form1() { InitializeComponent(); } private void MouseMoveTimer_Tick(object sender, EventArgs e) { Point cursor = new Point(); GetCursorPos(ref cursor); var c = GetColorAt(cursor); this.BackColor = c; if (c.R == c.G && c.G < 64 && c.B > 128) { MessageBox.Show("Blue"); } } Bitmap screenPixel = new Bitmap(1, 1, PixelFormat.Format32bppArgb); public Color GetColorAt(Point location) { // Create off-screen bitmaps for capturing screen pixels using (Graphics gdest = Graphics.FromImage(screenPixel)) using (Graphics gsrc = Graphics.FromHwnd(IntPtr.Zero)) { IntPtr hSrcDC = gsrc.GetHdc(); IntPtr hDC = gdest.GetHdc(); int retval = BitBlt(hDC, 0, 0, 1, 1, hSrcDC, location.X, location.Y, (int)CopyPixelOperation.SourceCopy); gdest.ReleaseHdc(); gsrc.ReleaseHdc(); } // Return the captured pixel color return screenPixel.GetPixel(0, 0); } } }
輪詢像素顏色變更:
要連續監視特定像素顏色,您可以在循環或執行緒中使用以下函數:
private void PollPixel(Point location, Color color) { while (true) { var c = GetColorAt(location); if (c.R == color.R && c.G == color.G && c.B == color.B) { DoAction(); return; } Thread.Sleep(); } }
結論:
這種方法可以實現準確的螢幕像素顏色檢測,並實現基於顏色的可靠事件觸發。
以上是如何偵測螢幕像素顏色變化並觸發事件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!