welsonjs/WelsonJS.Toolkit/WelsonJS.Service/ScreenMatching.cs

321 lines
9.3 KiB
C#
Raw Normal View History

2024-08-12 03:47:19 +00:00
// ScreenMatching.cs
// https://github.com/gnh1201/welsonjs
using System;
2024-07-29 12:43:14 +00:00
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.ServiceProcess;
2024-07-29 12:43:14 +00:00
using System.Text;
using System.Windows.Forms;
using WelsonJS.Service;
public class ScreenMatching
{
// User32.dll API 함수 선언
[DllImport("user32.dll")]
2024-08-13 02:21:48 +00:00
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
2024-07-29 12:43:14 +00:00
[DllImport("user32.dll")]
2024-08-13 02:21:48 +00:00
private static extern bool IsWindowVisible(IntPtr hWnd);
2024-07-29 12:43:14 +00:00
[DllImport("user32.dll")]
2024-08-13 02:21:48 +00:00
private static extern int GetWindowRect(IntPtr hWnd, out RECT lpRect);
2024-07-29 12:43:14 +00:00
[DllImport("user32.dll")]
2024-08-13 02:21:48 +00:00
private static extern IntPtr GetDC(IntPtr hWnd);
2024-07-29 12:43:14 +00:00
[DllImport("user32.dll")]
2024-08-13 02:21:48 +00:00
private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
2024-07-29 12:43:14 +00:00
[DllImport("user32.dll")]
2024-08-13 02:21:48 +00:00
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
2024-07-29 12:43:14 +00:00
[DllImport("user32.dll")]
2024-08-13 02:21:48 +00:00
private static extern int GetWindowTextLength(IntPtr hWnd);
2024-07-29 12:43:14 +00:00
[DllImport("gdi32.dll")]
private static extern bool BitBlt(IntPtr hDestDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);
2024-08-13 02:21:48 +00:00
2024-07-29 12:43:14 +00:00
private const int SRCCOPY = 0x00CC0020;
// 델리게이트 선언
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
// RECT 구조체 선언
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
private ServiceMain parent;
2024-08-12 03:47:19 +00:00
private List<Bitmap> templateImages;
2024-08-12 12:05:17 +00:00
private string templateDirectoryPath;
private int templateCurrentIndex = 0;
2024-08-24 05:57:01 +00:00
private double threshold = 0.4;
private string mode;
private string[] _params;
2024-07-29 12:43:14 +00:00
2024-08-12 03:47:19 +00:00
public ScreenMatching(ServiceBase parent, string workingDirectory)
2024-07-29 12:43:14 +00:00
{
2024-08-12 03:47:19 +00:00
this.parent = (ServiceMain)parent;
2024-08-12 12:05:17 +00:00
templateDirectoryPath = Path.Combine(workingDirectory, "app/assets/img/_templates");
2024-08-12 04:00:04 +00:00
templateImages = new List<Bitmap>();
2024-08-24 05:57:01 +00:00
// Read values from configration file
string mode;
string _params;
try
{
mode = this.parent.GetSettingsFileHandler().Read("SCREEN_TIME_MODE", "Service");
_params = this.parent.GetSettingsFileHandler().Read("SCREEN_TIME_PARAMS", "Service");
}
catch (Exception ex)
{
this.parent.Log($"Failed to read from configration file: {ex.Message}");
}
SetMode(mode);
SetParams(_params);
2024-07-29 12:43:14 +00:00
LoadTemplateImages();
}
2024-08-24 04:44:48 +00:00
public void SetMode(string mode)
{
2024-08-24 05:57:01 +00:00
if (!String.IsNullOrEmpty(mode))
{
this.mode = mode;
}
else
{
this.mode = "screen";
}
}
public void SetParams(string[] _params)
{
if (!String.IsNullOrEmpty(mode))
{
this._params = _params;
}
else
{
this._params = null;
}
2024-08-24 04:44:48 +00:00
}
public void SetThreshold(double threshold)
{
this.threshold = threshold;
}
2024-07-29 12:43:14 +00:00
public void LoadTemplateImages()
{
2024-08-24 06:40:15 +00:00
string[] files;
2024-08-12 04:00:04 +00:00
try
{
2024-08-12 12:05:17 +00:00
files = Directory.GetFiles(templateDirectoryPath, "*.png");
2024-08-12 04:00:04 +00:00
}
catch (Exception ex)
{
2024-08-24 06:40:15 +00:00
files = new string[]{};
2024-08-24 04:44:48 +00:00
parent.Log($"Failed to read the directory structure: {ex.Message}");
2024-08-12 04:00:04 +00:00
}
2024-07-29 12:43:14 +00:00
foreach (var file in files)
{
2024-08-24 04:44:48 +00:00
Bitmap bitmap = new Bitmap(file)
{
Tag = Path.GetFileName(file)
};
2024-07-29 12:43:14 +00:00
templateImages.Add(bitmap);
}
}
// 캡쳐 및 템플릿 매칭 진행
public List<ScreenMatchResult> CaptureAndMatch()
{
2024-08-24 04:44:48 +00:00
switch (mode)
{
case "screen": // 화면 기준
return CaptureAndMatchAllScreens();
2024-08-24 04:44:48 +00:00
case "window": // 윈도우 핸들 기준
return CaptureAndMatchAllWindows();
2024-08-24 04:44:48 +00:00
default:
break;
}
return new List<ScreenMatchResult>();
}
2024-07-29 12:43:14 +00:00
// 화면을 기준으로 찾기
public List<ScreenMatchResult> CaptureAndMatchAllScreens()
{
var results = new List<ScreenMatchResult>();
for (int i = 0; i < Screen.AllScreens.Length; i++)
{
Screen screen = Screen.AllScreens[i];
Bitmap mainImage = CaptureScreen(screen);
2024-08-12 12:05:17 +00:00
Bitmap image = templateImages[templateCurrentIndex];
2024-08-02 07:53:33 +00:00
parent.Log($"Trying match the template {image.Tag as string} on the screen {i}...");
2024-07-29 12:43:14 +00:00
Point matchLocation = FindTemplate(mainImage, (Bitmap)image.Clone(), out double maxCorrelation);
results.Add(new ScreenMatchResult
{
FileName = image.Tag.ToString(),
ScreenNumber = i,
Location = matchLocation,
MaxCorrelation = maxCorrelation
});
2024-07-29 12:43:14 +00:00
}
2024-08-12 12:05:17 +00:00
templateCurrentIndex = ++templateCurrentIndex % templateImages.Count;
2024-07-29 12:43:14 +00:00
return results;
}
public static Bitmap CaptureScreen(Screen screen)
{
Rectangle screenSize = screen.Bounds;
Bitmap bitmap = new Bitmap(screenSize.Width, screenSize.Height);
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(screenSize.Left, screenSize.Top, 0, 0, screenSize.Size);
}
return bitmap;
}
// 윈도우 핸들을 기준으로 찾기
public List<ScreenMatchResult> CaptureAndMatchAllWindows()
{
var results = new List<ScreenMatchResult>();
// 모든 윈도우 핸들을 열거
EnumWindows((hWnd, lParam) =>
{
if (IsWindowVisible(hWnd))
{
try
{
string windowTitle = GetWindowTitle(hWnd);
Bitmap windowImage = CaptureWindow(hWnd);
if (windowImage != null)
{
2024-08-12 12:05:17 +00:00
Bitmap image = templateImages[templateCurrentIndex];
Point matchLocation = FindTemplate(windowImage, image, out double maxCorrelation);
string templateFileName = image.Tag as string;
var result = new ScreenMatchResult
2024-07-29 12:43:14 +00:00
{
FileName = templateFileName,
WindowHandle = hWnd,
WindowTitle = windowTitle,
Location = matchLocation,
MaxCorrelation = maxCorrelation
};
results.Add(result);
2024-07-29 12:43:14 +00:00
}
}
catch { }
}
return true;
}, IntPtr.Zero);
2024-08-12 12:05:17 +00:00
templateCurrentIndex = ++templateCurrentIndex % templateImages.Count;
2024-07-29 12:43:14 +00:00
return results;
}
public string GetWindowTitle(IntPtr hWnd)
{
int length = GetWindowTextLength(hWnd);
StringBuilder sb = new StringBuilder(length + 1);
GetWindowText(hWnd, sb, sb.Capacity);
return sb.ToString();
}
public Bitmap CaptureWindow(IntPtr hWnd)
{
GetWindowRect(hWnd, out RECT rect);
int width = rect.Right - rect.Left;
int height = rect.Bottom - rect.Top;
if (width <= 0 || height <= 0)
return null;
Bitmap bitmap = new Bitmap(width, height);
Graphics graphics = Graphics.FromImage(bitmap);
IntPtr hDC = graphics.GetHdc();
IntPtr windowDC = GetDC(hWnd);
bool success = BitBlt(hDC, 0, 0, width, height, windowDC, 0, 0, SRCCOPY);
ReleaseDC(hWnd, windowDC);
graphics.ReleaseHdc(hDC);
return success ? bitmap : null;
}
public Point FindTemplate(Bitmap mainImage, Bitmap templateImage, out double maxCorrelation)
{
int mainWidth = mainImage.Width;
int mainHeight = mainImage.Height;
int templateWidth = templateImage.Width;
int templateHeight = templateImage.Height;
Point bestMatch = Point.Empty;
maxCorrelation = 0;
for (int x = 0; x <= mainWidth - templateWidth; x++)
{
for (int y = 0; y <= mainHeight - templateHeight; y++)
{
2024-08-12 12:05:17 +00:00
if (IsTemplateMatch(mainImage, templateImage, x, y, threshold))
2024-07-29 12:43:14 +00:00
{
bestMatch = new Point(x, y);
2024-08-24 04:44:48 +00:00
maxCorrelation = 1.0;
2024-07-29 12:43:14 +00:00
return bestMatch;
}
}
}
return bestMatch;
}
2024-08-12 12:05:17 +00:00
private bool IsTemplateMatch(Bitmap mainImage, Bitmap templateImage, int offsetX, int offsetY, double threshold)
2024-07-29 12:43:14 +00:00
{
int templateWidth = templateImage.Width;
int templateHeight = templateImage.Height;
int totalPixels = templateWidth * templateHeight;
int requiredMatches = (int)(totalPixels * threshold);
int matchedCount = 0;
Random rand = new Random();
2024-07-29 12:43:14 +00:00
while (matchedCount < requiredMatches)
2024-07-29 12:43:14 +00:00
{
int x = rand.Next(templateWidth);
int y = rand.Next(templateHeight);
Point point = new Point(x, y);
if (mainImage.GetPixel(x + offsetX, y + offsetY) != templateImage.GetPixel(x, y))
2024-07-29 12:43:14 +00:00
{
return false;
2024-07-29 12:43:14 +00:00
}
matchedCount++;
2024-07-29 12:43:14 +00:00
}
return true;
}
}