获取屏幕指定位置颜色

Windows桌面小工具,在桌面右上角显示时钟(包括年月日等信息)

先上效果图:

几个用到的关键代码:

//务必在程序using部分添加该引用
using System.Runtime.InteropServices;
using System.Drawing;

//在public Form1()之前添加以下代码
[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);

//获取指定位置(屏幕的x,y位置)的颜色
//返回C#中的Color类型
public Color GetColor(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;
}

后期优化:

1、由于Windows Form控件自身的原因,虽然设置Transparent属性可以显示透明色,但是并不能达到鼠标穿透的效果,因此我将其设置成:当鼠标移动进入控件时,自动隐藏窗体,以免影响鼠标的正常操作。

更新:可以设置鼠标穿透属性,但是做这个项目的时候没有完全掌握该方法,大家可以参考我的其他博客内容,有牵扯到相关的鼠标穿透属性。

2、由于上一步设置了鼠标进入自动隐藏,因此我们将无法改变时钟显示的位置,我们可以通过Load方法将其自动固定到桌面右上角位置,涉及到代码如下:

private void Form1_Load(object sender, EventArgs e)
{
    this.Left = Screen.PrimaryScreen.WorkingArea.Width - this.Width;
    this.Top = 0;
}

其他说明:

计时部分采用Windows Form自带的Timer控件实现,具体代码可见CSDN附件

 

补充:

鼠标穿透使用到的部分有:

[DllImport("user32", EntryPoint = "SetWindowLong")]
private static extern uint SetWindowLong(IntPtr hwnd, int nIndex, uint dwNewLong);
[DllImport("user32", EntryPoint = "GetWindowLong")]
private static extern uint GetWindowLong(IntPtr hwnd, int nIndex);

public string Penetrate(IntPtr Handle)
{
    uint intExTemp = GetWindowLong(Handle, GWL_EXSTYLE);
    uint oldGWLEx;
    oldGWLEx = SetWindowLong(Handle, GWL_EXSTYLE, intExTemp | WS_EX_TRANSPARENT |     WS_EX_LAYERED);
    return "设置鼠标穿透成功!";
}

//调用部分
Penetrate(this.Handle);

带有鼠标穿透的整个项目(项目中包含部分其他未完成功能,请自动忽略)下载

 

 

-----------------------------------------------------------------------------

作者邮箱:zzudongxiang@163.com

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值