VBGood网站全文搜索 Google

搜索VBGood全站网页(全文搜索)
返回 发表评论(0) 首页 - API手册 - 奇形怪状的窗体
 
奇形怪状的窗体

    普通的窗体都是方方的,使用API函数可以做出一些奇怪的形状。比如,窗体是圆角矩形,在中间挖一个椭圆形的洞。

    先要理解一个重要的概念:区域。区域是描述设备场景中某一块的GDI对象,每个区域都有一个句柄。一个区域可以是矩形,也可以是复杂的多边形,甚至是几个区域组织在一起。窗体默认的区域就是我们看到的矩形,当然它并非一定要用这个默认的区域

    现在开始,首先在窗体上做一个圆角矩形区域,这是窗体的大致轮廓。在圆角矩形里再确定一个椭圆形的区域,然后把这两个区域组织成一个区域,并设置窗体的区域为这个组织出来的区域。

    CreateRoundRectRgn函数用于创建一个圆角矩形区域;CreateEllipticRgn用于创建一个椭圆区域;CombineRgn函数用于将两个区域组合为一个新区域;SetWindowRgn函数允许您改变窗口的区域。使用其他的函数还可以做出其他更奇怪的窗体。

    源代码如下:

    Option Explicit

    ' API 函数声明

    Private Declare Function CreateRectRgn Lib "gdi32" (ByVal X1 As Long, ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long) As Long
    Private Declare Function CreateRoundRectRgn Lib "gdi32" (ByVal X1 As Long, ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long, ByVal X3 As Long, ByVal Y3 As Long) As Long
    Private Declare Function CreateEllipticRgn Lib "gdi32" (ByVal X1 As Long, ByVal Y1 As Long, ByVal X2 As Long, ByVal Y2 As Long) As Long
    Private Declare Function CombineRgn Lib "gdi32" (ByVal hDestRgn As Long, ByVal hSrcRgn1 As Long, ByVal hSrcRgn2 As Long, ByVal nCombineMode As Long) As Long
    Private Declare Function SetWindowRgn Lib "user32" (ByVal hWnd As Long, ByVal hRgn As Long, ByVal bRedraw As Boolean) As Long
    Private Declare Function DeleteObject Lib "gdi32" (ByVal hObject As Long) As Long

    '常数声明

    Private Const RGN_DIFF = 4
    ' 目标区域被设置为两个区域不相交的部分

    '模块级变量声明

    Private OutRgn As Long
    ' 外边的圆角矩形区域
    Private InRgn As Long
    ' 里边的椭圆区域
    Private MyRgn As Long
    ' 圆角区域剪切掉椭圆区域后的区域,也是窗体最终的形状

    Private Sub Form_Click()
        If OutRgn <> 0 And InRgn <> 0 And MyRgn <> 0 Then Exit Sub
        Dim w As Long, h As Long
        w = ScaleX(Form1.Width, vbTwips, vbPixels)
        h = ScaleY(Form1.Height, vbTwips, vbPixels)
        MyRgn = CreateRectRgn(0, 0, 0, 0)
        OutRgn = CreateRoundRectRgn(30, 30, w - 30, h - 30, 100, 100)
        InRgn = CreateEllipticRgn(100, 100, w - 100, h - 100)
        Call CombineRgn(MyRgn, OutRgn, InRgn, RGN_DIFF)
        Call SetWindowRgn(Form1.hWnd, MyRgn, True)
        Form1.BackColor = QBColor(4)
    End Sub

    Private Sub Form_DblClick()
        Unload Form1
    End Sub

    Private Sub Form_Load()
        OutRgn = 0
        InRgn = 0
        MyRgn = 0
        Form1.Width = 7800
        Form1.Height = 6000
    End Sub

    Private Sub Form_Unload(Cancel As Integer)
        If MyRgn <> 0 Then DeleteObject MyRgn
        If OutRgn <> 0 Then DeleteObject OutRgn
        If InRgn <> 0 Then DeleteObject InRgn
    End Sub

    这个程序运行后,在窗体上单击,窗体就会变形,双击窗体程序结束。要注意的是,在卸载窗体时,用DeleteObject函数删除已定义的区域。