日期:2014-05-19  浏览次数:20727 次

如何在MouseMove事件中获得control上某个点的颜色值?
请问各位高人:

如何在MouseMove事件中获得control类的对象上某个点的颜色值?

要是用MFC就好办   因为CDC类有GetPixel()
可是.net里面的Graphics类中怎么会没有类似的方法呢?

盼大侠们不吝赐教!

------解决方案--------------------
Public Function GetDCPixel(ByVal ScreenPoint As Point) As Color
Dim hCurrentDc As Integer
Dim intColor As Integer
Dim c As Color
hCurrentDc = CreateDC( "DISPLAY ", vbNullString, vbNullString, 0)
intColor = GetPixel(hCurrentDc, ScreenPoint.X, ScreenPoint.Y)
DeleteDC(hCurrentDc)
c = Color.FromArgb(intColor)
Return Color.FromArgb(c.B, c.G, c.R)
End Function
其中使用了CreateDC、DeleteDC和GetPixel三个API:
Declare Function GetPixel Lib "gdi32 " Alias "GetPixel " (ByVal hdc As Integer, ByVal x As Integer, ByVal y As Integer) As Integer

Declare Function CreateDC Lib "gdi32 " Alias "CreateDCA " (ByVal lpDriverName As String, ByVal lpDeviceName As String, ByVal lpOutput As String, ByVal lpInitData As Long) As Integer

Declare Function DeleteDC Lib "gdi32 " Alias "DeleteDC " (ByVal hdc As Long) As Long

------解决方案--------------------
[DllImport( "user32.dll ")]
public static extern IntPtr GetDC(IntPtr hwnd);

[DllImport( "user32.dll ")]
public static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);

[DllImport( "gdi32.dll ")]
public static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);

private void button1_Click(object sender, EventArgs e)
{
IntPtr vDC = GetDC(IntPtr.Zero);
int vPixel = (int)GetPixel(vDC, Cursor.Position.X, Cursor.Position.Y);
Color vColor = Color.FromArgb(
(vPixel & 0x000000FF) > > 0,
(vPixel & 0x0000FF00) > > 8,
(vPixel & 0x00FF0000) > > 16);
ReleaseDC(IntPtr.Zero, vDC);
button1.ForeColor = vColor;
Text = vColor.ToString();
}