정리가 필요한 카테고리(추후 정리)/C#,Unity

WPF, 윈폼] 마우스 커서 위치에 있는 픽셀의 색상값(RGB) 구하는 방법

TwinParadox 2019. 2. 2. 19:23
728x90

필요에 의해서 특정 지점에서의 RGB값으로 구성된 색상값을 구하고 싶어서 간단한 유틸리티를 만드는데, 특정 지점에서의 색상값을 구하는 방법을 찾아봤다. MSDN이랑 스택오버플로우를 뒤져보니까 GetPixel이라는 해당 픽셀에서의 색상값을 구하는 윈도우 API가 있다.


[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetDesktopWindow();	
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetWindowDC(IntPtr window);
[DllImport("gdi32.dll", SetLastError = true)]
public static extern uint GetPixel(IntPtr dc, int x, int y);
[DllImport("user32.dll", SetLastError = true)]
public static extern int ReleaseDC(IntPtr window, IntPtr dc);

public void GetColorAt(Point cursor)
{
	int x = (int)cursor.X, y = (int)cursor.Y;
	IntPtr desk = GetDesktopWindow();
	IntPtr dc = GetWindowDC(desk);
	int a = (int)GetPixel(dc, x, y);
	ReleaseDC(desk, dc);
	ChangeColor(Color.FromArgb(255, (byte)((a >> 0) & 0xff), (byte)((a >> 8) & 0xff), (byte)((a >> 16) & 0xff)));
}



GetPixel(hdc,x,y) 함수는 COLORREF를 반환하는데, 이 COLORREF는 RGB 값을 0x00bbggrr형식으로 나타낸다.



Color.FromArgb(255, (byte)((a >> 0) & 0xff), (byte)((a >> 8) & 0xff), (byte)((a >> 16) & 0xff))



이 부분이 GetPixel 함수로부터 받은 COLORREF 값을 가공해서 Color 클래스의 인스턴스를 만드는 과정이다.

728x90
728x90