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

前端之家收集整理的这篇文章主要介绍了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 教程 目录

猜你在找的VB相关文章