之前都是用别人的颜色拾取器,今天自己用WPF写了一个颜色拾取器小程序 拾取鼠标所在位置的颜色,按键盘上的空格键停止取色

程序下载:MyWPFScreenColorE.rar

程序里面有一个全局的勾子实现键盘的按下事件停止拾取(有全局勾子可能会报毒 勾子总被用于木马 现在的杀软对勾子很警惕 )

但是我还没有好的办法不用勾子去实现停止拾取,如果看到帖子的人有好的办法请指点一下,谢谢

是基于framework 3.5

用vs2008开发的

操作:

1点击开始取色就会根据鼠标的移动记录下鼠标下的颜色并显示在颜色预览里

2,按键盘上的空格键就会停止取色,自己复制下来RGB的值

开发思路:

1记录鼠标的坐标

2拾取鼠标下的颜色

开始上代码开发吧

记录鼠标的坐标

public class MyPoint
   {
       [StructLayout(LayoutKind.Sequential)]
       public struct POINT
       {
           public int X;
           public int Y;
           public POINT(int x, int y)
           {
               this.X = x;
               this.Y = y;
           }
       }
       [DllImport("user32.dll", CharSet = CharSet.Auto)]
       public static extern bool GetCursorPos(out POINT pt);
   }  

拾取颜色返回鼠标下的Color

public class ScreenColor
    {
        [DllImport("user32.dll")]
        static extern IntPtr GetDC(IntPtr hwnd);
        [DllImport("user32.dll")]
        static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);
        [DllImport("gdi32.dll")]
        static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);
        static public System.Drawing.Color GetPixelColor(int x, int y)
        {
            IntPtr hdc = GetDC(IntPtr.Zero);
            uint pixel = GetPixel(hdc, x, y);
            ReleaseDC(IntPtr.Zero, hdc);
            Color color = Color.FromArgb((int)(pixel & 0x000000FF),
                         (int)(pixel & 0x0000FF00) >> 8,
                         (int)(pixel & 0x00FF0000) >> 16);
            return color;
        }
    }

调用

MyPoint.POINT POINT = new MyPoint.POINT();
MyPoint.GetCursorPos(out POINT);  

用键盘让程序停下来我还真没有什么好办法就用了一个键盘勾子

这是一个全局的勾子实现拾取键盘的按键

//Declare wrapper managed POINT class.
   [StructLayout(LayoutKind.Sequential)]
   public class POINT
   {
       public int x;
       public int y;
   }
   //Declare wrapper managed MouseHookStruct class.
   [StructLayout(LayoutKind.Sequential)]
   public class MouseHookStruct
   {
       public POINT pt;
       public int hwnd;
       public int wHitTestCode;
       public int dwExtraInfo;
   }
   //Declare wrapper managed KeyboardHookStruct class.
   [StructLayout(LayoutKind.Sequential)]
   public class KeyboardHookStruct
   {
       public int vkCode; //Specifies a virtual-key code. The code must be a value in the range 1 to 254.
       public int scanCode; // Specifies a hardware scan code for the key.
       public int flags; // Specifies the extended-key flag, event-injected flag, context code, and transition-state flag.
       public int time; // Specifies the time stamp for this message.
       public int dwExtraInfo; // Specifies extra information associated with the message.
   }
   public class GlobalHook
   {
       public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
       public GlobalHook()
       {
           Start();
       }
       ~GlobalHook()
       {
           Stop();
       }
       public event MouseEventHandler OnMouseActivity;
       public event KeyEventHandler KeyDown;
       public event KeyPressEventHandler KeyPress;
       public event KeyEventHandler KeyUp;
       public delegate int GlobalHookProc(int nCode, Int32 wParam, IntPtr lParam);
       static int hMouseHook = 0; //Declare mouse hook handle as int.
       static int hKeyboardHook = 0; //Declare keyboard hook handle as int.
       //values from Winuser.h in Microsoft SDK.
       public const int WH_MOUSE_LL = 14; //mouse hook constant
       public const int WH_KEYBOARD_LL = 13; //keyboard hook constant
       GlobalHookProc MouseHookProcedure; //Declare MouseHookProcedure as HookProc type.
       GlobalHookProc KeyboardHookProcedure; //Declare KeyboardHookProcedure as HookProc type.
       //Import for SetWindowsHookEx function.
       //Use this function to install a hook.
       [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
       public static extern int SetWindowsHookEx(int idHook, GlobalHookProc lpfn,
           IntPtr hInstance, int threadId);
       //Import for UnhookWindowsHookEx.
       //Call this function to uninstall the hook.
       [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
       public static extern bool UnhookWindowsHookEx(int idHook);
       //Import for CallNextHookEx.
       //Use this function to pass the hook information to next hook procedure in chain.
       [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
       public static extern int CallNextHookEx(int idHook, int nCode,
           Int32 wParam, IntPtr lParam);
       public void Start()
       {
           // install Mouse hook
           if (hMouseHook == 0)
           {
               // Create an instance of HookProc.
               MouseHookProcedure = new GlobalHookProc(MouseHookProc);
               try
               {
                   hMouseHook = SetWindowsHookEx(WH_MOUSE_LL,
                       MouseHookProcedure,
                       Marshal.GetHINSTANCE(
                       Assembly.GetExecutingAssembly().GetModules()[0]),
                       0);
               }
               catch (Exception err)
               { }
               //If SetWindowsHookEx fails.
               if (hMouseHook == 0)
               {
                   Stop();
                   throw new Exception("SetWindowsHookEx failed.");
               }
           }
           // install Keyboard hook
           if (hKeyboardHook == 0)
           {
               KeyboardHookProcedure = new GlobalHookProc(KeyboardHookProc);
               try
               {
                   hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL,
                       KeyboardHookProcedure,
                       Marshal.GetHINSTANCE(
                       Assembly.GetExecutingAssembly().GetModules()[0]),
                       0);
               }
               catch (Exception err2)
               { }
               //If SetWindowsHookEx fails.
               if (hKeyboardHook == 0)
               {
                   Stop();
                   //throw new Exception("SetWindowsHookEx ist failed.");
               }
           }
       }
       public void Stop()
       {
           bool retMouse = true;
           bool retKeyboard = true;
           if (hMouseHook != 0)
           {
               retMouse = UnhookWindowsHookEx(hMouseHook);
               hMouseHook = 0;
           }
           if (hKeyboardHook != 0)
           {
               retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
               hKeyboardHook = 0;
           }
           //If UnhookWindowsHookEx fails.
           if (!(retMouse && retKeyboard))
           {
           }
               //throw new Exception("UnhookWindowsHookEx failed.");
       }
       private const int WM_MOUSEMOVE = 0x200;
       private const int WM_LBUTTONDOWN = 0x201;
       private const int WM_RBUTTONDOWN = 0x204;
       private const int WM_MBUTTONDOWN = 0x207;
       private const int WM_LBUTTONUP = 0x202;
       private const int WM_RBUTTONUP = 0x205;
       private const int WM_MBUTTONUP = 0x208;
       private const int WM_LBUTTONDBLCLK = 0x203;
       private const int WM_RBUTTONDBLCLK = 0x206;
       private const int WM_MBUTTONDBLCLK = 0x209;
       private int MouseHookProc(int nCode, Int32 wParam, IntPtr lParam)
       {
           // if ok and someone listens to our events
           if ((nCode >= 0) && (OnMouseActivity != null))
           {
               MouseButtons button = MouseButtons.None;
               switch (wParam)
               {
                   case WM_LBUTTONDOWN:
                       //case WM_LBUTTONUP:
                       //case WM_LBUTTONDBLCLK:
                       button = MouseButtons.Left;
                       break;
                   case WM_RBUTTONDOWN:
                       //case WM_RBUTTONUP:
                       //case WM_RBUTTONDBLCLK:
                       button = MouseButtons.Right;
                       break;
               }
               int clickCount = 0;
               if (button != MouseButtons.None)
                   if (wParam == WM_LBUTTONDBLCLK || wParam == WM_RBUTTONDBLCLK)
                       clickCount = 2;
                   else
                       clickCount = 1;
               //Marshall the data from callback.
               MouseHookStruct MyMouseHookStruct =
                   (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));
               MouseEventArgs e = new MouseEventArgs(
                   button,
                   clickCount,
                   MyMouseHookStruct.pt.x,
                   MyMouseHookStruct.pt.y,
                   0);
               OnMouseActivity(this, e);
           }
           return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
       }
       //The ToAscii function translates the specified virtual-key code and keyboard state to the corresponding character or characters. The function translates the code using the input language and physical keyboard layout identified by the keyboard layout handle.
       [DllImport("user32")]
       public static extern int ToAscii(int uVirtKey, //[in] Specifies the virtual-key code to be translated.
           int uScanCode, // [in] Specifies the hardware scan code of the key to be translated. The high-order bit of this value is set if the key is up (not pressed).
           byte[] lpbKeyState, // [in] Pointer to a 256-byte array that contains the current keyboard state. Each element (byte) in the array contains the state of one key. If the high-order bit of a byte is set, the key is down (pressed). The low bit, if set, indicates that the key is toggled on. In this function, only the toggle bit of the CAPS LOCK key is relevant. The toggle state of the NUM LOCK and SCROLL LOCK keys is ignored.
           byte[] lpwTransKey, // [out] Pointer to the buffer that receives the translated character or characters.
           int fuState); // [in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise.
       //The GetKeyboardState function copies the status of the 256 virtual keys to the specified buffer.
       [DllImport("user32")]
       public static extern int GetKeyboardState(byte[] pbKeyState);
       private const int WM_KEYDOWN = 0x100;
       private const int WM_KEYUP = 0x101;
       private const int WM_SYSKEYDOWN = 0x104;
       private const int WM_SYSKEYUP = 0x105;
       private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
       {
           // it was ok and someone listens to events
           if ((nCode >= 0) && (KeyDown != null || KeyUp != null || KeyPress != null))
           {
               KeyboardHookStruct MyKeyboardHookStruct =
                   (KeyboardHookStruct)Marshal.PtrToStructure(lParam,
                   typeof(KeyboardHookStruct));
               // raise KeyDown
               if (KeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
               {
                   Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
                   KeyEventArgs e = new KeyEventArgs(keyData);
                   KeyDown(this, e);
               }
               // raise KeyPress
               if (KeyPress != null && wParam == WM_KEYDOWN)
               {
                   byte[] keyState = new byte[256];
                   GetKeyboardState(keyState);
                   byte[] inBuffer = new byte[2];
                   if (ToAscii(MyKeyboardHookStruct.vkCode,
                       MyKeyboardHookStruct.scanCode,
                       keyState,
                       inBuffer,
                       MyKeyboardHookStruct.flags) == 1)
                   {
                       KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]);
                       KeyPress(this, e);
                   }
               }
               // raise KeyUp
               if (KeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
               {
                   Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
                   KeyEventArgs e = new KeyEventArgs(keyData);
                   KeyUp(this, e);
               }
           }
           return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
       }
   }

  

调用的时候

GlobalHook my_Hook = new GlobalHook();
my_Hook.KeyDown += new System.Windows.Forms.KeyEventHandler(my_Hook_KeyDown);      <br>my_Hook.Start();
void my_Hook_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
             
            if (e.KeyCode == System.Windows.Forms.Keys.Space )//(e.Alt || e.Control || e.Shift)
            {
                ifStart = false;
            }
        }

  

程序下载:MyWPFScreenColorE.rar

本文转自lpxxn博客园博客,原文链接:http://www.cnblogs.com/li-peng/archive/2013/03/08/2950015.html,如需转载请自行联系原作者

用 WPF 写的颜色拾取器相关推荐

  1. VS编程,WPF中,通过telerik控件创建颜色选择器,颜色拾取器,调色板的一种方法

     这里展示使用telerik控件时,调用颜色调色板,颜色选择器,颜色拾取器的一种方法 1.增加引用 2.前台定义引用 xmlns:telerik="http://schemas.teleri ...

  2. Winform中实现颜色拾取器获取RGB与16进制颜色程序与源码分享

    场景 效果 实现 关键代码 using System; using System.Collections.Generic; using System.ComponentModel; using Sys ...

  3. 在线颜色拾取器 - 资源篇

    在线颜色拾取器 - 资源篇 点击访问资源: 在线颜色拾取器 截图示下:

  4. 颜色拾取器color picker (javascript version)

    颜色拾取器 216种web safe color的构造方法 var cl = ['00','33','66','99','CC','FF'];     var clist = [];     for( ...

  5. windows(C语言版)——颜色拾取器

    2019独角兽企业重金招聘Python工程师标准>>> 这段时间一直有看<windows程序设计>,通过C语言调用windows API,这并不是件轻松的事,window ...

  6. html5 url颜色,HTML5input新增type属性color颜色拾取器的实例代码

    type 属性规定 input 元素的类型.本文较详细的给大家介绍了HTML5 input新增type属性color颜色拾取器的实例代码,感兴趣的朋友跟随脚本之家小编一起看看吧 定义和用法 type ...

  7. Pickr.js响应式颜色拾取器插件

    下载地址 Pickr是简单的响应式颜色拾取器插件,可删节拾色.它没有依赖关系,兼容所有的CSS框架比如Bootstrap.主要特色简单的使用没有依赖关系多种颜色表示颜色比较不透明度控制支持触摸设备轻量 ...

  8. html中input的color,怎么使用html5中input的color颜色拾取器?使用方法分享!

    从事编程方面类的小伙伴们都知道时不时更新换代是我们习以为常的家常便饭对于程序员来说,那么今天我们就来说说:"怎么使用html5中input新增type属性color颜色拾取器?"这 ...

  9. HTML5 input新增type属性color颜色拾取器是怎样使用的?你可能不知道的javascript获取法?(95)

    color 定义拾色器. 定义和用法 type 属性规定 input 元素的类型. 注释:该属性不是必需的,但是我们认为您应该始终使用它 代码如下:是通过js来获取的! <!DOCTYPE ht ...

最新文章

  1. Vi非正常退出导致敏感信息泄露
  2. 迷你世界电锯机器人_迷你世界:会旋转的机器人,安装多个火箭炮,全方位轰炸敌人...
  3. 逻辑网络拓扑与物理网络拓扑—Vecloud微云
  4. 数据分析与挖掘实战-窃电漏电用户的发现
  5. 一个SAP开发人员2017年在编程和游泳上的双重修炼过程
  6. 【Transformer】DETR: End-to-End Object Detection with Transformers
  7. 黑盒法测试c语言,黑盒测试用例练习题.pdf
  8. beast单元库的总结
  9. SpringMVC 控制层注解
  10. 同质化代币和非同质化代币 区别对比
  11. C++制作植物大战僵尸
  12. PDF能编辑吗,PDF文件怎么拆分页面
  13. RPG游戏之龙腾世纪魔术师养成攻略
  14. 前端面试系列-JavaScript作用域和作用域链
  15. 解决:outlook邮件内容过宽,打印不全
  16. QQ/微信里被禁止访问的网页怎么处理 如何检测域名是否被QQ/微信 屏蔽
  17. Library projects cannot set applicationId问题解决
  18. SystemUI Q 移植到android studio开发
  19. python \r \t \n 各种转义字符
  20. [超详细] Git 远程仓库及回滚日志操作

热门文章

  1. 直播app开发需要走的六大步骤
  2. 多商户商城系统功能拆解03讲-平台端商家管理
  3. linux 中的指令
  4. python:编解码器基类之无状态的编码和解码
  5. Word文档的锁定与解锁
  6. 【软件工具安装-win10】windows下VMware安装centos7
  7. Matlab深度学习实战一:LeNe-5图像分类篇MNIST数据集分十类且matlab提供模型框架全网为唯一详细操作流程
  8. ruby on rails 日志: log4r
  9. swf to html5 movie maker,SWF to Video Converter Pro(Flash转换视频格式)
  10. 各种开机画面的S905L3A/AB通刷包B863AV3.1-M2/3.2-M/311-1A/1AS/M401A/E900V22C/D