使用C#获取鼠标所指像素的颜色
1.创建一个C# windows应用程序
2.添加一个windows表单Label到Form1.cs
3.单击label1控件然后更改Text属性为空字符
4.更改BorderStyle属性为FixedSingle
5.右键单击Form1.cs,然后点击View Code
添加下面Using语句到Form1.cs源码的顶部
6.using System.Runtime.InteropServices;
注意该步骤添加必要的引用来调用InteropServices函数和方法
7.private Bitmap myBitmap;
添加下面的Win32APICall 类到Form1.cs中的Form1类后面
public class Win32APICall
{
[DllImport("gdi32.dll",EntryPoint="DeleteDC")]
public static extern IntPtr DeleteDC(IntPtr hdc);
[DllImport("gdi32.dll",EntryPoint="DeleteObject")]
public static extern IntPtr DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll",EntryPoint="BitBlt")]
public static extern bool BitBlt(IntPtr hdcDest,int nXDest,
int nYDest,int nWidth,int nHeight,IntPtr hdcSrc,
int nXSrc,int nYSrc,int dwRop);
[DllImport ("gdi32.dll",EntryPoint="CreateCompatibleBitmap")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc,
int nWidth, int nHeight);
[DllImport ("gdi32.dll",EntryPoint="CreateCompatibleDC")]
public static extern IntPtr CreateCompatibleDC(IntPtr hdc);
[DllImport ("gdi32.dll",EntryPoint="SelectObject")]
public static extern IntPtr SelectObject(IntPtr hdc,IntPtr hgdiobjBmp);
[DllImport("user32.dll", EntryPoint="GetDesktopWindow")]
public static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll",EntryPoint="GetDC")]
public static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll",EntryPoint="GetSystemMetrics")]
public static extern int GetSystemMetrics(int nIndex);
[DllImport("user32.dll",EntryPoint="ReleaseDC")]
public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDC);
public static Bitmap GetDesktop()
{
int screenX;
int screenY;
IntPtr hBmp;
IntPtr hdcScreen = GetDC(GetDesktopWindow());
IntPtr hdcCompatible = CreateCompatibleDC(hdcScreen);
screenX = GetSystemMetrics(0);
screenY = GetSystemMetrics(1);
hBmp = CreateCompatibleBitmap(hdcScreen, screenX, screenY);
if (hBmp!=IntPtr.Zero)
{
IntPtr hOldBmp = (IntPtr) SelectObject(hdcCompatible, hBmp);
BitBlt(hdcCompatible, 0, 0,screenX,screenY, hdcScreen, 0, 0,13369376);
SelectObject(hdcCompatible, hOldBmp);
DeleteDC(hdcCompatible);
ReleaseDC(GetDesktopWindow(), hdcScreen);
Bitmap bmp = System.Drawing.Image.FromHbitmap(hBmp);
DeleteObject(hBmp);
GC.Collect();
return bmp;
}
return null;
}
}
该步骤添加用于调用非托管windows GDI API函数所需的变量,结构和DllImport语句
8.添加下面代码到在第二步创建的标签的MouseDown 事件中
private void label1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
myBitmap = Win32APICall.GetDesktop();
}
9.添加下面代码到第二步创建的标签的MouseUp 事件中private void label1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
Color myColor = myBitmap.GetPixel(MousePosition.X,MousePosition.Y);
label1.BackColor = myColor;
}
10.点击运行,单击并保持鼠标按钮在标签上保持按下状态,在桌面拖动鼠标指针,然后释放鼠标按钮来捕获颜色