Quantcast
Channel: VBForums - CodeBank - Visual Basic 6 and earlier
Viewing all 1484 articles
Browse latest View live

Bind Cdecl Api To vb6 Function(stdcall),support run in IDE

$
0
0
'bind cdecl api to vb6 function
it's support vb6 ide,exe,excel vba
--------------
FixCdecl AddressOf VB_Add, CdeclApi, 2
c = VB_Add(a, b)

FORM1 CODE:
Code:

Dim h As Long
Dim CdeclApi_Add As Long

Private Sub Command1_Click()
If CdeclApi_Add = 0 Then
    h = LoadLibrary("cdecl.dll")
    CdeclApi_Add = GetProcAddress(h, "Add")
    FixCdecl GetAddress(AddressOf VB_Add), CdeclApi_Add, 2
End If

Dim a As Long, b As Long, c As Long
a = 44
b = 55

c = VB_Add(a, b)
MsgBox "c=" & c
End Sub

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
RestoreFunctionMemory
FreeLibrary h
End Sub

Module1.bas
Code:

Option Explicit
Declare Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As Long
Declare Function GetProcAddress Lib "kernel32" (ByVal hModule As Long, ByVal lpProcName As String) As Long
Public Const PAGE_EXECUTE_READWRITE As Long = &H40
Private Declare Sub CopyMemory2 Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Declare Function WriteProcessMemory2 Lib "kernel32" Alias "WriteProcessMemory" (ByVal hProcess As Long, ByVal lpBaseAddress As Any, ByVal lpBuffer As Any, ByVal nSize As Long, lpNumberOfBytesWritten As Long) As Long
Private Declare Function VirtualProtect2 Lib "kernel32" Alias "VirtualProtect" (ByRef lpAddress As Any, ByVal dwSize As Long, ByVal flNewProtect As Long, lpflOldProtect As Long) As Long  '设置内存可读写
Declare Function FreeLibrary Lib "kernel32" (ByVal hLibModule As Long) As Long
Dim OldFunctionAsm(18) As Byte, FunctionPtr As Long, THUNK_SIZE As Long
'演示用,最简化代码
Function VB_Add(ByVal a As Long, ByVal b As Long, Optional NoUsed As Long) As Long
    MsgBox 1
    MsgBox 1
    MsgBox 1
End Function

Sub FixCdecl(VbFunction As Long, CdeclApi As Long, Args As Long) 'GOOD
  'MsgBox "call-FixCdecl"
    Dim Asm(4) As String, Stub() As Byte ', THUNK_SIZE As Long
    '  0: 58                  pop        eax
    '  1: 89 84 24 XX XX XX XX mov        dword ptr [esp+Xh],eax
    Asm(0) = "58 89 84 24 " & LongToHex(Args * 4) '&H24848958
    Asm(1) = "B8 " & LongToHex(CdeclApi)      'B8 90807000    MOV EAX,708090
    Asm(2) = "FF D0"                          'FFD0          CALL EAX
    Asm(3) = "83 C4 " & Hex(Args * 4) '83 C4 XX      add esp, XX    'cleanup args
    Asm(4) = "C3"
   
    Stub() = toBytes(Join(Asm, " "))
    THUNK_SIZE = UBound(Stub) + 1
   
    Dim bInIDE          As Boolean
    Debug.Assert pvSetTrue(bInIDE)
 
    If bInIDE Then
        CopyMemory2 VbFunction, ByVal VbFunction + &H16, 4
    Else
        VirtualProtect2 VbFunction, THUNK_SIZE, PAGE_EXECUTE_READWRITE, 0    '更改函数地址所在页面属性
    End If
    FunctionPtr = VbFunction
   
    CopyMemory2 ByVal VarPtr(OldFunctionAsm(0)), ByVal VbFunction, THUNK_SIZE '保存函数旧数据
    WriteProcessMemory2 -1, VbFunction, VarPtr(Stub(0)), THUNK_SIZE, 0
End Sub
Sub RestoreFunctionMemory() '恢复原来函数的部分汇编代码,必不可少,否则会崩
    If THUNK_SIZE > 0 Then
        WriteProcessMemory2 -1, FunctionPtr, VarPtr(OldFunctionAsm(0)), THUNK_SIZE, 0
    End If
End Sub
Function toBytes(x As String) As Byte()
    Dim tmp() As String
    Dim fx() As Byte
    Dim i As Long
    tmp = Split(x, " ")
    ReDim fx(UBound(tmp))
    For i = 0 To UBound(tmp)
        fx(i) = CInt("&h" & tmp(i))
    Next
    toBytes = fx()
End Function
 Function LongToHex(x As Long) As String
    Dim b(1 To 4) As Byte
    CopyMemory2 b(1), x, 4
    LongToHex = Hex(b(1)) & " " & Hex(b(2)) & " " & Hex(b(3)) & " " & Hex(b(4))
End Function
 Function pvSetTrue(bValue As Boolean) As Boolean
    bValue = True
    pvSetTrue = True
End Function

Function GetAddress(ByVal V As Long) As Long
GetAddress = V
End Function


[VB6] - sSlide - User Control

Freehand drawing with GDI+

$
0
0
Illustrates how to perform freehand drawing within a GDI+ path. I needed this capability in an application some time ago but was only able to find one example which used GDI+, but it was done there by continuously updating an array of path points and so it was slow and produced ragged edges.

So I wrote this and it worked fine for me. It is very simple and fast. One caveat - using more transparency i.e. less opacity may cause line caps to become more visible.
Attached Files

Path Rotation with GDI+

$
0
0
Illustrates how to rotate a GDI+ path around a center axis. Uses a simple transformation matrix. Useful for certain drawing applications. I originally wrote this for use with certain elements of a custom user interface.
Attached Files

(VB6) Compare two controls interfaces

sorry,Chrome OCX,Miniblink,VB6 chromium,Chrome core only one dll

$
0
0
Chrome OCX,Miniblink,VB6 chromium,Chrome core only one dll
download node.dll from here:
https://github.com/weolar/miniblink49/releases
GitHub - imxcstar/vb6-miniblink-SBrowser: Miniblink control made with vb6 encapsulates all APIs of miniblink free version
https://github.com/imxcstar/vb6-miniblink-SBrowser

GitHub - weolar/miniblink49: a lighter, faster browser kernel of blink to integrate HTML UI in your app. A small, lightweight browser kernel to replace wke和libcef
https://github.com/weolar/miniblink49

This is a good Google Chrome control, free and open source. And the author is not me.

I've been sharing and uploading for free for almost a year. And I've never used it myself.


one developer was working on a software development project the other day and needed to use this control. He can't use it, and he needs me to develop many new functions for him. He contacted me on his own initiative and wanted to pay me some fees to help him develop the work project. This project is not mine, I have no obligation to unconditionally fix all bugs free of charge,If someone needs to develop Russian language for him or spend tens of thousands of dollars to add other functions, I have to give him free production, I can't help it.


Other people's projects were originally free, and I share them with you. Am I obligated to answer all technical questions unconditionally?

We just found some good source code, free to share for everyone to use.
If you need to add some functions, or fix some software technical bugs, you can ask to share it. Can you complete the free and unconditional modification and ask him to add any more functions? Am I his boss? But I didn't pay him salary.

[VB6] Simple VNC Server using DXGI Desktop Duplication

$
0
0
https://github.com/wqweto/VbVncServer

A single-class VNC server for embedding in LOB applications for built-in client support.

Very much work in progress but first cut seems to work.

Based on RFC 6143 and can be used with any VNC viewer like RealVNC or any other you prefer best.

cheers,
</wqw>

The fastest way to download web pages(GET,POST)

$
0
0
Research using multiple methods to download web pages and choose the fastest solution

2021/3/17 14:29:29--WinHttp4(No Options) UsedTime=19795 Ms,Size=319628
2021/3/17 14:29:09--WinHttpRequest3 UsedTime=21714.3689 Ms,Size=319628,Crc32=-2146165443
2021/3/17 14:28:47--WinHttpRequest3_GZIP UsedTime=5174.1903 Ms,Size=59198,Crc32=-2146165443,UnGzip Used Time=2.5319 Ms

Winhttp DonwLoad Use 21 Seconds,by GZIP,only use 5 Seconds

One of the test application examples:
best way to get or save utf-8 content url faster?(https support)-VBForums
https://www.vbforums.com/showthread....https-support)

in my computer, i don't khnow why WinHttpRequest is slowly
WinHttp.WinHttpRequest.5.1,Used 28 seconds
Xmlhttp used 5 seconds


Code:

Sub WinHttpRequest3_GZIP(URL As String, Optional ByVal TimeoutSec As Long = 5)
On Error Resume Next
    QueryPerformanceCounter CPUv1
    Dim http As WinHttpRequest
    Set http = New WinHttpRequest
    With http
        .open "GET", URL, True
        .Option(WinHttpRequestOption_SecureProtocols) = SecureProtocol_ALL
        .Option(WinHttpRequestOption_EnableRedirects) = True
        .Option(WinHttpRequestOption_SslErrorIgnoreFlags) = SslErrorFlag_Ignore_All
       
        .setRequestHeader "Accept-Encoding", "gzip, deflate"
        .setRequestHeader "Accept-Language", "zh-CN,zh;q=0.9,ru;q=0.8"
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"
        .send
        .waitForResponse (TimeoutSec)
    End With
   
    QueryPerformanceCounter CPUv2
    UsedTime1 = (CPUv2 - CPUv1) / MsCount
    Dim bt() As Byte, Bytes As Long
    bt = http.responseBody
    Bytes = UBound(bt) + 1
    Result = "WinHttpRequest3_GZIP UsedTime=" & UsedTime1 & " Ms,Size=" & Bytes
   
   
    Debug.Print Result
End Sub

Download Sample Xmlhttp_WithEvent-2.zip

test result:
2021/3/16 21:39:29 --Xmlhttp DownStart
2021/3/16 21:39:29 --XmlhttpState=1(UsedTime=6.8953 Ms)
2021/3/16 21:39:34 --XmlhttpState=2(UsedTime=4597.2895 Ms)
2021/3/16 21:39:34 --XmlhttpState=3(UsedTime=4598.3393 Ms)
2021/3/16 21:39:34 --XmlhttpState=4(UsedTime=4599.6692 Ms)
DownLoad Url UsedTime=4599.6692 Milliseconds ,Size=318284
------------
2021/3/16 21:31:57 --XmlhttpState=1
2021/3/16 21:32:01 --XmlhttpState=2
2021/3/16 21:32:01 --XmlhttpState=3
2021/3/16 21:32:13 --XmlhttpState=4
DownLoad Url UsedTime=15834.51 Milliseconds


Code:

Private Declare Function timeBeginPeriod Lib "winmm.dll" _
  (ByVal uPeriod As Long) As Long
Private Declare Function timeGetTime Lib "winmm.dll" () As Long

Private Sub Form_Load()
timeBeginPeriod 1
End Sub

Method 1:
Reference DLL:Microsoft scripting runtime,Microsoft Active Data Object,Microsoft MsXml

Code:

Public Function doSome() 'Set AS Class Default Method
    QueryPerformanceCounter CPUv2
    UsedTime1 = (CPUv2 - CPUv1) / MsCount
    Debug.Print Now & " --XmlhttpState=" & XmlhttpObj.readyState & "(UsedTime=" & UsedTime1 & " Ms)"
 
  If XmlhttpObj.readyState = 4 Then
    On Error Resume Next
    Dim bt() As Byte, Bytes As Long
    bt = XmlhttpObj.responseBody
    Bytes = UBound(bt) + 1
    Debug.Print "DownLoad Url UsedTime=" & UsedTime1 & " Milliseconds ,Size=" & Bytes
        Form1.Command1.Caption = "DownLoad Used " & UsedTime1 & " Milliseconds"
    Call SaveByte
  End If
End Function

Form1 code
Code:


  Public a As MSXML2.XMLHTTP
 

Private Sub Command1_Click()
  Dim d As Class1
  Set a = New MSXML2.XMLHTTP
  a.open "get", "http://www.ljc.com/sll.txt", True
  Set d = New Class1
  a.onreadystatechange = d
  a.send
End Sub

Class1 CODE:
Code:

Dim b As ADODB.Stream
 Dim fso As Scripting.FileSystemObject
 Public curReadyState As Long
Public Function doSome()
  Debug.Print Form1.a.readyState
  If Form1.a.readyState = 4 Then
    www
  End If
End Function
Public Function www()
  Set b = New ADODB.Stream
  b.Type = 1
  b.open
  Set fso = New Scripting.FileSystemObject
  If Form1.a.readyState = 4 Then
        b.Write (Form1.a.responseBody)
        If Not fso.FileExists("c:/mmm.txt") Then
          b.SaveToFile "c:/mmm.txt"
        End If
  End If
  b.Close
  Set b = Nothing
  Set fso = Nothing
End Function

Attached Files

vb6 Gif Ocx/Png OCX,Show Movie by DirectShow,WebBrowser,AniGif.OCX

$
0
0
Name:  ShowGif_byWebbrowser.jpg
Views: 19
Size:  30.0 KB
Usercontrol.ctl about Webbrowser GIF(PNG ,JPG),Support Url,Localdisk File
[gif ocx,Png ocx] activex control

Code:

Dim WithEvents M_Dom As MSHTML.HTMLDocument
Public Event ImgClick()
Private Url As String
'Usercontrol Name:WebImgOcx

Private Sub UserControl_Initialize()
'add Webbrowser to Usercontrol
UserControl.ScaleMode = 3
WebBrowser1.Visible = False
End Sub

Public Property Get ImgUrl() As String
    ImgUrl = Url
End Property

Public Property Let ImgUrl(ByVal vNewValue As String)
Url = vNewValue
If Url <> "" Then
    WebBrowser1.Visible = True
    SetImg Url
Else
    WebBrowser1.Visible = False
End If
End Property
 

Private Sub UserControl_ReadProperties(PropBag As PropertyBag)
  ImgUrl = PropBag.ReadProperty("ImgUrl", "")
End Sub
 

Private Sub UserControl_WriteProperties(PropBag As PropertyBag)
 PropBag.WriteProperty "ImgUrl", ImgUrl
End Sub
 

Sub SetImg(UrlA As String)
    Url = UrlA
    WebBrowser1.Navigate Url
End Sub
Private Function M_Dom_onclick() As Boolean
    RaiseEvent ImgClick
End Function

Private Sub WebBrowser1_DocumentComplete(ByVal pDisp As Object, Url As Variant)
If Url = "" Then Exit Sub
    Dim body As Object
    Set M_Dom = WebBrowser1.Document
    Set body = WebBrowser1.Document.body
   
    body.Scroll = "no"
    body.Style.border = "none"
    body.leftMargin = 0
    body.topMargin = 0
   
       
    WebBrowser1.Width = body.All(0).clientWidth
    WebBrowser1.Height = body.All(0).clientHeight
    UserControl.Width = WebBrowser1.Width * Screen.TwipsPerPixelX
    UserControl.Height = WebBrowser1.Height * Screen.TwipsPerPixelY
   
   
    Call WebBrowser1.Document.parentWindow.execScript("document.body.ondragstart=function(){return false}", "javascript") 'good
    Call WebBrowser1.Document.parentWindow.execScript("document.body.oncontextmenu=function(){return false}", "javascript") 'good '禁止右键
End Sub

CALL Usercontrol OCX IN FORM1
Code:

WebImgOcx2.Imgurl="http://www.a.com/123.gif"

Private Sub WebImgOcx2_ImgClick()
 MsgBox WebImgOcx2.ImgUrl
End Sub

Attached Images
 
Attached Files

Neumorphism Design

$
0
0
In this case, it is, on the one hand, a class Module and, on the other, a Usercontrol to create a modern user interface called Neumorphism, which began to become fashionable as of 2020, although it is designed for mobile applications or webs I see no reason not to implement it in our beloved vb6, at least in small applications so as not to overload memory and slow down our app. The whole engine is based on GDI +.

With the class module there is an example where we can play with the properties of the class and other forms with some graphical examples.
In addition, this allows you to draw a GDI + Path with which an extra module was used, where you can create different shapes (Shapes) and the style can be applied to them, I take the opportunity to thank Eduardo for taking part in the routines of his ShapeEx. and thank you very much to SomeYguy for the rutine to rotate path.

With the Usercontrol there are three applied examples. I am not going to detail all the properties, it is a matter of reaching out and playing a bit, they are the same as the module. Accompanying the examples is the "LabelPlus" usercontrol, which is to add text and icons to the forms, (I didn't want to reprogram all this, that's why I used two usercontrols).

Later I am going to upload a music player in which I am working where you can see all this applied.

Finally I want to clarify that all this works faster when it is compiled.

Name:  Neumorphism1.jpg
Views: 81
Size:  17.1 KBName:  Neumorphism2.jpg
Views: 81
Size:  18.1 KBName:  Neumorphism4.jpg
Views: 81
Size:  32.0 KBName:  Neumorphism5.jpg
Views: 81
Size:  15.4 KB

Neumorphism.zip
Attached Images
    
Attached Files

[VB6] In memory convert to JPEG using WIC

$
0
0
This uses Windows Imaging Component to convert a bitmap (a 32-bit DIB) to a JPEG stream purely in memory.

Paste the following code in a .bas module:

Code:

Option Explicit

Private Declare Function SHCreateMemStream Lib "shlwapi" Alias "#12" (pInit As Any, ByVal cbInit As Long) As stdole.IUnknown
Private Declare Function IStream_Size Lib "shlwapi" (ByVal pStream As stdole.IUnknown, uiSize As Any) As Long
Private Declare Function IStream_Reset Lib "shlwapi" (ByVal pStream As stdole.IUnknown) As Long
Private Declare Function IStream_Read Lib "shlwapi" (ByVal pStream As stdole.IUnknown, pvBuf As Any, ByVal cbSize As Long) As Long
'--- WIC
Private Declare Function WICCreateImagingFactory_Proxy Lib "windowscodecs" (ByVal SDKVersion As Long, ppIImagingFactory As stdole.IUnknown) As Long
Private Declare Function IWICImagingFactory_CreateStream_Proxy Lib "windowscodecs" (ByVal pFactory As stdole.IUnknown, ppIWICStream As stdole.IUnknown) As Long
Private Declare Function IWICImagingFactory_CreateEncoder_Proxy Lib "windowscodecs" (ByVal pFactory As stdole.IUnknown, guidContainerFormat As Any, pguidVendor As Any, ppIEncoder As stdole.IUnknown) As Long
Private Declare Function IWICImagingFactory_CreateBitmapFromMemory_Proxy Lib "windowscodecs" (ByVal pFactory As stdole.IUnknown, ByVal uiWidth As Long, ByVal uiHeight As Long, pixelFormat As Any, ByVal cbStride As Long, ByVal cbBufferSize As Long, pbBuffer As Any, ppIBitmap As stdole.IUnknown) As Long
Private Declare Function IWICStream_InitializeFromIStream_Proxy Lib "windowscodecs" (ByVal pIWICStream As stdole.IUnknown, ByVal pIStream As stdole.IUnknown) As Long
Private Declare Function IWICBitmapEncoder_Initialize_Proxy Lib "windowscodecs" (ByVal pIEncoder As stdole.IUnknown, ByVal pIStream As stdole.IUnknown, ByVal cacheOption As Long) As Long
Private Declare Function IWICBitmapEncoder_CreateNewFrame_Proxy Lib "windowscodecs" (ByVal pIEncoder As stdole.IUnknown, ppIFrameEncode As stdole.IUnknown, ppIEncoderOptions As stdole.IUnknown) As Long
Private Declare Function IWICBitmapEncoder_Commit_Proxy Lib "windowscodecs" (ByVal pIEncoder As stdole.IUnknown) As Long
Private Declare Function IWICBitmapFrameEncode_Initialize_Proxy Lib "windowscodecs" (ByVal pIFrameEncode As stdole.IUnknown, ByVal pIEncoderOptions As stdole.IUnknown) As Long
Private Declare Function IWICBitmapFrameEncode_SetSize_Proxy Lib "windowscodecs" (ByVal pIFrameEncode As stdole.IUnknown, ByVal uiWidth As Long, ByVal uiHeight As Long) As Long
Private Declare Function IWICBitmapFrameEncode_WriteSource_Proxy Lib "windowscodecs" (ByVal pIFrameEncode As stdole.IUnknown, ByVal pIBitmapSource As stdole.IUnknown, pWicRect As Any) As Long
Private Declare Function IWICBitmapFrameEncode_Commit_Proxy Lib "windowscodecs" (ByVal pIFrameEncode As stdole.IUnknown) As Long
Private Declare Function IPropertyBag2_Write_Proxy Lib "windowscodecs" (ByVal pPropBag As stdole.IUnknown, ByVal cProperties As Long, pBag As Any, pvarValue As Variant) As Long

Private m_pWicFactory          As stdole.IUnknown

Public Function WicConvertToJpeg(baOutput() As Byte, ByVal lWidth As Long, ByVal lHeight As Long, baInput() As Byte, ByVal lQuality As Long) As Boolean
    Const WINCODEC_SDK_VERSION1  As Long = &H236&
    Const WINCODEC_SDK_VERSION2  As Long = &H237&
    Const WICBitmapEncoderNoCache As Long = 2
    Dim aGUID(0 To 3)  As Long
    Dim pBitmap        As stdole.IUnknown
    Dim pWicStream      As stdole.IUnknown
    Dim pStream        As stdole.IUnknown
    Dim pEncoder        As stdole.IUnknown
    Dim pFrame          As stdole.IUnknown
    Dim pPropBag        As stdole.IUnknown
    Dim cSize          As Currency
    Dim aBag(0 To 7)    As Long
   
    On Error GoTo EH
    If m_pWicFactory Is Nothing Then
        If WICCreateImagingFactory_Proxy(WINCODEC_SDK_VERSION2, m_pWicFactory) < 0 Then
            If pvCheckHResult(WICCreateImagingFactory_Proxy(WINCODEC_SDK_VERSION1, m_pWicFactory)) < 0 Then
                GoTo QH
            End If
        End If
    End If
    '--- GUID_WICPixelFormat32bppPBGRA
    aGUID(0) = &H6FDDC324
    aGUID(1) = &H4BFE4E03
    aGUID(2) = &H773D85B1
    aGUID(3) = &H10C98D76
    If pvCheckHResult(IWICImagingFactory_CreateBitmapFromMemory_Proxy(m_pWicFactory, lWidth, lHeight, aGUID(0), lWidth * 4, UBound(baInput) + 1, baInput(0), pBitmap)) < 0 Then
        GoTo QH
    End If
    If pvCheckHResult(IWICImagingFactory_CreateStream_Proxy(m_pWicFactory, pWicStream)) < 0 Then
        GoTo QH
    End If
    Set pStream = SHCreateMemStream(ByVal 0, 0)
    If pvCheckHResult(IWICStream_InitializeFromIStream_Proxy(pWicStream, pStream)) < 0 Then
        GoTo QH
    End If
    '--- GUID_ContainerFormatJpeg
    aGUID(0) = &H19E4A5AA
    aGUID(1) = &H4FC55662
    aGUID(2) = &H5817C0A0
    aGUID(3) = &H57108E02
    If pvCheckHResult(IWICImagingFactory_CreateEncoder_Proxy(m_pWicFactory, aGUID(0), ByVal 0, pEncoder)) < 0 Then
        GoTo QH
    End If
    If pvCheckHResult(IWICBitmapEncoder_Initialize_Proxy(pEncoder, pWicStream, WICBitmapEncoderNoCache)) < 0 Then
        GoTo QH
    End If
    If pvCheckHResult(IWICBitmapEncoder_CreateNewFrame_Proxy(pEncoder, pFrame, pPropBag)) < 0 Then
        GoTo QH
    End If
    aBag(3) = StrPtr("ImageQuality")
    If pvCheckHResult(IPropertyBag2_Write_Proxy(pPropBag, 1, aBag(0), CSng(lQuality) / 100!)) < 0 Then
        GoTo QH
    End If
    If pvCheckHResult(IWICBitmapFrameEncode_Initialize_Proxy(pFrame, pPropBag)) < 0 Then
        GoTo QH
    End If
    If pvCheckHResult(IWICBitmapFrameEncode_SetSize_Proxy(pFrame, lWidth, lHeight)) < 0 Then
        GoTo QH
    End If
    If pvCheckHResult(IWICBitmapFrameEncode_WriteSource_Proxy(pFrame, pBitmap, ByVal 0)) < 0 Then
        GoTo QH
    End If
    If pvCheckHResult(IWICBitmapFrameEncode_Commit_Proxy(pFrame)) < 0 Then
        GoTo QH
    End If
    If pvCheckHResult(IWICBitmapEncoder_Commit_Proxy(pEncoder)) < 0 Then
        GoTo QH
    End If
    If pvCheckHResult(IStream_Size(pStream, cSize)) < 0 Then
        GoTo QH
    End If
    cSize = cSize * 10000
    If pvCheckHResult(IStream_Reset(pStream)) < 0 Then
        GoTo QH
    End If
    If cSize > 0 Then
        ReDim baOutput(0 To cSize - 1) As Byte
        If pvCheckHResult(IStream_Read(pStream, baOutput(0), cSize)) < 0 Then
            GoTo QH
        End If
    Else
        baOutput = vbNullString
    End If
    '--- success
    WicConvertToJpeg = True
QH:
    Exit Function
EH:
    Debug.Print Err.Description
End Function

Private Function pvCheckHResult(ByVal hResult As Long) As Long
    If hResult < 0 Then
        Err.Raise hResult
    End If
    pvCheckHResult = pvCheckHResult
End Function

Here is the sample Form1 that exercises the WicConvertToJpeg function above

Code:

Option Explicit

Private Declare Function DeleteFile Lib "kernel32" Alias "DeleteFileA" (ByVal lpFileName As String) As Long

Private Sub Form_Load()
    Dim lWidth          As Long
    Dim lHeight        As Long
    Dim baBitmap()      As Byte
    Dim baJpeg()        As Byte
   
    If Not WicLoadPicture("d:\temp\aaa.bmp", lWidth, lHeight, baBitmap) Then
        GoTo QH
    End If
    If Not WicConvertToJpeg(baJpeg, lWidth, lHeight, baBitmap, 80) Then
        GoTo QH
    End If
    WriteBinaryFile "d:\temp\aaa.jpg", baJpeg
QH:
End Sub

Public Sub WriteBinaryFile(sFile As String, baBuffer() As Byte)
    Dim nFile          As Integer
   
    Call DeleteFile(sFile)
    nFile = FreeFile
    Open sFile For Binary Access Write Shared As nFile
    If UBound(baBuffer) >= 0 Then
        Put nFile, , baBuffer
    End If
    Close nFile
End Sub

The test code above needs another .bas module with the WicLoadPicture function

Code:

Option Explicit

'--- WIC
Private Declare Function WICCreateImagingFactory_Proxy Lib "windowscodecs" (ByVal SDKVersion As Long, ppIImagingFactory As stdole.IUnknown) As Long
Private Declare Function IWICImagingFactory_CreateDecoderFromFilename_Proxy Lib "windowscodecs" (ByVal pFactory As stdole.IUnknown, ByVal wzFilename As Long, pguidVendor As Any, ByVal dwDesiredAccess As Long, ByVal lMetadataOptions As Long, ppIDecoder As stdole.IUnknown) As Long
Private Declare Function IWICImagingFactory_CreateFormatConverter_Proxy Lib "windowscodecs" (ByVal pFactory As stdole.IUnknown, ppIFormatConverter As stdole.IUnknown) As Long
Private Declare Function IWICBitmapDecoder_GetFrame_Proxy Lib "windowscodecs" (ByVal pThis As stdole.IUnknown, ByVal lIndex As Long, ppIBitmapFrame As stdole.IUnknown) As Long
Private Declare Function IWICBitmapSource_CopyPixels_Proxy Lib "windowscodecs" (ByVal pThis As stdole.IUnknown, prc As Any, ByVal cbStride As Long, ByVal cbBufferSize As Long, pbBuffer As Any) As Long
Private Declare Function IWICBitmapSource_GetSize_Proxy Lib "windowscodecs" (ByVal pThis As stdole.IUnknown, puiWidth As Long, puiHeight As Long) As Long
Private Declare Function IWICFormatConverter_Initialize_Proxy Lib "windowscodecs" (ByVal pThis As stdole.IUnknown, ByVal pISource As stdole.IUnknown, dstFormat As Any, ByVal lDither As Long, ByVal pIPalette As stdole.IUnknown, ByVal dblAlphaThresholdPercent As Double, ByVal lPaletteTranslate As Long) As Long

Private m_pWicFactory          As stdole.IUnknown

Public Function WicLoadPicture( _
            sFileName As String, _
            lWidth As Long, _
            lHeight As Long, _
            baOutput() As Byte) As Boolean
    Const WINCODEC_SDK_VERSION1 As Long = &H236&
    Const WINCODEC_SDK_VERSION2 As Long = &H237&
    Const GENERIC_READ          As Long = &H80000000
    Dim pDecoder        As stdole.IUnknown
    Dim pFrame          As stdole.IUnknown
    Dim pConverter      As stdole.IUnknown
    Dim aGUID(0 To 3)  As Long
   
    If m_pWicFactory Is Nothing Then
        If WICCreateImagingFactory_Proxy(WINCODEC_SDK_VERSION2, m_pWicFactory) < 0 Then
            If pvCheckHResult(WICCreateImagingFactory_Proxy(WINCODEC_SDK_VERSION1, m_pWicFactory)) < 0 Then
                GoTo QH
            End If
        End If
    End If
    If pvCheckHResult(IWICImagingFactory_CreateDecoderFromFilename_Proxy(m_pWicFactory, StrPtr(sFileName), ByVal 0, GENERIC_READ, 0, pDecoder)) < 0 Or pDecoder Is Nothing Then
        GoTo QH
    End If
    If pvCheckHResult(IWICBitmapDecoder_GetFrame_Proxy(pDecoder, 0, pFrame)) < 0 Or pFrame Is Nothing Then
        GoTo QH
    End If
    If pvCheckHResult(IWICBitmapSource_GetSize_Proxy(pFrame, lWidth, lHeight)) < 0 Then
        GoTo QH
    End If
    If pvCheckHResult(IWICImagingFactory_CreateFormatConverter_Proxy(m_pWicFactory, pConverter)) < 0 Or pConverter Is Nothing Then
        GoTo QH
    End If
    '--- GUID_WICPixelFormat32bppPBGRA
    aGUID(0) = &H6FDDC324
    aGUID(1) = &H4BFE4E03
    aGUID(2) = &H773D85B1
    aGUID(3) = &H10C98D76
    If pvCheckHResult(IWICFormatConverter_Initialize_Proxy(pConverter, pFrame, aGUID(0), 0, Nothing, 0#, 0)) < 0 Then
        GoTo QH
    End If
    ReDim baOutput(0 To lWidth * lHeight * 4 - 1) As Byte
    If pvCheckHResult(IWICBitmapSource_CopyPixels_Proxy(pConverter, ByVal 0&, lWidth * 4, lWidth * lHeight * 4, baOutput(0))) < 0 Then
        GoTo QH
    End If
    '--- success
    WicLoadPicture = True
QH:
End Function

Private Function pvCheckHResult(ByVal hResult As Long) As Long
    If hResult < 0 Then
        Err.Raise hResult
    End If
    pvCheckHResult = pvCheckHResult
End Function

Posted all this code with all API declares to be searchable in the forums as WIC is quite apocryphal technology here.

cheers,
</wqw>

Get Rgb info by GdipBitmapLockBits,Read Bitmap into a 2D array

$
0
0
Read Bitmap into a 2D array
test in form1.frm
Code:

Private Sub Form_Load()
StartUpGDIPlus

Dim Data() As RgbType
Data = GetPicBmpData_RGB(App.Path & "\BMP1.bmp")

MsgBox "One Pixel rgb=" & Data(0, 0).Red & "," & Data(0, 0).Green & "," & Data(0, 0).Blue
'One Pixel rgb=2,22,222
End Sub

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
CloseGdiPlus
End Sub

Name:  GetImgARgb.jpg
Views: 43
Size:  58.4 KB

in bas:
Code:

Option Explicit

  Enum Status
    OK = 0
    GenericError = 1
    InvalidParameter = 2
    OutOfMemory = 3
    ObjectBusy = 4
    InsufficientBuffer = 5
    NotImplemented = 6
    Win32Error = 7
    WrongState = 8
    Aborted = 9
    FileNotFound = 10
    ValueOverflow = 11
    AccessDenied = 12
    UnknownImageFormat = 13
    FontFamilyNotFound = 14
    FontStyleNotFound = 15
    NotTrueTypeFont = 16
    UnsupportedGdiplusVersion = 17
    GdiplusNotInitialized = 18
    PropertyNotFound = 19
    PropertyNotSupported = 20
    ProfileNotFound = 21
End Enum

Private Type GdiplusStartupInput
    GdiplusVersion As Long
    DebugEventCallback As Long
    SuppressBackgroundThread As Long
    SuppressExternalCodecs As Long
End Type

Private Type GdiplusStartupOutput
    NotificationHook As Long
    NotificationUnhook As Long
End Type

Declare Function GdipDisposeImage Lib "GDIPlus" (ByVal image As Long) As Status
Private Declare Function GdiplusShutdown Lib "GDIPlus" (ByVal token As Long) As Status
Private Declare Function GdiplusStartup Lib "GDIPlus" (ByRef token As Long, ByRef lpInput As GdiplusStartupInput, ByRef lpOutput As GdiplusStartupOutput) As Status
Private Const GdiplusVersion As Long = 1&
 

Private Declare Function GdipCreateBitmapFromFile Lib "GDIPlus" (ByVal filename As Long, Bitmap As Long) As Long

Public Declare Function GdipGetImageWidth Lib "GDIPlus" ( _
    ByVal pImage As Long, _
    ByRef nWidth As Long _
) As Long
Public Declare Function GdipGetImageHeight Lib "GDIPlus" ( _
    ByVal pImage As Long, _
    ByRef nHeight As Long _
) As Long
Public Declare Function GdipBitmapLockBits Lib "GDIPlus" ( _
    ByVal pBitmap As Long, _
    ByRef prect As RECTL, _
    ByVal Flags As Long, _
    ByVal pixelFormat As Long, _
    ByRef lockedBitmapData As BitmapData _
) As Long

Public Type BitmapData
  Width As Long
  Height As Long
  Stride As Long
  pixelFormat As Long
  Scan0 As Long
  Reserved As Long
End Type
'
Public Type RECTL
    Left As Long
    Top As Long
    Right As Long
    Bottom As Long
End Type

Public Type Argb
    Blue As Byte
    Green As Byte
    Red As Byte
    Alphi As Byte
End Type

Public Type RgbType
    Blue As Byte
    Green As Byte
    Red As Byte
End Type

Public Enum ImageLockMode
    ImageLockModeRead = &H1
    ImageLockModeWrite = &H2
    ImageLockModeUserInputBuf = &H4
End Enum
'
Public Enum PixelFormats
    PixelFormat24bppRGB = &H21808
    PixelFormat32bppRGB = &H22009
    PixelFormat32bppARGB = &H26200A
    PixelFormat32bppPARGB = &HD200B
End Enum
 Dim lngGdipToken As Long
  Function StartUpGDIPlus(Optional ByVal GdipVersion As Long = GdiplusVersion) As Boolean
 
    Dim GdipStartupInput As GdiplusStartupInput
    Dim GdipStartupOutput As GdiplusStartupOutput
    GdipStartupInput.GdiplusVersion = GdipVersion
    If GdiplusStartup(lngGdipToken, GdipStartupInput, GdipStartupOutput) = OK Then
        StartUpGDIPlus = True
    End If
End Function
Sub CloseGdiPlus()
    GdiplusShutdown lngGdipToken
End Sub


Function GetPicBmpData(File1 As String, Optional W As Long, Optional H As Long) As Byte()
Dim Bitmap As Long, RC As RECTL
Dim Data() As Byte

 
    GdipCreateBitmapFromFile StrPtr(File1), Bitmap
    GdipGetImageWidth Bitmap, W
    GdipGetImageHeight Bitmap, H
RC.Right = W
RC.Bottom = H

 Dim FormatID As Long, Wsize As Long
 FormatID = PixelFormat32bppARGB
 Wsize = 4
 
' FormatID = PixelFormat24bppRGB
'Wsize = 3
    ReDim Data(RC.Right * Wsize * RC.Bottom - 1)
 
    Dim BmpData As BitmapData
    With BmpData
        .Width = W
        .Height = H
 
        .pixelFormat = FormatID
        '.Scan0 = VarPtr(data(0, 0))
        .Scan0 = VarPtr(Data(0))
        .Stride = Wsize * CLng(W)
    End With
 
    GdipBitmapLockBits Bitmap, RC, ImageLockModeUserInputBuf Or ImageLockModeWrite Or ImageLockModeRead, FormatID, BmpData
    GetPicBmpData = Data
    GdipDisposeImage Bitmap
End Function

 
Function GetPicBmpDataXY(File1 As String) As Long()
Dim Bitmap As Long
Dim RC As RECTL
Dim Data() As Long 'DATA(W,H),LONG TYPE=4 BYTE,ARGB
Dim tdata() As Long

GdipCreateBitmapFromFile StrPtr(File1), Bitmap
GdipGetImageWidth Bitmap, RC.Right
  GdipGetImageHeight Bitmap, RC.Bottom
  ReDim Data(RC.Bottom - 1, RC.Right - 1)
  ReDim tdata(RC.Bottom - 1, RC.Right - 1)
  Dim BmpData As BitmapData
  Dim FormatID As Long
  FormatID = PixelFormat32bppARGB

  With BmpData
    .Width = RC.Right
    .Height = RC.Bottom
    .pixelFormat = FormatID
    .Scan0 = VarPtr(Data(0, 0))
    .Stride = 4 * CLng(RC.Right)
  End With
  GdipBitmapLockBits Bitmap, RC, ImageLockModeUserInputBuf Or ImageLockModeWrite Or ImageLockModeRead, FormatID, BmpData
  GetPicBmpDataXY = Data()
End Function

 

Function GetPicBmpData_Argb(File1 As String) As Argb()
Dim Bitmap As Long
Dim RC As RECTL
Dim Data() As Argb 'DATA(W,H),LONG TYPE= ARGB

GdipCreateBitmapFromFile StrPtr(File1), Bitmap
GdipGetImageWidth Bitmap, RC.Right
  GdipGetImageHeight Bitmap, RC.Bottom
 
  ReDim Data(RC.Bottom - 1, RC.Right - 1)

  Dim BmpData As BitmapData
  Dim FormatID As Long
  FormatID = PixelFormat32bppARGB

  With BmpData
    .Width = RC.Right
    .Height = RC.Bottom
    .pixelFormat = FormatID
    .Scan0 = VarPtr(Data(0, 0))
    .Stride = 4 * CLng(RC.Right)
  End With
  GdipBitmapLockBits Bitmap, RC, ImageLockModeUserInputBuf Or ImageLockModeWrite Or ImageLockModeRead, FormatID, BmpData
  GetPicBmpData_Argb = Data()
  GdipDisposeImage Bitmap
End Function

get rgb info:
Code:

Public Type RgbType
    Blue As Byte
    Green As Byte
    Red As Byte
End Type

Function GetPicBmpData_RGB(File1 As String) As RgbType()
Dim Bitmap As Long
Dim RC As RECTL
Dim Data() As RgbType 'DATA(W,H),LONG TYPE= RGB

GdipCreateBitmapFromFile StrPtr(File1), Bitmap
GdipGetImageWidth Bitmap, RC.Right
  GdipGetImageHeight Bitmap, RC.Bottom
 
  ReDim Data(RC.Bottom - 1, RC.Right - 1)

  Dim BmpData As BitmapData
  Dim FormatID As Long
  FormatID = PixelFormat24bppRGB

  With BmpData
    .Width = RC.Right
    .Height = RC.Bottom
    .pixelFormat = FormatID
    .Scan0 = VarPtr(Data(0, 0))
    .Stride = 3 * CLng(RC.Right)
  End With
  GdipBitmapLockBits Bitmap, RC, ImageLockModeUserInputBuf Or ImageLockModeWrite Or ImageLockModeRead, FormatID, BmpData
  GdipDisposeImage Bitmap
  GetPicBmpData_RGB = Data()
End Function

Attached Images
 

Transparent Ocx By Multiple transparent windows form

$
0
0
Multiple transparent windows form a transparent program
load a picture on form1.frm

load a alpha png file to pictureBox1
but pictureBox1 is not transparent
only form with WS_EX_LAYERED can real transparent.

Name:  Transparent Forms.jpg
Views: 32
Size:  26.5 KB
It seems too difficult to implement multiple transparent PNG displays at different levels on one form, with buttons and table controls interspersed in the middle.
My idea is to use multiple windows instead of multiple controls, and a main window to achieve unified follow dragging, and to limit the automatic adjustment of the size of each window.
For example, if the web control webbrowser adopts the color transparency method, a certain color on the web page may not be displayed.
Now the new method is to use a brand new form to load the web page controls separately.
A button can also be loaded separately with a new form.
Too many forms will cause the Z order to change after clicking. So all are set to the top mode (HWND_TOPMOST), and the top and bottom order of each window is set by the code.
Code:

Dim CTf As New PngForm
Dim CTf2 As New PngForm

Sub Main()
CTf.LoadPng App.Path & "\01.png"
mainf.show
CTf2.LoadPng App.Path & "\02.png"

End Sub

Code:

Private Const WIN32_NULL As Long = 0
Private Const WIN32_FALSE As Long = 0
Private Const WIN32_TRUE As Long = Not WIN32_FALSE

Private Declare Function CreateBitmap Lib "gdi32" ( _
    ByVal Width As Long, _
    ByVal Height As Long, _
    ByVal Planes As Long, _
    ByVal BitsPerPixel As Long, _
    ByRef Bits As Any) As Long

Private Declare Function CreateCompatibleDC Lib "gdi32" (ByVal hDC As Long) As Long

Private Const LR_DEFAULTCOLOR As Long = 0

Private Declare Function CreateIconFromResourceEx Lib "user32" ( _
    ByRef IconBits As Byte, _
    ByVal cbIconBits As Long, _
    ByVal fIcon As Long, _
    ByVal dwVersion As Long, _
    ByVal cxDesired As Long, _
    ByVal cyDesired As Long, _
    ByVal uFlags As Long) As Long

Private Declare Function DeleteDC Lib "gdi32" (ByVal hDC As Long) As Long

Private Declare Function DeleteObject Lib "gdi32" (ByVal hObject As Long) As Long

Private Declare Function DestroyIcon Lib "user32" (ByVal hIcon As Long) As Long

Private Enum DI_FLAGS
    DI_MASK = &H1&
    DI_IMAGE = &H2&
    DI_NORMAL = &H3&
    DI_COMPAT = &H4&
    DI_DEFAULTSIZE = &H8&
    DI_NOMIRROR = &H10&
End Enum

Private Declare Function DrawIconEx Lib "user32" ( _
    ByVal hDC As Long, _
    ByVal xLeft As Long, _
    ByVal yTop As Long, _
    ByVal hIcon As Long, _
    ByVal cxWidth As Long, _
    ByVal cyWidth As Long, _
    ByVal istepIfAniCur As Long, _
    ByVal hbrFlickerFreeDraw As Long, _
    ByVal diFlags As DI_FLAGS) As Long

Private Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long

Private Type ICONINFO
    fIcon As Long    'API TRUE for icon, API FALSE for cursor.
    xHotspot As Long  'The hotspot X-coordinate for cursor.
    yHotspot As Long  'The hotspot Y-coordinate for cursor.
    hbmMask As Long  'HBITMAP handle to monochrome AND mask bitmap.
    hbmColor As Long  'HBITMAP handle to device dependent XOR mask bitmap.
End Type

Private Declare Function GetIconInfo Lib "user32" ( _
    ByVal hIcon As Long, _
    ByRef ICONINFO As ICONINFO) As Long

Private Type BITMAP
    bmType As Long
    bmWidth As Long
    bmHeight As Long
    bmWidthBytes As Long
    bmPlanes As Integer
    bmBitsPixel As Integer
    bmBits As Long
End Type

Private Declare Function GetObject Lib "gdi32" Alias "GetObjectW" ( _
    ByVal hObject As Long, _
    ByVal nCount As Long, _
    ByRef Obj As Any) As Long

Private Const GWL_EXSTYLE = -20
Private Const WS_EX_LAYERED = &H80000

Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongW" ( _
    ByVal hwnd As Long, _
    ByVal nIndex As Long) As Long

Private Declare Function ReleaseDC Lib "user32" ( _
    ByVal hwnd As Long, _
    ByVal hDC As Long) As Long

Private Declare Function SelectObject Lib "gdi32" ( _
    ByVal hDC As Long, _
    ByVal hObject As Long) As Long

Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongW" ( _
    ByVal hwnd As Long, _
    ByVal nIndex As Long, _
    ByVal dwNewLong As Long) As Long

Private Type POINT
    x As Long
    y As Long
End Type

Private Type SIZE
    cx As Long
    cy As Long
End Type

Private Const AC_SRC_OVER As Byte = 0
Private Const AC_SRC_ALPHA As Byte = 1

Private Type BLENDFUNCTION
    BlendOp As Byte 'Always AC_SRC_OVER.
    BlendFlags As Byte 'Always 0.
    SourceConstantAlpha As Byte 'We'll set this value upon use.
    AlphaFormat As Byte 'Always AC_SRC_ALPHA.
End Type

Private Enum ULW_FLAGS
    ULW_COLORKEY = &H1&
    ULW_ALPHA = &H2&
    ULW_OPAQUE = &H4&
    ULW_EX_NORESIZE = &H8&
End Enum

Private Declare Function UpdateLayeredWindow Lib "user32" ( _
    ByVal hwnd As Long, _
    ByVal hdcDst As Long, _
    ByRef ptDst As Any, _
    ByRef sizeNew As Any, _
    ByVal hdcSrc As Long, _
    ByRef ptSrc As Any, _
    ByVal crKey As Long, _
    ByRef blend As BLENDFUNCTION, _
    ByVal dwFlags As ULW_FLAGS) As Long

'For dragging:
Private GrabX As Single
Private GrabY As Single

Private Sub Form_DblClick()
    Unload Me
End Sub
Sub LoadPng(Png1 As String)

 
    Dim Bytes() As Byte
    Dim hIcon As Long
    Dim ICONINFO As ICONINFO
    Dim BITMAP As BITMAP
    Dim sizeNew As SIZE
    Dim ptDst As POINT
    Dim ptSrc As POINT '0, 0
    Dim BLENDFUNCTION As BLENDFUNCTION
    Dim hdcScreen As Long
    Dim hdcMem As Long
    Dim hbm As Long

    'Bytes = LoadResData("CIRCLE", "PNG")
    Bytes = OpenBinFile(Png1)
    'App.Path & "\01透明PNG_ICQ.png")
    hIcon = CreateIconFromResourceEx(Bytes(0), _
                                    UBound(Bytes) + 1, _
                                    WIN32_TRUE, _
                                    &H30000, _
                                    0, _
                                    0, _
                                    LR_DEFAULTCOLOR)
    Erase Bytes
    GetIconInfo hIcon, ICONINFO
    GetObject ICONINFO.hbmColor, LenB(BITMAP), BITMAP
    With BITMAP
        sizeNew.cx = .bmWidth
        sizeNew.cy = .bmHeight
    End With
    hdcScreen = GetDC(WIN32_NULL)
    hdcMem = CreateCompatibleDC(hdcScreen)
    With sizeNew
        hbm = CreateBitmap(.cx, .cy, 1, 32, ByVal WIN32_NULL)
        SelectObject hdcMem, hbm
        DrawIconEx hdcMem, _
                  0, _
                  0, _
                  hIcon, _
                  .cx, _
                  .cy, _
                  0, _
                  WIN32_NULL, _
                  DI_NORMAL
    End With
    DestroyIcon hIcon
    SetWindowLong hwnd, _
                  GWL_EXSTYLE, _
                  GetWindowLong(hwnd, GWL_EXSTYLE) Or WS_EX_LAYERED
    With ptDst
        .x = ScaleX(Left, vbTwips, vbPixels)
        .y = ScaleY(Top, vbTwips, vbPixels)
    End With
    With BLENDFUNCTION
        .BlendOp = AC_SRC_OVER
        .SourceConstantAlpha = 255
        .AlphaFormat = AC_SRC_ALPHA
    End With
    UpdateLayeredWindow hwnd, _
                        hdcScreen, _
                        ptDst, _
                        sizeNew, _
                        hdcMem, _
                        ptSrc, _
                        0, _
                        BLENDFUNCTION, _
                        ULW_ALPHA
    ReleaseDC WIN32_NULL, hdcScreen
    DeleteDC hdcMem 'Releases hbm.
    DeleteObject hbm
Me.Show
    'MsgBox "Left-click to end, right-click and drag"
End Sub
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single)
If Button = 1 Then
    Call ReleaseCapture
    SendMessage Me.hwnd, WM_NCLBUTTONDOWN, HTCAPTION, 0&
End If
End Sub

Function OpenBinFile(filename As String, Optional ErrInfo As String) As Byte()
  '[mycode_id:1903],edittime:2011/7/11 13:27:34
On Error Resume Next
Dim hFile As Integer
hFile = FreeFile
Open filename For Binary As #hFile
ReDim OpenBinFile(LOF(hFile) - 1)
Get #hFile, , OpenBinFile
Close #hFile
End Function

Attached Images
 

Transparent Control By Multiple transparent windows form

$
0
0
Multiple transparent windows form a transparent program

How do you switch between multiple windows without changing the focus of the form?If you have five windows with similar layers and click and input textbox on the third window, the first two windows will continue to remain in the top position.
load a picture on form1.frm

load a alpha png file to pictureBox1
but pictureBox1 is not transparent
only form with WS_EX_LAYERED can real transparent.

Name:  Transparent Forms.jpg
Views: 59
Size:  26.5 KB
It seems too difficult to implement multiple transparent PNG displays at different levels on one form, with buttons and table controls interspersed in the middle.
My idea is to use multiple windows instead of multiple controls, and a main window to achieve unified follow dragging, and to limit the automatic adjustment of the size of each window.
For example, if the web control webbrowser adopts the color transparency method, a certain color on the web page may not be displayed.
Now the new method is to use a brand new form to load the web page controls separately.
A button can also be loaded separately with a new form.
Too many forms will cause the Z order to change after clicking. So all are set to the top mode (HWND_TOPMOST), and the top and bottom order of each window is set by the code.
Code:

Dim CTf As New PngForm
Dim CTf2 As New PngForm

Sub Main()
CTf.LoadPng App.Path & "\01.png"
mainf.show
CTf2.LoadPng App.Path & "\02.png"

End Sub

Code:

Private Const WIN32_NULL As Long = 0
Private Const WIN32_FALSE As Long = 0
Private Const WIN32_TRUE As Long = Not WIN32_FALSE

Private Declare Function CreateBitmap Lib "gdi32" ( _
    ByVal Width As Long, _
    ByVal Height As Long, _
    ByVal Planes As Long, _
    ByVal BitsPerPixel As Long, _
    ByRef Bits As Any) As Long

Private Declare Function CreateCompatibleDC Lib "gdi32" (ByVal hDC As Long) As Long

Private Const LR_DEFAULTCOLOR As Long = 0

Private Declare Function CreateIconFromResourceEx Lib "user32" ( _
    ByRef IconBits As Byte, _
    ByVal cbIconBits As Long, _
    ByVal fIcon As Long, _
    ByVal dwVersion As Long, _
    ByVal cxDesired As Long, _
    ByVal cyDesired As Long, _
    ByVal uFlags As Long) As Long

Private Declare Function DeleteDC Lib "gdi32" (ByVal hDC As Long) As Long

Private Declare Function DeleteObject Lib "gdi32" (ByVal hObject As Long) As Long

Private Declare Function DestroyIcon Lib "user32" (ByVal hIcon As Long) As Long

Private Enum DI_FLAGS
    DI_MASK = &H1&
    DI_IMAGE = &H2&
    DI_NORMAL = &H3&
    DI_COMPAT = &H4&
    DI_DEFAULTSIZE = &H8&
    DI_NOMIRROR = &H10&
End Enum

Private Declare Function DrawIconEx Lib "user32" ( _
    ByVal hDC As Long, _
    ByVal xLeft As Long, _
    ByVal yTop As Long, _
    ByVal hIcon As Long, _
    ByVal cxWidth As Long, _
    ByVal cyWidth As Long, _
    ByVal istepIfAniCur As Long, _
    ByVal hbrFlickerFreeDraw As Long, _
    ByVal diFlags As DI_FLAGS) As Long

Private Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long

Private Type ICONINFO
    fIcon As Long    'API TRUE for icon, API FALSE for cursor.
    xHotspot As Long  'The hotspot X-coordinate for cursor.
    yHotspot As Long  'The hotspot Y-coordinate for cursor.
    hbmMask As Long  'HBITMAP handle to monochrome AND mask bitmap.
    hbmColor As Long  'HBITMAP handle to device dependent XOR mask bitmap.
End Type

Private Declare Function GetIconInfo Lib "user32" ( _
    ByVal hIcon As Long, _
    ByRef ICONINFO As ICONINFO) As Long

Private Type BITMAP
    bmType As Long
    bmWidth As Long
    bmHeight As Long
    bmWidthBytes As Long
    bmPlanes As Integer
    bmBitsPixel As Integer
    bmBits As Long
End Type

Private Declare Function GetObject Lib "gdi32" Alias "GetObjectW" ( _
    ByVal hObject As Long, _
    ByVal nCount As Long, _
    ByRef Obj As Any) As Long

Private Const GWL_EXSTYLE = -20
Private Const WS_EX_LAYERED = &H80000

Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongW" ( _
    ByVal hwnd As Long, _
    ByVal nIndex As Long) As Long

Private Declare Function ReleaseDC Lib "user32" ( _
    ByVal hwnd As Long, _
    ByVal hDC As Long) As Long

Private Declare Function SelectObject Lib "gdi32" ( _
    ByVal hDC As Long, _
    ByVal hObject As Long) As Long

Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongW" ( _
    ByVal hwnd As Long, _
    ByVal nIndex As Long, _
    ByVal dwNewLong As Long) As Long

Private Type POINT
    x As Long
    y As Long
End Type

Private Type SIZE
    cx As Long
    cy As Long
End Type

Private Const AC_SRC_OVER As Byte = 0
Private Const AC_SRC_ALPHA As Byte = 1

Private Type BLENDFUNCTION
    BlendOp As Byte 'Always AC_SRC_OVER.
    BlendFlags As Byte 'Always 0.
    SourceConstantAlpha As Byte 'We'll set this value upon use.
    AlphaFormat As Byte 'Always AC_SRC_ALPHA.
End Type

Private Enum ULW_FLAGS
    ULW_COLORKEY = &H1&
    ULW_ALPHA = &H2&
    ULW_OPAQUE = &H4&
    ULW_EX_NORESIZE = &H8&
End Enum

Private Declare Function UpdateLayeredWindow Lib "user32" ( _
    ByVal hwnd As Long, _
    ByVal hdcDst As Long, _
    ByRef ptDst As Any, _
    ByRef sizeNew As Any, _
    ByVal hdcSrc As Long, _
    ByRef ptSrc As Any, _
    ByVal crKey As Long, _
    ByRef blend As BLENDFUNCTION, _
    ByVal dwFlags As ULW_FLAGS) As Long

'For dragging:
Private GrabX As Single
Private GrabY As Single

Private Sub Form_DblClick()
    Unload Me
End Sub
Sub LoadPng(Png1 As String)

 
    Dim Bytes() As Byte
    Dim hIcon As Long
    Dim ICONINFO As ICONINFO
    Dim BITMAP As BITMAP
    Dim sizeNew As SIZE
    Dim ptDst As POINT
    Dim ptSrc As POINT '0, 0
    Dim BLENDFUNCTION As BLENDFUNCTION
    Dim hdcScreen As Long
    Dim hdcMem As Long
    Dim hbm As Long

    'Bytes = LoadResData("CIRCLE", "PNG")
    Bytes = OpenBinFile(Png1)
    'App.Path & "\01透明PNG_ICQ.png")
    hIcon = CreateIconFromResourceEx(Bytes(0), _
                                    UBound(Bytes) + 1, _
                                    WIN32_TRUE, _
                                    &H30000, _
                                    0, _
                                    0, _
                                    LR_DEFAULTCOLOR)
    Erase Bytes
    GetIconInfo hIcon, ICONINFO
    GetObject ICONINFO.hbmColor, LenB(BITMAP), BITMAP
    With BITMAP
        sizeNew.cx = .bmWidth
        sizeNew.cy = .bmHeight
    End With
    hdcScreen = GetDC(WIN32_NULL)
    hdcMem = CreateCompatibleDC(hdcScreen)
    With sizeNew
        hbm = CreateBitmap(.cx, .cy, 1, 32, ByVal WIN32_NULL)
        SelectObject hdcMem, hbm
        DrawIconEx hdcMem, _
                  0, _
                  0, _
                  hIcon, _
                  .cx, _
                  .cy, _
                  0, _
                  WIN32_NULL, _
                  DI_NORMAL
    End With
    DestroyIcon hIcon
    SetWindowLong hwnd, _
                  GWL_EXSTYLE, _
                  GetWindowLong(hwnd, GWL_EXSTYLE) Or WS_EX_LAYERED
    With ptDst
        .x = ScaleX(Left, vbTwips, vbPixels)
        .y = ScaleY(Top, vbTwips, vbPixels)
    End With
    With BLENDFUNCTION
        .BlendOp = AC_SRC_OVER
        .SourceConstantAlpha = 255
        .AlphaFormat = AC_SRC_ALPHA
    End With
    UpdateLayeredWindow hwnd, _
                        hdcScreen, _
                        ptDst, _
                        sizeNew, _
                        hdcMem, _
                        ptSrc, _
                        0, _
                        BLENDFUNCTION, _
                        ULW_ALPHA
    ReleaseDC WIN32_NULL, hdcScreen
    DeleteDC hdcMem 'Releases hbm.
    DeleteObject hbm
Me.Show
    'MsgBox "Left-click to end, right-click and drag"
End Sub
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single)
If Button = 1 Then
    Call ReleaseCapture
    SendMessage Me.hwnd, WM_NCLBUTTONDOWN, HTCAPTION, 0&
End If
End Sub

Function OpenBinFile(filename As String, Optional ErrInfo As String) As Byte()
  '[mycode_id:1903],edittime:2011/7/11 13:27:34
On Error Resume Next
Dim hFile As Integer
hFile = FreeFile
Open filename For Binary As #hFile
ReDim OpenBinFile(LOF(hFile) - 1)
Get #hFile, , OpenBinFile
Close #hFile
End Function

Attached Images
 

Transparent Activex Control,WS_EX_LAYERED on child controls

$
0
0
Project2:VB6 UserControl-Transparency Container-VBForums
https://www.vbforums.com/showthread....ency-Container

Project3: Transparent Control By Multiple transparent windows form-VBForums
https://www.vbforums.com/showthread....t-windows-form

Starting from Window 8, WS_EX_LAYERED can be used for child controls.

Method: A manifest file is required, and at least Window 8 compatibility is specified (sub-layering only supports starting from Window 8).

For anyone who wants to use hierarchical child windows, the following content should be included as a manifest file.

Windows-classic-samples/Samples/DirectCompositionLayeredChildWindow at master · microsoft/Windows-classic-samples · GitHub
https://github.com/Microsoft/Windows...redChildWindow

Code:

<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
      <!--The ID below indicates app support for Windows 8 -->
      <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
    </application>
  </compatibility>
  <dependency>
    <dependentAssembly>
        <assemblyIdentity
            type="win32"
            name="Microsoft.Windows.Common-Controls"
            version="6.0.0.0"
            processorArchitecture="*"
            publicKeyToken="6595b64144ccf1df"
            language="*"
        />
    </dependentAssembly>
  </dependency>
</assembly>

Attached Images
 
Attached Files

VB6 UserControl-Transparency Container

$
0
0
'TransparencyOcx(Transparent container)
'Like PictureBox(NOT for Set Picture),Can Put Controls on it
'Don't Remove Area() Control

change code in sub ShowAllChildArea:
Code:

Sub ShowAllChildArea()
Dim Obj As Control
Dim id As Long
For Each Obj In ContainedControls
    id = id + 1
    If id > Area.Count - 1 Then Load Area(id)
    Area(id).Width = Obj.Width
    Area(id).Height = Obj.Height

    Area(id).Left = Obj.Left
    Area(id).Top = Obj.Top
    Area(id).Visible = True
Next
End Sub

Attached Images
 
Attached Files

Transparent text Box by CreateWindowEx(edit)

$
0
0
How to Transparent text Box by CreateWindowEx(edit)?

.BackgroundBrush = CreatePatternBrush(Form1.Image1.Picture.Handle) 'IT'S good
CODE FROM HERE

YOU GUYS MUST BE SMARTER THAN THIS...-VBForums
https://www.vbforums.com/showthread....92#post5516192

Code:

Option Explicit
Private Const GWL_EXSTYLE = -20
Private Const WS_EX_LAYERED = &H80000

Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongW" ( _
    ByVal hwnd As Long, _
    ByVal nIndex As Long) As Long


Private Const NULL_BRUSH = 5
Private Const HOLLOW_BRUSH = NULL_BRUSH
Declare Function GetStockObject Lib "gdi32" (ByVal nIndex As Long) As Long

Private Declare Function CreateWindowEx Lib "user32" Alias "CreateWindowExA" (ByVal dwExStyle As Long, ByVal lpClassName As String, ByVal lpWindowName As String, ByVal dwStyle As Long, ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hWndParent As Long, ByVal hMenu As Long, ByVal hInstance As Long, lpParam As Any) As Long
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Private Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcA" (ByVal lpPrevWndFunc As Long, ByVal hwnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

Private Declare Function CreateSolidBrush Lib "gdi32" (ByVal crColor As Long) As Long
Private Declare Function DeleteObject Lib "gdi32" (ByVal hObject As Long) As Long
Public Declare Function SetBkMode Lib "gdi32.dll" ( _
  ByVal hdc As Long, _
  ByVal nBkMode As Long) As Long
Private Declare Function SetTextColor Lib "gdi32" (ByVal hdc As Long, ByVal crColor As Long) As Long
Private Declare Function GetBkColor Lib "gdi32" (ByVal hdc As Long) As Long
Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long

Private Const WS_EX_CLIENTEDGE = &H200
Private Const WS_CHILD = &H40000000
Private Const SW_SHOWNORMAL = 1
Private Const GWL_WNDPROC = (-4)
Private Const WM_CTLCOLOREDIT = &H133
Private Const WM_CTLCOLORSTATIC = &H138

Private lFormWndProc As Long

Public Type Editbox
    hwnd As Long
    ForeColor As Long
    BackgroundBrush As Long
    Index As Long
End Type

Private tEditBoxes() As Editbox
Private lEditBoxCount As Long
Dim TxtHwnd As Long
Public Const TRANSPARENT As Long = 1

Public Function FormWindowProc(ByVal hwnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
    Dim tEditBox As Editbox
   
    If Msg = WM_CTLCOLOREDIT Then
    'CTLCOLOR_EDIT:  //对所有编辑框控件的设置
   
        tEditBox = GetEditBox(lParam)
        'lParam就是控件句柄
        If tEditBox.hwnd Then
            With tEditBox
            'Debug.Print "do tEditBox"
                Dim OldBKMode As Long
                OldBKMode = SetBkMode(wParam, TRANSPARENT)

                Call SetTextColor(wParam, .ForeColor)
                If .BackgroundBrush Then
                    Debug.Print "Delete_BackgroundBrush"
                    Call DeleteObject(.BackgroundBrush)
                End If
                Debug.Print "set BackgroundBrush"
 

'                .BackgroundBrush = CreateSolidBrush(GetBkColor(wParam)) 
              .BackgroundBrush = CreatePatternBrush(Form1.Image1.Picture.Handle)


                'CreateSolidBrush(GetStockObject(HOLLOW_BRUSH))
                'CreateSolidBrush (GetBkColor(wParam))

                FormWindowProc = .BackgroundBrush
            End With
            Exit Function
        End If
'    ElseIf Msg = WM_CTLCOLORSTATIC Then
'        Debug.Print "WM_CTLCOLORSTATIC"
    End If
    FormWindowProc = CallWindowProc(lFormWndProc, hwnd, Msg, wParam, lParam)
End Function

Public Function SubClassForm(ByVal hwnd As Long) As Boolean
    If lFormWndProc Then Exit Function
    lFormWndProc = SetWindowLong(hwnd, GWL_WNDPROC, AddressOf FormWindowProc)
    SubClassForm = True
End Function

Public Function RemoveFormSubclassing(ByVal hwnd As Long) As Boolean
    If lFormWndProc Then Exit Function
    Call SetWindowLong(hwnd, GWL_WNDPROC, lFormWndProc)
    RemoveFormSubclassing = True
End Function

Public Function CreateEditbox(ByVal ParentHwnd As Long, ByVal Left As Long, ByVal Top As Long, ByVal Width As Long, ByVal Height As Long) As Editbox
    Dim lHwnd As Long
   
    lHwnd = CreateWindowEx(WS_EX_CLIENTEDGE, "Edit", "", WS_CHILD, Left, Top, Width, Height, ParentHwnd, 0&, App.hInstance, 0&)
   
    If lHwnd = 0 Then Exit Function
    TxtHwnd = lHwnd
'    SetWindowLong TxtHwnd, _
'                  GWL_EXSTYLE, _
'                  GetWindowLong(TxtHwnd, GWL_EXSTYLE) Or WS_EX_LAYERED ' Or WS_DISABLED
                 
    Call ShowWindow(lHwnd, SW_SHOWNORMAL)
   
    lEditBoxCount = lEditBoxCount + 1
   
    ReDim Preserve tEditBoxes(lEditBoxCount)
   
    tEditBoxes(lEditBoxCount).hwnd = lHwnd
    tEditBoxes(lEditBoxCount).ForeColor = vbBlack
    tEditBoxes(lEditBoxCount).Index = lEditBoxCount
    CreateEditbox = tEditBoxes(lEditBoxCount)
End Function

Public Function GetEditBox(ByVal hwnd As Long) As Editbox
    Dim lIndex As Long
    For lIndex = 0 To lEditBoxCount
        If tEditBoxes(lIndex).hwnd = hwnd Then Exit For
    Next
    If lIndex <= lEditBoxCount Then
        GetEditBox = tEditBoxes(lIndex)
    End If
End Function

Public Function SetEditboxForeColor(ByVal Index As Long, ByVal Color As ColorConstants) As ColorConstants
    If Index > lEditBoxCount Then Exit Function
    tEditBoxes(Index).ForeColor = Color
    SetEditboxForeColor = tEditBoxes(Index).ForeColor
End Function

in form1:
Code:

Private Sub Form_Load()
    Me.Picture = LoadPicture("D:\Data2\03编程临时测试资料\01图片\0006背景图.jpg")
    Dim tNewEditBox As Editbox
   
    SubClassForm hwnd
    tNewEditBox = CreateEditbox(hwnd, 10, 10, 150, 28)
    Call SetEditboxForeColor(tNewEditBox.Index, vbRed)
End Sub

Private Sub Form_Unload(Cancel As Integer)
    RemoveFormSubclassing hwnd
End Sub

Msgbox With Picture

$
0
0
how to change use TRANSPARENT color?
GetStockObject(HOLLOW_BRUSH)?

SubMsgBox = CreatePatternBrush(Form1.Picture.Handle)

form1.frm
Code:

Option Explicit

Private Sub Form_Load()
Me.Picture = LoadPicture(App.Path & "\pic3.jpg")
MsgBoxEx "Test Msgbox" & vbCrLf & "123" & vbCrLf & "abc", vbYesNo, "Set Msgbox Picture"
End Sub

bas file:
Code:

Private Type CWPSTRUCT
    lParam As Long
    wParam As Long
    message As Long
    hWnd As Long
End Type

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Declare Function SetWindowsHookEx Lib "user32" Alias "SetWindowsHookExA" (ByVal idHook As Long, ByVal lpfn As Long, ByVal hmod As Long, ByVal dwThreadId As Long) As Long
Private Declare Function CallNextHookEx Lib "user32" (ByVal hHook As Long, ByVal nCode As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare Function UnhookWindowsHookEx Lib "user32" (ByVal hHook As Long) As Long
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Private Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcA" (ByVal lpPrevWndFunc As Long, ByVal hWnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" (ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long

Private Declare Function SetTextColor Lib "gdi32" (ByVal hdc As Long, ByVal crColor As Long) As Long
Private Declare Function GetSysColor Lib "user32" (ByVal nIndex As Long) As Long

Private Declare Function SetBkMode Lib "gdi32" (ByVal hdc As Long, ByVal nBkMode As Long) As Long
Private Declare Function CreatePatternBrush Lib "gdi32" (ByVal hBitmap As Long) As Long
'透明处理
Public Const TRANSPARENT = 1

Private Const WH_CALLWNDPROC = 4
Private Const GWL_WNDPROC = (-4)
Private Const WM_CTLCOLORBTN = &H135
Private Const WM_DESTROY = &H2
Private Const WM_SETTEXT = &HC
Private Const WM_CREATE = &H1

' System Color Constants
Private Const COLOR_BTNFACE = 15
Private Const COLOR_BTNTEXT = 18

' Windows Messages
Private Const WM_CTLCOLORSTATIC = &H138
Private Const WM_CTLCOLORDLG = &H136

Private lHook As Long
Private lPrevWnd As Long

Private lForecolor As Long

Public Function SubMsgBox(ByVal hWnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
    Dim sText As String
    Select Case Msg
        '对话框颜色和标签颜色Message
        Case WM_CTLCOLORDLG, WM_CTLCOLORSTATIC
            Debug.Print wParam & ":Wparam"
            'Set Font Back 透明 和改变颜色。
            If Msg = WM_CTLCOLORSTATIC Then
                Call SetBkMode(wParam, TRANSPARENT)
            End If
            Call SetTextColor(wParam, lForecolor)
            'Set BackGround Picture。
'            SubMsgBox = CreatePatternBrush(LoadResPicture(101, 0).Handle)
            SubMsgBox = CreatePatternBrush(Form1.Picture.Handle)
 
            'LoadResPicture(101, 0).Handle 是资源文件中ID为101的图片。
            Exit Function
        Case WM_DESTROY
            'Remove the MsgBox Subclassing
            Call SetWindowLong(hWnd, GWL_WNDPROC, lPrevWnd)
    End Select
    SubMsgBox = CallWindowProc(lPrevWnd, hWnd, Msg, wParam, ByVal lParam)
End Function

Private Function HookWindow(ByVal nCode As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
    Dim tCWP As CWPSTRUCT
    Dim sClass As String
    'This is where you need to Hook the Messagebox
    CopyMemory tCWP, ByVal lParam, Len(tCWP)
    If tCWP.message = WM_CREATE Then
        sClass = Space(255)
        sClass = Left(sClass, GetClassName(tCWP.hWnd, ByVal sClass, 255))
        If sClass = "#32770" Then
            'Subclass the Messagebox as it's created
            lPrevWnd = SetWindowLong(tCWP.hWnd, GWL_WNDPROC, AddressOf SubMsgBox)
        End If
    End If
    HookWindow = CallNextHookEx(lHook, nCode, wParam, ByVal lParam)
End Function

Public Function MsgBoxEx(ByVal Prompt As String, Optional ByVal Buttons As VbMsgBoxStyle, Optional ByVal Title As String, Optional ByVal HelpFile As String, Optional ByVal Context As Long, Optional ByVal ForeColor As ColorConstants = -1) As Long
    Dim lReturn As Long
    lHook = SetWindowsHookEx(WH_CALLWNDPROC, AddressOf HookWindow, App.hInstance, App.ThreadID)
    'Set the Defaults
    If Len(Title) = 0 Then Title = App.Title
    lForecolor = GetSysColor(COLOR_BTNTEXT)
    If ForeColor >= 0 Then lForecolor = ForeColor
    'Show the Modified MsgBox
    lReturn = MsgBox(Prompt, Buttons, Title, HelpFile, Context)
    Call UnhookWindowsHookEx(lHook)
    MsgBoxEx = lReturn
End Function

MySimpleProjects

$
0
0
6 small apps from my in progress program folder. In various stages of completion , but generally working.
Attached Files

VB6 Transparent Textbox By API(WM_CTLCOLOREDIT)

$
0
0
How to use API to set text to transparent and accept cursor in vb
Code:

'在窗体Form代码中,把以下代码复制进去:
'IN FORM1
Private Sub Form_Load()
makeTransparentTextbox Text1 'Text1
'是需要透明的文本框
End Sub


'BAS FILE: APIs to install our subclassing routines
Code:

Private Const GWL_WNDPROC = (-4)
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Private Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcA" (ByVal lpPrevWndFunc As Long, ByVal hwnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Private Declare Function DefWindowProc Lib "user32" Alias "DefWindowProcA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
' These APIs are used to create a pattern brush for each textbox...
Private Declare Function BitBlt Lib "gdi32" (ByVal hDestDC As Long, ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hSrcDC As Long, ByVal xSrc As Long, ByVal ySrc As Long, ByVal dwRop As Long) As Long
Private Declare Function CreateCompatibleBitmap Lib "gdi32" (ByVal hdc As Long, ByVal nWidth As Long, ByVal nHeight As Long) As Long
Private Declare Function CreateCompatibleDC Lib "gdi32" (ByVal hdc As Long) As Long
Private Declare Function CreatePatternBrush Lib "gdi32" (ByVal hBitmap As Long) As Long
Private Declare Function CreateSolidBrush Lib "gdi32" (ByVal crColor As Long) As Long
Private Declare Function DeleteDC Lib "gdi32" (ByVal hdc As Long) As Long
Private Declare Function DeleteObject Lib "gdi32" (ByVal hObject As Long) As Long
Private Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function GetSysColor Lib "user32" (ByVal nIndex As Long) As Long
Private Declare Function ReleaseDC Lib "user32" (ByVal hwnd As Long, ByVal hdc As Long) As Long
Private Declare Function SelectObject Lib "gdi32" (ByVal hdc As Long, ByVal hObject As Long) As Long
' Messages which we will be processing in our subclassing routines
Private Const WM_COMMAND As Long = &H111
Private Const WM_CTLCOLOREDIT As Long = &H133
Private Const WM_DESTROY As Long = &H2
Private Const WM_ERASEBKGND As Long = &H14
Private Const WM_HSCROLL As Long = &H114
Private Const WM_VSCROLL As Long = &H115
' A rectangle.
Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
' APIs used to keep track of brush handles and process addresses
Private Declare Function GetProp Lib "user32" Alias "GetPropA" (ByVal hwnd As Long, ByVal lpString As String) As Long
Private Declare Function RemoveProp Lib "user32" Alias "RemovePropA" (ByVal hwnd As Long, ByVal lpString As String) As Long
Private Declare Function SetProp Lib "user32" Alias "SetPropA" (ByVal hwnd As Long, ByVal lpString As String, ByVal hData As Long) As Long
' APIs used in our subclassing routine to create the "transparent" effect.
Private Declare Function FillRect Lib "user32" (ByVal hdc As Long, lpRect As RECT, ByVal hBrush As Long) As Long
Private Declare Function GetClientRect Lib "user32" (ByVal hwnd As Long, lpRect As RECT) As Long
Private Declare Function GetParent Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function InvalidateRect Lib "user32" (ByVal hwnd As Long, ByVal lpRect As Long, ByVal bErase As Long) As Long
Private Declare Function LockWindowUpdate Lib "user32" (ByVal hwndLock As Long) As Long
Private Declare Function SetBkMode Lib "gdi32" (ByVal hdc As Long, ByVal nBkMode As Long) As Long
Private Declare Function UpdateWindow Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function WindowFromDC Lib "user32" (ByVal hdc As Long) As Long
Public Function makeTransparentTextbox(aTxt As TextBox)
' Make sure we don't have any typos in our subclassing procedures.
NewWindowProc 0, 0, 0, 0
NewTxtBoxProc 0, 0, 0, 0
' Create a background brush for this textbox, which we will used to give
' the textbox an APPEARANCE of transparency
CreateBGBrush aTxt
' Subclass the textbox's form, IF NOT ALREADY subclassed
If GetProp(GetParent(aTxt.hwnd), "OrigProcAddr") = 0 Then
SetProp GetParent(aTxt.hwnd), "OrigProcAddr", SetWindowLong(GetParent(aTxt.hwnd), GWL_WNDPROC, AddressOf NewWindowProc)
End If
' Subclass the textbox, IF NOT ALREADY subclassed
If GetProp(aTxt.hwnd, "OrigProcAddr") = 0 Then
SetProp aTxt.hwnd, "OrigProcAddr", SetWindowLong(aTxt.hwnd, GWL_WNDPROC, AddressOf NewTxtBoxProc)
End If
End Function
Private Sub CreateBGBrush(aTxtBox As TextBox)
Dim screenDC As Long ' The screen's device context.
Dim imgLeft As Long ' The X location inside the image which we are going to copy from.
Dim imgTop As Long ' The Y location inside the image which we are going to copy from.
Dim picDC As Long ' A temporary DC to pull the form's picture into
Dim picBmp As Long ' the 1x1 bitmap which is created with picDC
Dim aTempBmp As Long ' A temporary bitmap we'll use to create the pattern brush for our textbox
Dim aTempDC As Long ' the temporary device context used to hold aTempBmp
Dim txtWid As Long ' The form's width
Dim txtHgt As Long ' the form's height.
Dim solidBrush As Long ' Solid brush used to color in the bitmap... incase the textbox
' gets sized outside the dimensions of the picture
Dim aRect As RECT ' Rectangle to fill in with solid brush
If aTxtBox.Parent.Picture Is Nothing Then Exit Sub
' Get our form's dimensions, in pixels
txtWid = aTxtBox.Width / Screen.TwipsPerPixelX
txtHgt = aTxtBox.Height / Screen.TwipsPerPixelY
' Get the location within the bitmap picture we're copying from
imgLeft = aTxtBox.Left / Screen.TwipsPerPixelX
imgTop = aTxtBox.Top / Screen.TwipsPerPixelY
' Get the screen's device context
screenDC = GetDC(0)
' Create a device context to hold the form's picture.
picDC = CreateCompatibleDC(screenDC)
picBmp = SelectObject(picDC, aTxtBox.Parent.Picture.Handle)
' Create a temporary bitmap to blt the underlying image onto
aTempDC = CreateCompatibleDC(screenDC)
aTempBmp = CreateCompatibleBitmap(screenDC, txtWid, txtHgt)
DeleteObject SelectObject(aTempDC, aTempBmp)
' create a brush the color of BUTTON_FACE
solidBrush = CreateSolidBrush(GetSysColor(15))
aRect.Right = txtWid
aRect.Bottom = txtHgt
' Fill in the area
FillRect aTempDC, aRect, solidBrush
' clean up our resource
DeleteObject solidBrush
' Transfer the image
BitBlt aTempDC, 0, 0, txtWid, txtHgt, picDC, imgLeft, imgTop, vbSrcCopy
' Check to make sure that a brush hasn't already been made for this one
If GetProp(aTxtBox.hwnd, "CustomBGBrush") <> 0 Then
' If so, then delete it and free its memory before storing the new one's handle.
DeleteObject GetProp(aTxtBox.hwnd, "CustomBGBrush")
End If
' Create a pattern brush from our bitmap and store its handle against
' the textbox's handle
SetProp aTxtBox.hwnd, "CustomBGBrush", CreatePatternBrush(aTempBmp)
' Clean up our temporary DC and bitmap resources
DeleteDC aTempDC
DeleteObject aTempBmp
' Replace the original 1x1 bitmap, releasing the form's picture
SelectObject picDC, picBmp
' Clean up our picture DC and the 1x1 bitmap that was created with it
DeleteDC picDC
DeleteObject picBmp
' Release the screen's DC back to the system... forgetting to do this
' causes a nasty memory leak.
ReleaseDC 0, screenDC
End Sub
Private Function NewWindowProc(ByVal hwnd As Long, ByVal uMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
' ******************************************************
' SUBCLASSING ROUTINE FOR THE TEXTBOX'S >>>>PARENT<<<<
' ******************************************************
Dim origProc As Long ' The original process address for the window.
Dim isSubclassed As Long ' Whether a certain textbox is subclassed or not.
' I've gotten in the habit of passing 0 values to the subclassing functions before
' actually installing them, just to make sure that I don't have any typos or other
' problems which can be easily detected. As such, if there is a hwnd of 0, its not
' a "valid" message, so we'll just exit right away.
If hwnd = 0 Then Exit Function
' Get the original process address which we stored earlier.
origProc = GetProp(hwnd, "OrigProcAddr")
If origProc <> 0 Then
If (uMsg = WM_CTLCOLOREDIT) Then
' Check to see if our window has a stored value for the original
' process address. If so, we're subclassing this one.
isSubclassed = (GetProp(WindowFromDC(wParam), "OrigProcAddr") <> 0)
If isSubclassed Then
' Invoke the default process... This will set the font, font color
' and other stuff we don't really want to fool with.
CallWindowProc origProc, hwnd, uMsg, wParam, lParam
' Make the words print transparently
SetBkMode wParam, 1
' Return the handle to our custom brush rather than that which
' the default process would have returned.
NewWindowProc = GetProp(WindowFromDC(wParam), "CustomBGBrush")
Else
' The textbox in question isn't subclassed, so we aren't going
' to do anything out of the ordinary. Just invoke the default proc.
NewWindowProc = CallWindowProc(origProc, hwnd, uMsg, wParam, lParam)
End If
ElseIf uMsg = WM_COMMAND Then
' Check to see if our window has a stored value for the original
' process address. If so, we're subclassing this one.
isSubclassed = (GetProp(lParam, "OrigProcAddr") <> 0)
If isSubclassed Then
' We are going lock the window from updating while we invalidate
' and redraw it. This prevents flickering.
LockWindowUpdate GetParent(lParam)
' Force windows to redraw the window.
InvalidateRect lParam, 0&, 1&
UpdateWindow lParam
End If
' Invoke the default process
NewWindowProc = CallWindowProc(origProc, hwnd, uMsg, wParam, lParam)
If isSubclassed Then LockWindowUpdate 0&
ElseIf uMsg = WM_DESTROY Then
' The window is being destroyed... time to unhook our process so we
' don't cause a big fat error which crashes the application.
' Install the default process address again
SetWindowLong hwnd, GWL_WNDPROC, origProc
' Invoke the default process
NewWindowProc = CallWindowProc(origProc, hwnd, uMsg, wParam, lParam)
' Remove our stored value since we don't need it anymore
RemoveProp hwnd, "OrigProcAddr"
Else
' We're not concerned about this particular message, so we'll just
' let it go on its merry way.
NewWindowProc = CallWindowProc(origProc, hwnd, uMsg, wParam, lParam)
End If
Else
' A catch-all in case something freaky happens with the process addresses.
NewWindowProc = DefWindowProc(hwnd, uMsg, wParam, lParam)
End If
End Function
Private Function NewTxtBoxProc(ByVal hwnd As Long, ByVal uMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
' *********************************************
' SUBCLASSING ROUTINE FOR THE >>>>TEXTBOX<<<<
' *********************************************
Dim aRect As RECT
Dim origProc As Long
Dim aBrush As Long
If hwnd = 0 Then Exit Function
' Get the original process address which we stored earlier.
origProc = GetProp(hwnd, "OrigProcAddr")
If origProc <> 0 Then
' We're subclassing! Which is silly, 'cause otherwise we wouldn't be in
' this function, however we double check the process address just in case.
If uMsg = WM_ERASEBKGND Then
' We're going to get our custom brush for this textbox and fill the
' textbox's background area with it...
aBrush = GetProp(hwnd, "CustomBGBrush")
If aBrush <> 0 Then
' Get the area dimensions to fill
GetClientRect hwnd, aRect
' Fill it with our custom brush
FillRect wParam, aRect, aBrush
' Tell windows that we took care of the "erasing"
NewTxtBoxProc = 1
Else
' Something happened to our custom brush :-\ We'll just invoke
' the default process
NewTxtBoxProc = CallWindowProc(origProc, hwnd, uMsg, wParam, lParam)
End If
ElseIf uMsg = WM_HSCROLL Or uMsg = WM_VSCROLL Then
' We are scrolling, either horizontally or vertically. This requires
' us to totally repaint the background area... so we'll lock the
' window updates so we don't see any of the freaky flickering
LockWindowUpdate GetParent(hwnd)
' Invoke the default process so the user actually get's the scroll
' they want
NewTxtBoxProc = CallWindowProc(origProc, hwnd, uMsg, wParam, lParam)
' Force window to repaint itself
InvalidateRect hwnd, 0&, 1&
UpdateWindow hwnd
' Release the update lock
LockWindowUpdate 0&
ElseIf uMsg = WM_DESTROY Then
' The textbox's parent is closing / destroying, so we need to
' unhook our subclassing routine ... or bad things happen
' Clean up our brush object... muy importante!!!
aBrush = GetProp(hwnd, "CustomBGBrush")
' Delete the brush object, freeing its resource.
DeleteObject aBrush
' Remove our values we stored against the textbox's handle
RemoveProp hwnd, "OrigProcAddr"
RemoveProp hwnd, "CustomBGBrush"
' Replace the original process address
SetWindowLong hwnd, GWL_WNDPROC, origProc
' Invoke the default "destroy" process
NewTxtBoxProc = CallWindowProc(origProc, hwnd, uMsg, wParam, lParam)
Else
' We're not interested in this message, so we'll just let it truck
' right on thru... invoke the default process
NewTxtBoxProc = CallWindowProc(origProc, hwnd, uMsg, wParam, lParam)
End If
Else
' A catch-all in case something freaky happens with the process addresses.
NewTxtBoxProc = DefWindowProc(hwnd, uMsg, wParam, lParam)
End If
End Function

Viewing all 1484 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>