첨부 소스 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170

TestProject.zip
다운로드

▶ MainWindow.xaml

<Window x:Class="TestProject.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400"
    Height="300"
    ResizeMode="NoResize"
    Title="마우스 위치 픽셀 색상 구하기"
    FontFamily="나눔고딕코딩"
    FontSize="16">
    <Grid>
        <Grid
            HorizontalAlignment="Center"
            VerticalAlignment="Center">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="Auto" />
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
            <TextBlock Grid.Row="0" Grid.Column="0"
                VerticalAlignment="Center"
                Text="좌표" />
            <TextBlock Grid.Row="1" Grid.Column="0"
                VerticalAlignment="Center"
                Text="색상(16진수)" />
            <TextBlock Grid.Row="2" Grid.Column="0"
                VerticalAlignment="Center"
                Text="색상(10진수)" />
            <TextBox Name="coordinateTextBox" Grid.Row="0" Grid.Column="1"
                Margin="5"
                MinWidth="100"
                BorderThickness="1"
                BorderBrush="Black"
                IsReadOnly="True" />
            <TextBox Name="hexadecimalTextBox" Grid.Row="1" Grid.Column="1"
                Margin="5"
                MinWidth="100"
                BorderThickness="1"
                BorderBrush="Black"
                IsReadOnly="True" />
            <TextBox Name="decimalTextBox" Grid.Row="2" Grid.Column="1"
                Margin="5"
                MinWidth="100"
                BorderThickness="1"
                BorderBrush="Black"
                IsReadOnly="True" />
            <TextBlock Name="messageTextBlock" Grid.Row="3" Grid.Column="1"
                Margin="5"
                Text="캡처중" />
        </Grid>
    </Grid>
</Window>

 

728x90

 

▶ MainWindow.xaml.cs

using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;

namespace TestProject
{
    /// <summary>
    /// 메인 윈도우
    /// </summary>
    public partial class MainWindow : Window
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Struct
        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region 포인트 - POINT

        /// <summary>
        /// 포인트
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        private struct POINT
        {
            /// <summary>
            /// X 좌표
            /// </summary>
            public int X;

            /// <summary>
            /// Y 좌표
            /// </summary>
            public int Y;
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Import
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Private

        #region 커서 위치 구하기 - GetCursorPos(point)

        /// <summary>
        /// 커서 위치 구하기
        /// </summary>
        /// <param name="point">포인트</param>
        /// <returns>처리 결과</returns>
        [DllImport("user32.dll")]
        private static extern bool GetCursorPos(out POINT point);

        #endregion
        #region 디바이스 컨텍스트 생성하기 - CreateDC(driver, device, output, dataHandle)

        /// <summary>
        /// 디바이스 컨텍스트 생성하기
        /// </summary>
        /// <param name="driver">드라이버</param>
        /// <param name="device">디바이스</param>
        /// <param name="output">출력</param>
        /// <param name="dataHandle">데이터 핸들</param>
        /// <returns>디바이스 컨텍스트 핸들</returns>
        [DllImport("gdi32.dll")]
        private static extern IntPtr CreateDC(string driver, string device, string output, IntPtr dataHandle);

        #endregion
        #region 디바이스 컨텍스트 삭제하기 - DeleteDC(dcHandle)

        /// <summary>
        /// 디바이스 컨텍스트 삭제하기
        /// </summary>
        /// <param name="dcHandle">디바이스 컨텍스트 핸들</param>
        /// <returns>처리 결과</returns>
        [DllImport("gdi32.dll")]
        private static extern bool DeleteDC(IntPtr dcHandle);

        #endregion
        #region 픽셀 구하기 - GetPixel(dcHandle, x, y)

        /// <summary>
        /// 픽셀 구하기
        /// </summary>
        /// <param name="dcHandle">디바이스 컨텍스트 핸들</param>
        /// <param name="x">X 좌표</param>
        /// <param name="y">Y 좌표</param>
        /// <returns>픽셀 색상</returns>
        [DllImport("gdi32.dll")]
        private static extern int GetPixel(IntPtr dcHandle, int x, int y);

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field
        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region Field

        /// <summary>
        /// 마지막 색상
        /// </summary>
        private Color lastColor;

        /// <summary>
        /// 마지막 포인트
        /// </summary>
        private POINT lastPoint;

        /// <summary>
        /// 디스패처 타이머
        /// </summary>
        private DispatcherTimer dispatcherTimer;

        /// <summary>
        /// 캡처 여부
        /// </summary>
        private bool isCapturing = true;

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - MainWindow()

        /// <summary>
        /// 생성자
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();

            this.dispatcherTimer = new DispatcherTimer();

            this.dispatcherTimer.Interval = TimeSpan.FromMilliseconds(100);

            PreviewKeyDown            += Window_PreviewKeyDown;
            this.dispatcherTimer.Tick += dispatcherTimer_Tick;

            this.dispatcherTimer.Start();
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region 윈도우 키 DOWN PREVIEW 처리하기 - Window_PreviewKeyDown(sender, e)

        /// <summary>
        /// 윈도우 키 DOWN PREVIEW 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if(e.Key == Key.Space)
            {
                this.isCapturing = !this.isCapturing;

                if(this.isCapturing)
                {
                    this.messageTextBlock.Text = "캡처중";
                }
                else
                {
                    this.messageTextBlock.Text = "캡처 중단";
                }
            }
        }

        #endregion
        #region 디스패처 타이머 틱 처리하기 - dispatcherTimer_Tick(sender, e)

        /// <summary>
        /// 디스패처 타이머 틱 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            if(!this.isCapturing)
            {
                return;
            }

            POINT mousePoint;

            GetCursorPos(out mousePoint);

            if(this.lastPoint.X != mousePoint.X || this.lastPoint.Y != mousePoint.Y)
            {
                this.coordinateTextBox.Text = string.Format("{0}, {1}", mousePoint.X, mousePoint.Y);

                this.lastPoint = mousePoint;
            }

            IntPtr dcHandle = CreateDC("Display", null, null, IntPtr.Zero);

            int colorValue = GetPixel(dcHandle, mousePoint.X, mousePoint.Y);

            DeleteDC(dcHandle);

            Color color = Color.FromRgb
            (
                (byte)( colorValue & 0x000000ff       ),
                (byte)((colorValue & 0x0000ff00) >> 8 ),
                (byte)((colorValue & 0x00ff0000) >> 16)
            );

            if(color != this.lastColor)
            {
                this.hexadecimalTextBox.Text = string.Format("{0:X2}-{1:X2}-{2:X2}", color.R, color.G, color.B);
                this.decimalTextBox.Text     = string.Format("{0}-{1}-{2}"         , color.R, color.G, color.B);

                this.lastColor = color;
            }
        }

        #endregion
    }
}
728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요