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

VB6 Tools: VB6 Rapihken Kabeh (Code Formatter)

$
0
0
This VB6 Add-Ins tools will format your code easy, based on Bobo Code Formatter.

How to use:

  1. Compile
  2. Double click install.bat
  3. Open your project click Add-Ins >> Rapikan Kode.
  4. Simply click Button Rapihken Wawarehan for formatting single (current) Code Module or check Rapihken Kabehanana for formatting all Code Module, please wait while VB6 Rapihken Kabeh working.


Warning!
Please backup your code before use this tools.
Attached Files

VB6 - SQL Parameters Example

$
0
0
Background

I'll start with a quote:

Why Parameters are a Best Practice
Quote:

Perhaps the single most important SQL Server application development Best Practice is the consistent use of parameters in application code. Parameterized database calls are more secure, easier to program and promote query plan reuse. Yet I continue to see code with SQL statements constructed by concatenating literal strings with variable values. I think this is largely out of ignorance rather than design so I decided to show how easy it is for .NET application developers to use parameters and peek into the internals to show why parameters are so important.
The same applies to VB6 just as well. However Dan's examples don't help us much since we're using ADO rather than any of the .Net data connector technologies.

So here is a simplified demo showing how to do similar things in VB6 with ADO.


The Demo

This is a simple demo showing the use of named ADO Command objects to perform parameter queries. It also shows how to store photos in the database as BLOB fields, retrieve them, display them, and update them.

While the demo uses Jet 4.0 to make it quick and easy to "unzip and play" the demo, these same concepts apply to other databases that you can use ADO with.


What It Does

When the program runs it begins by looking for an existing database. If found, it asks whether to delete it and create a new one or not.

If it creates a new database it then:

  • Removes any existing database.
  • Creates an empty database with one table [PicTable] with three fields:
    • [ID] an autonumber "identity" field set as the primary key.
    • [Description] a variable length (0-255 character) text field.
    • [Picture] a variable length (0-20000 byte)) long binary (BLOB) field.
  • Closes the empty database.
  • Reopens the database defining commands InsertPic and UpdatePic on the Connection.
  • Populates the table with three sample records based on information in a provided text file and JPEG images in a subfolder.


Else it then:

  • Opens the existing database defining the command UpdatePic (since it won't need InsertPic).


Finally, it:

  • Displays the first record, showing all three fields.


The user interface has three buttons:

  • "Back" and "Next" to step through records and display them.
  • "Replace Photo" to replace the photo of the current record by a provided fixed replacement JPEG and redisplay the updated record.


The Command objects are used to do a SQL INSERT and a SQL UPDATE. They are invoked as dynamic methods of the open Connection object.


Running the Demo

Just unzip into a folder and open the Project in the VB6 IDE. Then go ahead and run it.

Step through the records. When you see the "wrong" picture you can click Replace Photo to update with a hard-coded replacement photo.

Name:  sshot1.jpg
Views: 95
Size:  16.9 KB

Name:  sshot2.jpg
Views: 80
Size:  16.2 KB


Close the program. Run it again and when prompted to create a new empty database click the "No" button.

Step through the records to see that the update was permanent.


Defining Named ADO Command Objects

By creating named Command objects you can use them dynamic methods of the Connection object until they are destroyed or disconnected. Here is what the demo does when connecting to the database after it has been created:

Code:

Public Sub OpenDbDefineCommands(ByVal NewDb As Boolean)
    Set conDB = New ADODB.Connection
    conDB.Open strConn

    If NewDb Then
        Set cmndInsert = New ADODB.Command
        With cmndInsert
            .Name = "InsertPic"
            .CommandType = adCmdText
            .CommandText = "INSERT INTO [PicTable] " _
                        & "([Description], [Picture]) " _
                        & "VALUES (?, ?)"
            .Parameters.Append .CreateParameter(, adVarWChar, adParamInput, 255)
            .Parameters.Append .CreateParameter(, adLongVarBinary, adParamInput, MAX_PHOTO_BYTES)
            .Prepared = True
            Set .ActiveConnection = conDB
        End With
    End If

    Set cmndUpdate = New ADODB.Command
    With cmndUpdate
        .Name = "UpdatePic"
        .CommandType = adCmdText
        .CommandText = "UPDATE [PicTable] " _
                    & "SET [Picture] = ? " _
                    & "WHERE [ID] = ?"
        .Parameters.Append .CreateParameter(, adLongVarBinary, adParamInput, MAX_PHOTO_BYTES)
        .Parameters.Append .CreateParameter(, adInteger, adParamInput)
        .Prepared = True
        Set .ActiveConnection = conDB
    End With
End Sub

ADO will actually create entries in the Parameters collection itself on first use of a Command if you do not Create/Append them yourself. However it has to "guess" at things like the data type and length 9for variable length types).

In the cases here, those "guesses" are fine... until they aren't.

Let's say when you populate the new, empty database your first image is 4000 bytes. This will cause ADO to set the maximum length of the 2nd Parameter to 4000. And if you use the Command again passing an image larger than 4000 bytes you will get a runtime error!


Calling Named ADO Command Objects

You can call the Execute method on these Command objects, or you can also use them as dynamic methods of the Connection:

Code:

Public Function UpdatePic(ByVal PicFileName As String, ByVal ID As Long) As Boolean
    'Returns True if the operation fails.

    On Error Resume Next
    conDB.UpdatePic LoadPicBlob(PicFileName), ID
    If Err Then
        conDB.Errors.Clear
        Err.Clear
        UpdatePic = True
    End If
End Function

Private Function LoadPicBlob(ByVal PicFileName As String) As Byte()
    Dim PicFile As Integer
    Dim PicBlob() As Byte

    PicFile = FreeFile(0)
    Open PHOTOS_FOLDER & PicFileName For Binary Access Read As #PicFile
    ReDim PicBlob(LOF(PicFile) - 1)
    Get #PicFile, , PicBlob
    Close #PicFile
    LoadPicBlob = PicBlob
End Function

Attached Images
  
Attached Files

VB6 SQLite DB-Demos (based on the RichClient-Framework)

$
0
0
SQLite (http://sqlite.org/)

...is the worlds most widely deployed DB-engine (running on nearly every mobile-device or tablet - but it is also "strong on the Desktop",
being the Default-App-DB for Firefox or WebKit or Thunderbird - and many other vendors/applications.

The (SingleFile-DB-) Format is unicode-capable and interchangeable among operating-systems (no matter if little-endian or big-endian-based).
Means, if you copy an SQLite-DB from your iPhone (or Linux-Server) onto your Win-Desktop, you will have no problem accessing it there (and vice versa).

It still has a pretty small footprint, but other than the name may suggest, it is by no means "Lite" in the technical sense anymore...
So, if there is a strong competitor for the very often used JET-engine, VB5/6-users so far prefer as their "typical App-DB", SQLite is it...

Features (not found in JET-*.mdbs)
- Triggers
- FullText-Search (FTS4)
- true InMemory-DBs (for "LINQ-like" query-scenarios in your VB6-App, using cMemDB and cRecordset)
- strong (and compared with JET "unhackable") encryption on the whole DB (only 10-15% performance-decrease)
- userdefinable Collations (String-Comparisons for Sorts)
- userdefinable SQL-Functions (calling back into easy codable, native compilable VB6-code)
- UTF8-String-storage by default (resulting in typically smaller DBs, compared with JET, which preferrably stores in UTF-16)

Performance (compared with JET)
- typically 2-3 times as fast in read-direction (Rs-retrieval, complex Selects)
- typically 10 times as fast in write-direction (Bulk-Inserts/Updates/Deletes wrapped in transactions, import-scenarios with typically 200000 new inserted Records per second)

VB6-access per DAO/ADO...
Over ODBC ... a well-written SQLite-ODBC-driver can be found here:
http://www.ch-werner.de/sqliteodbc/

VB6-access without any MS-(DAO/ADO) dependencies...
per builtin (ADO-like) cConnection/cRecordset/cCommand-Classes in vbRichClient5:
http://www.vbRichClient.com/#/en/Downloads.htm

These wrapper-classes work faster than the above mentioned ADO/ODBC-combination.

Ok, Demo-Apps:

First a simple one, still using the normal GUI-controls of VB6, to not "alienate" anybody ...(as said, the usage of the DB-related classes is pretty much comparable to ADO)... ;-)

Thanks to dilettante for the nice Original, which can be found (as an ADO/JET-version) here:
http://www.vbforums.com/showthread.p...meters-Example

The version below is not that much different (aside from the AddNew and Delete-Buttons - and the SQLite-engine of course).
http://www.vbRichClient.com/Download...DemoSQLite.zip




Finally an SQLite-Demo, which does not only replace ADO/JET, but also the VB6-GUI-controls ...
There isn't any Common-Controls involved, only the Widget-engine of the RichClient-library comes into play here
(in conjunction with the vbWidgets.dll, which is hosted on GitHub: https://github.com/vbRichClient/vbWidgets).

The Original to this still simple Demo is also based on ADO/JET, and can be found on PSC:
http://www.planet-source-code.com/vb...35601&lngWId=1

There's one thing "special" (aside from the vbWidgets) in this demo - and that's the regfree-deployment-feature,
which is supported (without manifests and SxS-services) by the Frameworks smallest lib, the DirectCOM.dll.

So the archive below comes as "a RealWorld-DeployPackage", and is therefore a bit larger (it contains,
beside the VB6-source, also the 3 Base-Dlls of the RC5-Framework in a SubFolder \RC5Bin\).

This way the Application is directly startable from e.g. an USB-Stick, without the need to register anything -
the deploymentsize for such a RC5-based "regfree Package" starts from about 1.6MB (when LZMA-compressed,
e.g. with InnoSetup ... or, as the download here, in a 7z-archive):
http://www.vbRichClient.com/Downloads/SQLiteTree.7z (about 1.7MB)

Another thing which is different from the first demo above (which provides its new generated DB, directly from imported Text-file-snippets),
is the fact, that this Demo is using the exact same ADO-JET-*.mdb as the original on PSC as its Import-Source for the new created SQLite-DB.
So this example also covers a simple "Convert-From-JET-DB-to-SQLite"-scenario - and shows, how to use the builtin cCOnvert-Class for that task...





Well, have fun with it.

Olaf

BSpline-based "Bezier-Art"

$
0
0
A small Graphics-Demo for VB6, which shows the nice effects one can produce, when Anti-Aliasing in conjunction with Color-Alpha-settings is combined with "curved Line-Output".

Here's the ~90 lines of code, to put into a single VB-Form:
Code:

'needs a reference to the free vbRichClient5-lib, which is located and available on:
'http://www.vbRichClient.com/#/en/Downloads.htm
Option Explicit
 
Private Srf As cCairoSurface, NumPoints As Single
Private pntX() As Single, pntY() As Single, sgnX() As Single, sgnY() As Single
Private WithEvents tmrRefresh As cTimer

Private Sub Form_Load()
Dim i As Long
'    Rnd -1 'uncomment, if you want to always start from the same "randomness"

    Me.ScaleMode = vbPixels
    Me.Caption = "Left-Click for Start/Stop, Right-Click to clear"
   
    NumPoints = 7
    ReDim pntX(1 To NumPoints): ReDim pntY(1 To NumPoints)
    ReDim sgnX(1 To NumPoints): ReDim sgnY(1 To NumPoints)
 
    For i = 1 To NumPoints
      pntX(i) = ScaleWidth * Rnd
      pntY(i) = ScaleHeight * Rnd
      sgnX(i) = IIf(i Mod 2, 1, -1)
      sgnY(i) = IIf(i Mod 2, -1, 1)
    Next i
   
    Set tmrRefresh = New_c.Timer(10, True)
End Sub
 
Private Sub Form_DblClick()
  tmrRefresh.Enabled = Not tmrRefresh.Enabled
End Sub
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single)
  If Button = 1 Then tmrRefresh.Enabled = Not tmrRefresh.Enabled
  If Button = 2 Then Set Srf = Cairo.CreateSurface(ScaleWidth, ScaleHeight) 'reset the surface
End Sub

Private Sub Form_Resize()
  Set Srf = Cairo.CreateSurface(ScaleWidth, ScaleHeight)
End Sub

Private Sub Form_Terminate()
  If Forms.Count = 0 Then New_c.CleanupRichClientDll
End Sub

Private Sub tmrRefresh_Timer()
Dim i As Integer, cc As Long

  For cc = 1 To 100 'just to perform some more operations within a single timer-event

    For i = 1 To NumPoints 'the next two lines influence the erratic point-movement (just play around)
      pntX(i) = pntX(i) + sgnX(i) * 0.0004 * Abs(pntY(i) - pntX(i))
      pntY(i) = pntY(i) + sgnY(i) * 0.1 / Abs((33 - pntY(i)) / (77 + pntX(i)))
     
      If pntX(i) < ScaleLeft Then pntX(i) = ScaleLeft: sgnX(i) = 1
      If pntX(i) > ScaleLeft + ScaleWidth Then pntX(i) = ScaleLeft + ScaleWidth: sgnX(i) = -1
      If pntY(i) < ScaleTop Then pntY(i) = ScaleTop: sgnY(i) = 1
      If pntY(i) > ScaleHeight + ScaleTop Then pntY(i) = ScaleHeight + ScaleTop: sgnY(i) = -1
    Next i
 
    Static j As Long, k As Single
    k = k + 0.34: If k > 255 Then k = 0: j = j + 1: If j > 5 Then j = 0
    Select Case j
      Case 0: draw RGB(k, 255 - k, 255)
      Case 1: draw RGB(255, k, 255 - k)
      Case 2: draw RGB(255 - k, 255, k)
      Case 3: draw RGB(0, 255 - k, k)
      Case 4: draw RGB(0, 0, 255 - k)
      Case 5: draw RGB(255 - k, k, 0)
    End Select
   
    If cc Mod 10 = 0 Then Srf.DrawToDC hDC
 
  Next cc
End Sub
 
Private Sub draw(ByVal Color As Long)
Dim i As Long, PolyArr() As Single
  ReDim PolyArr(0 To (NumPoints + 3) * 2 - 1)
  For i = 0 To NumPoints - 1 'this is just a normal copy-over
    PolyArr(2 * i) = pntX(i + 1) 'the dst-array has x at even indexes...
    PolyArr(2 * i + 1) = pntY(i + 1) 'and the y-coord at the uneven ones
  Next i
  For i = 0 To 2 'now we add 3 additional points, to "close the circle" (so to say)
    PolyArr(2 * (NumPoints + i)) = PolyArr(2 * i) 'those extra-points are copies ...
    PolyArr(2 * (NumPoints + i) + 1) = PolyArr(2 * i + 1) '...of the first 3 points
  Next i
 
  With Srf.CreateContext 'once we have filled our PolyArr, the rest is pretty simple
    .SetSourceColor Color, 0.05
    .SetLineWidth 0.5
      .PolygonSingle PolyArr, False, splNormal '... using the powerful Poly-call
    .Stroke
  End With
End Sub

The example starts out producing something like that (all Screenshots were reduced in their Pixel-dimensions for smaller upload/download-size - they look even a bit better when directly rendered):



Then, as long as not resetted continues adding more and more alpha-curves (still the same "set" as above, just some more rendered lines on it):



But one can reset the whole thing with the right Mouse and start with a fresh image, ending up with something like this:



Just play around with it (and maybe manipulate the PolyArray-xy-Coords with your own random move-formulas or parameters) ...
Have fun... :-)

Olaf

VB6-TLS1 Simulation

$
0
0
This program was written to simulate a TLS1 handshake connection, with the long term goal being to implement TLS with email. TLS1 (Transport Layer Security) is only slightly different from SSL3 (Secure Sockets Layer) developed by Netscape. TLS was what the IETF adopted based upon SSL3. This evident in the version number used within the actual protocols. SSL3 is version 3.0 and TLS1 is version 3.1. If you examine the Wikipedia Page on the subject (http://en.wikipedia.org/wiki/Transport_Layer_Security), you will see that virtually all major servers and browsers support TLS 1.0. The same cannot be said for SSL, and the IETF has been strongly recommending that support for fallback to SSL2 be dropped as insecure.

To understand how it all works, you should understand a little bit about Cryptography in general. Cryptography is not really that difficult, but it is very convoluted. There are many competing implementations, and not all of them work together. And the standards don't help that much, as they deal with the issues at the lowest level. Working at that level with VB would be a difficult undertaking and probably not work that well. We could purchase a library/control with all the built-in functions for all or most of the standards, and that would have made life simpler. But then we would have been tied to that control for any fixes or updates. The newer Microsoft Operating Systems come complete with several Crypto Libraries built in, called Cryptographic Service Providers (or CSP's). The one we are interested in is the RSA/Schannel Cryptographic Provider, which provides support for TLS. Microsoft discourages applications from using this CSP directly, choosing instead to limit their support to CSP developers and vendors. But that does not mean it cannot be done. It simply means that information on most of the calls is limited.

J.A. Coutts
Attached Files

Simple Proxy-Server (multiple Winsock-Connections per Controls.Add)

$
0
0
Ok, needed a simple one myself for debugging- and some filter-purposes, so here is what I came up with.

It currently already understands https-tunneling - but the whole Proxy-Application is not thoroughly tested yet -
and could need some love from people who would use it for a bit more than just "playing around with things".

Just post back here, in case you add something nice and useful - or fix the one or other bug... ;-)

I surfed with it for a while (in fact more than a few days without noticing or remembering that the small thingy was "On" the whole time) -
so it's not *that* bad a starting-point I'd say (although the sites I visit are not in a broad spectrum... YMMV).

Here's the usual ScreenShot and Code-Zip-Archive.

Have fun with it...

Olaf
Attached Images
 
Attached Files

AnalogClock-Widget-Class (Png-based-Clock-faces + antialiased, ownerdrawn ClockHands)

$
0
0
The Demo-Source needs a reference to the free vbRichClient5-lib, which is located and available on:
http://www.vbRichClient.com/#/en/Downloads.htm

It's currently only the drawing which is solved - so this Control-Class has no Extra-features yet (as e.g. settable Alarm-Times or other "bells and whistles")
But the drawing is done nicely as I think - and the amount of code needed is still pretty small.

Here's the Class-Code (cwClock.cls)
Code:

Option Explicit
 
Private WithEvents W As cWidgetBase, WithEvents tmrTick As cTimer

Private ClockSrf As cCairoSurface
Private PatHour As cCairoPattern, PatMinute As cCairoPattern, PatSecond As cCairoPattern

Private Sub Class_Initialize()
  Set W = Cairo.WidgetBase '<- this is required in each cwImplementation...
      W.Moveable = True
  Set tmrTick = New_c.Timer(490, True)
End Sub
 
Public Property Get Widget() As cWidgetBase
  Set Widget = W
End Property
Public Property Get Widgets() As cWidgets
  Set Widgets = W.Widgets
End Property
 
Private Sub tmrTick_Timer()
  W.Refresh
End Sub

Private Sub W_Paint(CC As vbRichClient5.cCairoContext, ByVal xAbs As Single, ByVal yAbs As Single, ByVal dx_Aligned As Single, ByVal dy_Aligned As Single, UserObj As Object)
Dim CCclk As cCairoContext, D As Date
  If Not Cairo.ImageList.Exists(W.ImageKey) Then Exit Sub
  W.ToolTip = W.Key & vbCrLf & "You can drag me around..."
 
  If ClockSrf Is Nothing Then InitClockSurfaceAndClockHandPatterns
 
  Set CCclk = ClockSrf.CreateContext
  CCclk.Operator = CAIRO_OPERATOR_SOURCE
    CCclk.RenderSurfaceContent W.ImageKey, 0, 0 'clear the last contents with a fresh copy from the Imagelist-Key
  CCclk.Operator = CAIRO_OPERATOR_OVER
 
  CCclk.TranslateDrawings ClockSrf.Width / 2, ClockSrf.Height / 2  'shift the coord-system from the TopLeft-Default to the center
 
  D = Now()
  DrawPat CCclk, PatHour, ((Hour(D) Mod 12) + Minute(D) / 60) * 5 * 6, 1.5
  DrawPat CCclk, PatMinute, (Minute(D) + Second(D) / 60) * 6, 2.75
  DrawPat CCclk, PatSecond, Second(D) * 6, 3.75

  With Cairo.CreateRadialPattern(0, 0, 7, 2.2, -2.2, 0)
    .AddGaussianStops_TwoColors &HAA, vbWhite, , 0.6
    CCclk.ARC 0, 0, 7
    CCclk.Fill , .This
  End With
 
  CC.RenderSurfaceContent ClockSrf, 0, 0, dx_Aligned, dy_Aligned, , W.Alpha
End Sub

Private Sub InitClockSurfaceAndClockHandPatterns()
Set ClockSrf = Cairo.ImageList(W.ImageKey).CreateSimilar(CAIRO_CONTENT_COLOR_ALPHA)
   
    Set PatHour = Cairo.CreateSurfacePattern(Cairo.CreateSurface(15, ClockSrf.Height))
    DrawLineHands PatHour.Surface.CreateContext, ClockSrf.Height, vbBlack, 9, 0.066, 0.22
 
    Set PatMinute = Cairo.CreateSurfacePattern(Cairo.CreateSurface(15, ClockSrf.Height))
    DrawLineHands PatMinute.Surface.CreateContext, ClockSrf.Height, vbBlack, 6, 0.1, 0.29
   
    Set PatSecond = Cairo.CreateSurfacePattern(Cairo.CreateSurface(15, ClockSrf.Height))
    DrawLineHands PatSecond.Surface.CreateContext, ClockSrf.Height, &HAA, 2, 0.044, 0.34
    DrawLineHands PatSecond.Surface.CreateContext, ClockSrf.Height, &HAA, 4, 0.044, -0.17
End Sub

Private Sub DrawLineHands(CC As cCairoContext, SrfHeight, Color, LineWidth, DownFac, TopFac)
  CC.TranslateDrawings CC.Surface.Width / 2, SrfHeight / 2
  CC.DrawLine 0, SrfHeight * DownFac, 0, -SrfHeight * TopFac, , LineWidth + 2, Color, W.Alpha * 0.33 'a thin outer-border with more alpha
  CC.DrawLine 0, SrfHeight * DownFac, 0, -SrfHeight * TopFac, , LineWidth, Color, W.Alpha
End Sub
 
Private Sub DrawPat(CC As cCairoContext, Pat As cCairoPattern, ByVal Deg As Double, Optional ByVal ShadowOffs As Single)
Dim M As cCairoMatrix
  Set M = Cairo.CreateIdentityMatrix
      M.TranslateCoords Pat.Surface.Width / 2, Pat.Surface.Height / 2
      M.RotateCoordsDeg -Deg
  Set Pat.Matrix = M 'we do not rotate the Coord-System of the CC, but instead we rotate that of the pattern
 
  If ShadowOffs Then
    CC.Save
      CC.TranslateDrawings -ShadowOffs, ShadowOffs
      CC.Paint W.Alpha * 0.25, Pat
    CC.Restore
  End If
 
  CC.Paint W.Alpha, Pat 'so what we do in this line, is only "a Blit" (using the already rotated Pattern-Matrix)
End Sub

And here the Form-Code (fTest.frm)
Code:

Option Explicit

Private WithEvents Panel As cWidgetForm 'a cWidgetForm-based Panel-area (followed by 4 clock-Widget-Vars)
Private LaCrosse As cWidgetBase, Flower As cWidgetBase, Square As cWidgetBase, System As cWidgetBase
 
Private Sub Form_Load()
  ScaleMode = vbPixels
  Caption = "Resize Me... (the four Clock-Widgets are individually moveable too)"
  LoadImgResources
 
  Set Panel = Cairo.WidgetForms.CreateChild(Me.hWnd)
      Panel.WidgetRoot.ImageKey = "BackGround"
 
  Set LaCrosse = Panel.Widgets.Add(New cwClock, "LaCrosse", 0.015 * ScaleWidth, 0.16 * ScaleHeight, 501, 501).Widget
      LaCrosse.ImageKey = "ClockLaCrosse" 'same as with the Background of the Panel above - just specify an ImageKey
 
  Set Flower = Panel.Widgets.Add(New cwClock, "Flower", 0.73 * ScaleWidth, 0.01 * ScaleHeight, 501, 501).Widget
      Flower.ImageKey = "ClockFlower" 'same as with the Background of the Panel above - just specify an ImageKey
 
  Set Square = Panel.Widgets.Add(New cwClock, "Square", 0.528 * ScaleWidth, 0.65 * ScaleHeight, 501, 501).Widget
      Square.ImageKey = "ClockSquare" 'same as with the Background of the Panel above - just specify an ImageKey
 
  Set System = Panel.Widgets.Add(New cwClock, "System", 0.3405 * ScaleWidth, 0.726 * ScaleHeight, 501, 501).Widget
      System.ImageKey = "ClockSystem" 'same as with the Background of the Panel above - just specify an ImageKey
      System.Alpha = 0.75 '<- just to show, that this would work too of course
     
  Move Left, Top, Screen.Width / 2, Screen.Width / 2 * 0.66
End Sub

Private Sub Panel_BubblingEvent(Sender As Object, EventName As String, P1 As Variant, P2 As Variant, P3 As Variant, P4 As Variant, P5 As Variant, P6 As Variant, P7 As Variant)
  If TypeOf Sender Is cwClock And EventName = "W_Moving" Or EventName = "W_AddedToHierarchy" Then
    Sender.Widget.Tag = Array(Sender.Widget.Left / ScaleWidth, Sender.Widget.Top / ScaleHeight) 'the Widgets Tag-Prop is a Variant - and can store anything
  End If
End Sub

Private Sub Form_Resize()
  Panel.Move 0, 0, ScaleWidth, ScaleHeight
End Sub

Private Sub Panel_ResizeWithDimensions(ByVal NewWidth As Long, ByVal NewHeight As Long)
  'that doesn't really have anything to do with the analog-clock-widgets, it's just normal "percentual positioning-tricks"
  LaCrosse.Move LaCrosse.Tag(0) * NewWidth, LaCrosse.Tag(1) * NewHeight, NewWidth * 0.25, NewHeight * 0.4
  Flower.Move Flower.Tag(0) * NewWidth, Flower.Tag(1) * NewHeight, NewWidth * 0.16, NewHeight * 0.25
  Square.Move Square.Tag(0) * NewWidth, Square.Tag(1) * NewHeight, NewWidth * 0.18, NewHeight * 0.29
  System.Move System.Tag(0) * NewWidth, System.Tag(1) * NewHeight, NewWidth * 0.032, NewHeight * 0.058
End Sub

Private Sub LoadImgResources() 'just plain image-loading from disk (into the global ImageList, from where it is accessible by Key)
  Cairo.ImageList.AddImage "BackGround", App.Path & "\BackGround.jpg"
 
  Cairo.ImageList.AddImage "ClockLaCrosse", App.Path & "\ClockLaCrosse.png"
  Cairo.ImageList.AddImage "ClockFlower", App.Path & "\ClockFlower.png", 251, 251
  Cairo.ImageList.AddImage "ClockSquare", App.Path & "\ClockSquare.png", 401, 401
  Cairo.ImageList.AddImage "ClockSystem", App.Path & "\ClockSystem.png", 401, 401
End Sub

Private Sub Form_Terminate()
  If Forms.Count = 0 Then New_c.CleanupRichClientDll
End Sub

Attached is the usual ScreenShot and a Zip-File which contains the above Code again (together with a set of Image-ResourceFiles the small Example is based on).
Attached Images
 
Attached Files

Typing Text Directly Into A Picturebox

$
0
0
This VB6 Project allows you to type text directly on a picture much like you do using MS Paint
Attached Files

Tapi Telephone Answering System

$
0
0
Download from the link below. It is too big to upload here.

I wrote this about 12 - 13 years ago when I was on Dial-Up and I had a phone modem (with voice) installed. I wrote it using VB 5 (I think) and on Windows 98

When I had it installed it did incoming and outgoing calls. On incoming it did voice greetings and other voice things. It detects dial tones. Caller could leave message. If I wasn't home this app would call me on my cell phone and inform me of a call I missed giving me the number. I also used this to activate my home security camera system. I would call home and this would answer my call and I would enter a special code which would cause this app to load and run the security software. I built this application as I was learning TAPI and it took me over 6-months to complete. It was my biggest challenge at that time.

Download from below:

http://www.codeavenue.com/downloads/...ringSystem.zip


NOTE: www.codeavenue.com is my own web site

[VB6] Force Foreground Window Demo

$
0
0
The attached project demonstrates how to utilize various APIs to force a window to the foreground. Keep in mind though, that these techniques would probably annoy your users if your window forcibly stealed the focus from whatever they're currently doing. ;)


Name:  ForceForeground.png
Views: 36
Size:  7.0 KB
Attached Images
 
Attached Files

[VB6] clsStrToIntArray.cls - Cast String To Integer Array

$
0
0
This simple class makes it very easy to typecast a String into an Integer array. Treating a String as an array enables some kinds of String processing to be done much quicker than is possible with VB's intrinsic String functions.


clsStrToIntArray.cls
Code:


Option Explicit

Private Const
FADF_AUTO      As Integer = &H1  'An array that is allocated on the stack.
Private Const FADF_FIXEDSIZE As Integer = &H10  'An array that may not be resized or reallocated.

Private Type SAFEARRAY1D    'Represents a safe array. (One Dimensional)
    cDims      As Integer  'The count of dimensions.
    fFeatures  As Integer  'Flags used by the SafeArray.
    cbElements As Long      'The size of an array element.
    cLocks    As Long      'The number of times the array has been locked without a corresponding unlock.
    pvData    As Long      'Pointer to the data.
    cElements  As Long      'The number of elements in the dimension.
    lLbound    As Long      'The lower bound of the dimension.
End Type                    'http://msdn.microsoft.com/en-us/library/ms221482(v=vs.85).aspx

Private Declare Function VarPtrArray Lib "msvbvm60.dll" Alias "VarPtr" (ByRef ArrayVar() As Any) As Long
Private Declare Sub
PutMem4 Lib "msvbvm60.dll" (ByVal Addr As Long, ByVal NewVal As Long)

Private Ptr  As Long
Private
SA1D As SAFEARRAY1D

Private Sub Class_Initialize()
    With SA1D
        .cDims = 1
        .fFeatures = FADF_AUTO Or FADF_FIXEDSIZE
        .cbElements = 2&
        .cLocks = 1&
        .lLbound = 1&
    End With
End Sub


'This should be the first method called right after instantiating
'the class and should be invoked only once per class instance.
'Pass the Integer array that will substitute for the String.


Public Sub InitArray(ByRef IntArray_OUT() As Integer)
    Erase IntArray_OUT
    Ptr = VarPtrArray(IntArray_OUT())
    PutMem4 Ptr, VarPtr(SA1D)
End Sub

'This function typecasts the passed String into an Integer array.
'That is, the characters of the String can be treated as elements
'of the Integer array. Any number of Strings can be typecast to
'the Integer array by calling this function repeatedly. However,
'the array should not be Erased when assigning another String.
'This function fails (returns False) if passed an empty string.


Public Function CastString(ByRef String_IN As String) As Boolean
    Dim
StrLen As Long

    If
Ptr Then
        StrLen = Len(String_IN)
        If StrLen Then
            With
SA1D
              .pvData = StrPtr(String_IN)
              .cElements = StrLen
                CastString = .pvData <> 0&
            End With
        End If
    End If
End Function

Private Sub
Class_Terminate()
    If Ptr Then PutMem4 Ptr, 0&
End Sub


modMain.bas
Code:


Option Explicit

Private Sub
Main()
    Dim aintChars() As Integer, i As Long
    Dim
sControlChars As String, sPrintableChars As String

    sControlChars = Space$(31&)
    sPrintableChars = String$(224&, 0)

    With New clsStrToIntArray
      .InitArray aintChars()

        If .CastString(sPrintableChars) Then
            For
i = LBound(aintChars) To UBound(aintChars)
                aintChars(i) = i + 31&
            Next
            Debug
.Print """" & sPrintableChars & """"
        End If

        If
.CastString(sControlChars) Then
            For
i = LBound(aintChars) To UBound(aintChars)
                aintChars(i) = i
            Next
            Debug
.Print """" & sControlChars & """"
        End If
    End With
End Sub



Attached Files

Vb6 - Word Search App (Scrabble Solver?) *includes Wildcard usage

$
0
0
Name:  Word Search.jpg
Views: 68
Size:  41.2 KB

First off...My apologies if "Word Search" is the incorrect term for this, I have no clue what the official name for this type of app is. people usually relate it to Scrabble.

Here is my take/idea on making a word search/"Scrabble solver" app that can handle wildcards. I created this a while back, and updated it a bit since then. It is not rapid fast sometimes when looking for 10 or more letters, or when using a lot of wildcards, but i find it pretty fast if using it as you would in any scrabble combination.

If you have a link to one you've created or seen, let me know; i'd like to view the source.


:eek2:Note: This includes a dictionary. The program is built around the current dictionary words in relation to the amount of duplicate letters in a word(maximum 7) and word length(maximum 15).
Attached Images
 
Attached Files

Word extractor program.

$
0
0
Hi all
This is my vague program to extract the words that are used in a text with no repetition.
It does the purpose for me at this level. I liked to share with you hoping someone have the time to add some more functions.
thank you.
Attached Files

AutoComplete (Using the IAutoComplete interface)

$
0
0
This project is intended to demonstrate how to implement the IAutoComplete interface to VB6.

It provides more features than the "SHAutoComplete" API.

For example to determine whether the drop-down list is dropped down or not.
But the most important feature is that you can define custom sources. (by a simple string array)

At design time (IDE) there is only one dependency. (AutoCompleteGuids.tlb)
But for the compiled .exe there are no dependencies, because the .tlb gets then compiled into the executable.

Notes:
- There is no way to uninitialize the autocomplete object. You can only disable it. Setting the autocomplete object to nothing has therefore no effect and is not recommended. Anyhow, the autocomplete object will be automatically uninitialized when the TextBox (or any other edit control) receives the WM_DESTROY message.
- Use modeless forms to enable the user to use the mouse on the drop-down suggest list as else only keyboard inputs will work on modal forms.

List of revisions:
Code:

13-Aug-2013
- Fixed a bug that the application will crash when there is an empty string in the custom source.
12-Aug-2013
- First release.

Attached Files

Pinboard (plus bonus - 100 free pushpins!)

$
0
0
This project was made per a request by a member who needed an application that user could load an image and push pins into it and have a descriptive label for the pins.
Attached Files

VB6 - ThinDavApi, Cloud Storage for the Masses

$
0
0
ThinDavApi

ThinDavApi is a small DAV client API based on MSXML.

Its main limitations are:

  • No support for DAV resource locking.
  • No partial-resource reading or writing, it deals with whole resources.
  • No chunked transfer support, so it is better suited for smaller resources or situations where your application can afford the memory to hold a medium sized resource in memory.
  • Only supports a few common resource properties, does not support modifying properties of existing resources.


ThinDavApi refers to resources as "files" and collection resources as "directories" but this is merely an abstraction since they are really BLOBs of data. ThinDavApi can read/write binary data or UTF-8 text, handling text translation to and from Windows Unicode (UTF-16LE) via MSXML's facilities.


Purpose

ThinDavApi is meant to offer programmers a simple way to implement "cloud storage" within applications. There are many inexpensive and even free WebDAV hosting services you might use for a number of purposes. Examples might include submitting and/or retrieving updated data, remote logging, error reporting, and contact requests. This allows you to completely replace the use of SMTP email or FTP, both of which can suffer from insecure data transfer and firewall or ISP blocking problems. Very few firewalls will block WebDAV traffic over standard HTTP (port 80) or HTTPS (port 443).

ThinDavApi does not require any "web folder" setup and doesn't use any of the Microsoft WebDAV filesystem redirectors. When used with MSXML 3.0 which is perfectly adequate ThinDavApi can work on any version of Windows as far back as Windows 95. On an older OS you'd need to deploy MSXML 3.0 unless it was already installed by another product (e.g. IE 5.x). It is installed on every OS from a fully patched Win2k SP4 installation on up and is patched with bug fixes via Windows Update.

Some limited testing has been done using MSXML 6.0 but considering its deployment issues any advantages it offers probably don't warrant its use. However there might be a small performance boost in doing so as long as you only target systems where MSXML 6.0 is preinstalled or you are willing to deploy it (Win2K SP4 through WinXP SP2).


Aync Operation

Since the main reason for your programs to use WebDAV is to access a remote datastore over the Internet, synchronous operations aren't really practical. Because of this ThinDavApi does not support them.

All requests you make through ThinDavApi calls end by raising a Complete event. You can determine success or failure and retrieve results in your event handler.

Timeouts should be handled in your program using a timer of some kind. When a request takes too long you can call AbortRequest, and when Complete is subsequently raised you can test for the Aborted property.


Thin Wrapper

DAV is an XML-based protocol on top of HTTP.

ThinDavApi is a fairly thin wrapper on the MSXML library. Because of this request completion status information is reported as HTTP results (status code and status text) and some requests provide HTTP response headers after minimal parsing.

You don't need any XML knowledge to use ThinDavApi unless you need to do some advanced debugging or to add or modify features of ThinDavApi. Your best reference on DAV is probably RFC 2518, which covers all of the things ThinDavApi supports (and more).


Supported Resource Properties

ThinDavApi will make a PROPFIND request through its GetDir() method which returns:

  • Name - simple name of a file or directory. String.
  • FullName - fully qualified path of a file or directory below the ThinDavApi BaseURL property. String.
  • LastModified - timestamp. Date.
  • ContentType - MIME type (only files). String.
  • Length - in bytes at the server (only files). Long.
  • IsFile - False for a directory and True for a file. Boolean.


The returned XML is parsed into a Variant property DirEntries. DirEntries is an array of Variant arrays, one row for the file or directory queried on and one row for each "child" resource unless the call specifies ChildInfo = False. Each column in these inner "DirEntry" arrays corresponds to one of the supported properties, translated to an appropriate Automation type (e.g. Date, Long, Boolean, or String in VB terms).

ThinDavApi also accepts an optional ContentType to use when creating a file by calling PutFileBytes() or PutFileText(), or if none is supplied a default is used.


Source Code, Usage

The ThinDavApi.cls module contains a block of comments describing its properties, methods, and events.

It has been provided here as part of a demo Project "ThinDAVMan" which makes use of most of its supported operations. In particular I've tried to show how to handle the async method calls and implement request timeouts using a Timer control. The ThinDAVMan.zip archive is attached to this post.


From Here

ThinDavApi 1.0 posted here was taken from another WebDAV client class that is at version 3.1, so it has had a lot of testing and debugging done already. However it may still have flaws including some that won't show up until somebody tries to use it with some server I haven't used yet. Despite the WebDAV standard I have found variations out there which required subtle workarounds.

The goal with ThinDavApi was to make a basic client that can be compiled into a VB6 program or used from VBA. This could also be the basis for a more complete WebDAV client that adds locking and other features, though at that point you may want to look at 3rd party commercial libraries that do a great job.
Attached Files

Push Pin Board

$
0
0
This project was made per a request by a member who needed an application that user could load an image and push pins into it and have a descriptive label for the pins.
Attached Files

VB6 - Test Crypto Functions

$
0
0
As promised, I have attached a VB6 Cryptography Test program originally developed in C++ by:
Michael Jung 2004
Juan Lang 2006
Vijay Kiran Kamuju 2007
The original C++ code is included as TestC++.txt.

Not all functions behave exactly the same as predicted, and much of that I attribute to the fact that Encryption and Decryption routines are done using strings rather than byte arrays. The reason for doing this is that in VB6, data is usually sent and received as string information.

The Test NULL Provider routine has not been implemented at all. Of the first 4 tests that I converted, 3 of them did not behave as predicted. The bulk of the routine seemed to be based on testing for failures rather than productive code, so I abandoned the effort.

I also made no attempt to provide support for XP and older operating systems as the original authors did. There were a lot of system calls that just were not supported by these older systems, and I had no way of testing them.

Most of the system calls have built in error trapping, and would not be present in this format in final working code. But these routines are built as demonstration test code, and a full description of the error is useful. A full list of the 0x80090000 level errors is included in the module.

I am by no means a Cryptographic expert, but I will attempt to address any questions.

J.A. Coutts
Attached Files

Round Colorful Forms

$
0
0
Ok in its raw form this is really quite useless but it contains several interesting parts that can be put to greater use

With this code you can create a round, color changing form that can be moved freely.

Thank you SamOscarBrown for your circle code and Microsoft for helping me get the form movable

you will need a form with a text box and a timer. I named the form frmRound

seeing it work really blew my mind! :eek2:

Code:

Private Declare Function SendMessage Lib "User32" _
                        Alias "SendMessageA" (ByVal hWnd As Long, _
                                              ByVal wMsg As Long, _
                                              ByVal wParam As Long, _
                                              lParam As Any) As Long
Private Declare Sub ReleaseCapture Lib "User32" ()

      Const WM_NCLBUTTONDOWN = &HA1
      Const HTCAPTION = 2

    Option Explicit
    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 SetWindowRgn Lib "User32" (ByVal hWnd As Long, ByVal hRgn As Long, ByVal bRedraw As Long) As Long
 

   
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, _
                                X As Single, Y As Single)
        Dim lngReturnValue As Long

        If Button = 1 Then
            Call ReleaseCapture
            lngReturnValue = SendMessage(frmRound.hWnd, WM_NCLBUTTONDOWN, _
                                        HTCAPTION, 0&)
        End If
      End Sub

    Private Sub Form_DblClick()
      Unload Me
    End Sub
    Private Sub Form_Load()
        Dim lngRegion As Long
        Dim lngReturn As Long
        Dim lngFormWidth As Long
        Dim lngFormHeight As Long
        Me.Width = Me.Height
       
        lngFormWidth = Me.Width / Screen.TwipsPerPixelX
        lngFormHeight = Me.Height / Screen.TwipsPerPixelY
        lngRegion = CreateEllipticRgn(0, 0, lngFormWidth, lngFormHeight)
        lngReturn = SetWindowRgn(Me.hWnd, lngRegion, True)
Label1.Left = (Me.Width / 2) - (Label1.Width / 2)
Label1.Top = (Me.Height / 2) - (Label1.Height / 2)
    End Sub
    Private Sub Label1_Click()
      Unload frmRound
    End Sub
    Private Sub Timer1_Timer()
  Static iColor As Integer
  Select Case iColor
  Case 0: Me.BackColor = RGB(255, 0, 0)  ' Red
  Case 1: Me.BackColor = RGB(255, 165, 0) ' Orange
  Case 2: Me.BackColor = RGB(255, 255, 0) ' Yellow
  Case 3: Me.BackColor = RGB(0, 128, 0)  ' Green
  Case 4: Me.BackColor = RGB(0, 0, 255)  ' Blue
  Case 5: Me.BackColor = RGB(128, 0, 128) ' Purple
  End Select
  iColor = iColor + 1
  If iColor > 5 Then iColor = 0
End Sub

VB6 - Jet UserRoster, Connection Control, Backup

$
0
0
Background

When Jet 4.0 came out it offered many new features that go beyond those in Jet 3.x and the Jet 4.0 OLEDB Provider exposes many of them through ADO and a few more through JRO.

Some of these can be useful in getting a Jet database closed so you can back it up, as well as another way to do the backup that runs a compact and repair operation to reclaim space and fix up indexes.


User Roster

It is possible for programs to retrieve a list of active connections open on a database. Since this even shows which computer each connection comes from on a shared database it can be useful in getting persistent opens closed.


Connection Control

A program can invoke Connection Control to prevent new connections to a database from being established. The idea is to get the database closed for backup or other maintenance through attrition, without interfering with existing activity.

Invoke this and put the word out. As connections are closed eventually you can perform the database maintenence once the last man standing... sits.


CompactDatabase

A method of the JRO.JetEngine object you can call to compact an existing database into a new database. Useful as a backup step because it reclaims unused "holes" in the MDB file created by lots of updates and deletes, compacts indexes, and repairs some kinds of internal broken links.


Backup Demo

This demo has two programs:


DbDemo

A small program that opens a database (creating it if necessary) and does some simple queries and updates. It can be run passing a database folder on the command line if you want to test access over the network to a database on a file share.


BackupDemo

A small program that opens the database (creating it if necessary) and sets Jet Connection Control to prevent new connections. Then it polls the database for a list of current users/connections and displays them. Once the connection count is one (just this program) it closes the current database, copies it as a backup, and uses JRO to compact the backup to create a new "current" database.


Running The Demo

Open each Project and compile (Make) it.

Run DbDemo and create a few records.

Name:  sshot0.png
Views: 36
Size:  9.8 KB

Run a second copy of DbDemo.

Run BackupDemo. Observe the users list.

Name:  sshot1.png
Views: 46
Size:  11.3 KB

In the second screenshot there are three connections listed. One of these is an instance of DbDemo running on another computer (ATOMANT in this case). Two more connections show from the first computer (SNITZ), one being a local instance of DbDemo and the other being BackupDemo itself.

All of them show as the user "Admin" since this isn't a secured Jet database. Jet User/Group security is beyond the scope of this writeup.

Close a copy of DbDemo and the list shown in BackupDemo should change to reflect this.

Close the other copy of DbDemo.

Name:  sshot2.png
Views: 32
Size:  10.7 KB

Try starting a new DbDemo copy. It should fail with an error message describing the database's state, which currently blocks attempts to open or lock it.

Name:  sshot4.png
Views: 31
Size:  10.0 KB

When the last DbDemo is gone, BackupDemo should enable its "Back Up MDB" button. Click on this to start the compact & backup process.

Name:  sshot3.png
Views: 36
Size:  18.1 KB

At this point BackupDemo is done. Users can start running DbDemo again, using the compacted database. The original database has been renamed and can be copied off to archival storage as desired.


Remarks

This is a demonstration providing sample code. For a real application you might do things differently, such as creating backup MDB names with timestamps in them. You might create a backup utility with no user interface that can be scheduled to run via Task Scheduler and just "takes off" and does the backup once all other users have closed out.

You might even add some mechanism to send messages from your backup utility to any running copies of the database client application. These could warn the users to finish up and close out for a while, and let them know when the backup is complete.

Don't try to back up directly to a slow network share. It is also best to run your backup utility directly on the box hosting the database. You can't always do this, but it makes the process much quicker and more reliable when possible.
Attached Images
     
Viewing all 1478 articles
Browse latest View live


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