微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

vb.net 教程 5-9 屏幕范围内取色

屏幕范围内取色
在本博客 《vb:Cg色彩精灵》系列中,我们在vb6中使用Api函数对屏幕进行取色,在vb.net中,我们可以有更简单的方法完成此项工作。


延续使用我们在 《颜色》中的窗口界面,增加两个控件:
btnPick Button
lblLocation Label


窗体级的变量
isPick:标识是否开始取色
bmp:不可见的bitmap,保存了当前屏幕的截图
    Dim isPick As Boolean
    Dim bmp As Bitmap

鼠标左键按下的时候我们要做的工作:
1、设置按下鼠标左键时,isPick为真,标识开始取色
2、将屏幕截图保存在bmp中
3、将鼠标光标设置为十字样式
    Private Sub btnPick_MouseDown(sender As Object,e As MouseEventArgs) Handles btnPick.MouseDown
        If e.Button = MouseButtons.Left Then
            isPick = True
            Dim Scr As Screen = Screen.PrimaryScreen
            Dim recSc As Rectangle = Scr.Bounds
            bmp = New Bitmap(recSc.Width,recSc.Height)
            Dim g As Graphics = Graphics.FromImage(bmp)

            g.copyFromScreen(New Point(0,0),New Point(0,New Size(recSc.Width,recSc.Height))

            Me.Cursor = Cursors.Cross
        End If
    End Sub


鼠标移动的时候我们要做的工作
1、获得鼠标坐标位置
2、将鼠标坐标转换为屏幕坐标,通过控件的PointToScreen()方法完成
3、对bmp坐标点取色,通过GetPixel()方法完成
4、附加对颜色的RGB值做了简单分析
    Private Sub btnPick_MouseMove(sender As Object,e As MouseEventArgs) Handles btnPick.MouseMove
        Dim x,y As Integer
        Dim p As Point = New Point(e.X,e.Y)
        Dim colorPoint As Color
        Dim r,g,b As Byte

        If isPick = True Then
            x = btnPick.PointToScreen(p).X
            y = btnPick.PointToScreen(p).Y
            lblLocation.Text = "x:" & x & " y:" & y
            colorPoint = bmp.GetPixel(x,y)

            picPalette.BackColor = colorPoint
            r = colorPoint.R
            g = colorPoint.G
            b = colorPoint.B

            hsbRed.Value = r
            hsbGreen.Value = g
            hsbBlue.Value = b

            lblRed.Text = r.ToString
            lblGreen.Text = g.ToString
            lblBlue.Text = b.ToString

            Call toWebColor()
        End If
    End Sub

鼠标左键抬起的时候要做的工作:
1、设置抬起鼠标左键时,isPick为假,标识停止取色
2、将鼠标光标设置为认样式
    Private Sub btnPick_MouseUp(sender As Object,e As MouseEventArgs) Handles btnPick.MouseUp
        isPick = False
        Me.Cursor = Cursors.Default
    End Sub

当鼠标左键在“取色”按钮上按下不放时,移动鼠标就可以在屏幕上取色了。如下图:


由于.net平台下C#和vb.NET很相似,本文也可以为C#爱好者提供参考。

学习更多vb.net知识,请参看 vb.net 教程 目录

原文地址:https://www.jb51.cc/vb/256756.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐