实践过程
效果
代码
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("gdi32.dll")]
static public extern uint GetPixel(IntPtr hDC, int XPos, int YPos);
[DllImport("gdi32.dll")]
static public extern IntPtr CreateDC(string driverName, string deviceName, string output, IntPtr lpinitData);
[DllImport("gdi32.dll")]
static public extern bool DeleteDC(IntPtr DC);
static public byte GetRValue(uint color)
{
return (byte) color;
}
static public byte GetGValue(uint color)
{
return ((byte) (((short) (color)) >> 8));
}
static public byte GetBValue(uint color)
{
return ((byte) ((color) >> 16));
}
static public byte GetAValue(uint color)
{
return ((byte) ((color) >> 24));
}
public Color GetColor(Point screenPoint)
{
IntPtr displayDC = CreateDC("DISPLAY", null, null, IntPtr.Zero);
uint colorref = GetPixel(displayDC, screenPoint.X, screenPoint.Y);
DeleteDC(displayDC);
byte Red = GetRValue(colorref);
byte Green = GetGValue(colorref);
byte Blue = GetBValue(colorref);
return Color.FromArgb(Red, Green, Blue);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
Point pt = new Point(Control.MousePosition.X, Control.MousePosition.Y);
Color cl = GetColor(pt);
panel1.BackColor = cl;
}
}
partial class Form1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.panel1 = new System.Windows.Forms.Panel();
this.SuspendLayout();
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// panel1
//
this.panel1.Location = new System.Drawing.Point(12, 12);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(200, 100);
this.panel1.TabIndex = 0;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(535, 298);
this.Controls.Add(this.panel1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.Panel panel1;
}
到此这篇关于基于C#实现屏幕取色器的示例详解的文章就介绍到这了,更多相关C#屏幕取色器内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!