WPF开发者QQ群: 340500857
前言
如何进行颜色值拾取?这里采用的是调用WindowsAPI进行实现。
吸取 @沙漠尽头的狼 的建议多写一些文字进行描述。
效果图如下:
第一步 注册WindowsAPI 代码如下:
[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);
第二步 定义颜色拾取方法GetPixelColor 和 鼠标GetCursorPos代码如下:
static public System.Windows.Media.Color GetPixelColor(int x, int y)
{
IntPtr hdc = GetDC(IntPtr.Zero);
uint pixel = GetPixel(hdc, x, y);
ReleaseDC(IntPtr.Zero, hdc);
Color color = Color.FromRgb(
(byte)(pixel & 0x000000FF),
(byte)((pixel & 0x0000FF00) >> 8),
(byte)((pixel & 0x00FF0000) >> 16));
return color;
}
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);
}
第三步 创建计时器 DispatcherTimer 代码如下:
private readonly DispatcherTimer_timer = new DispatcherTimer();
private const int MousePullInfoIntervalInMs = 10;
第四步 构造函数 代码如下:
_timer.Interval = TimeSpan.FromMilliseconds(MousePullInfoIntervalInMs);
_timer.Tick += Timer_Tick;
第五步 Timer_Tick 代码如下:
private void Timer_Tick(object sender, EventArgs e)
{
MyPoint.POINT point = new MyPoint.POINT();
var isMouseDown = MyPoint.GetCursorPos(out point);
var color = GetPixelColor(point.X, point.Y);
btnColor.Background = new SolidColorBrush(color); //new System.Windows.Media.BrushConverter().ConvertFromString(color);
Console.WriteLine(color);
}
第六步 XAML 增加控件 代码如下:
<StackPanel>
<Button Content="拾Color" x:Name="btnColor" Click="Button_Click"></Button>
<Button Content="取消" Click="Button_Click_1"></Button>
</StackPanel>
第七步 实现Button 事件 代码如下:
private void Button_Click(object sender, RoutedEventArgs e)
{
if(!_timer.IsEnabled)
{
_timer.Start();
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (_timer.IsEnabled)
{
_timer.Stop();
}
}
WPF开发者QQ群: 340500857
blogs: https://www.cnblogs.com/yanjinhua
Github:https://github.com/yanjinhuagood
作者:驚鏵
出处:https://www.cnblogs.com/yanjinhua
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
转载请著名作者 出处 https://github.com/yanjinhuagood