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

VB6 - Hidden Conversations V3

$
0
0
On the surface, Version 3 looks very much like Versions 1 & 2. Underneath the hood however, cSocket2.cls has been replaced by the slimmer and faster NewSocket.cls, as well as utilizing an updated clsCrypto.cls. Versions 1 & 2 had difficulty working with systems that did not utilize the Latin character set (such as Chinese or Arabic), and the addtion of these 2 classes now makes Hidden Conversations Unicode compatible. It is NOT Unicode compliant.

Like Version 2, Version 3 incorporates a 2048 bit/256 byte Public/Private key pair to initiate the conversation. Using the Public key, the Client sends a random 32 byte encrypted number to the Host. The Host then decrypts that number using the Private key. The Host then sends a Private Key encrypted message to the Client, who decrypts it using the Public key to verify that the Host is the holder of the private key. And you can change that key pair at any time. Of course the Public key has to be sent by alternate means to the Client after a change, as only the Host is capable of creating new keys.

If only one key is present, Hidden Conversations will automatically use that key. However, some Clients will need to converse with more than one Host, and provision has been made to deal with that. In addition to the IP Address and Port, the key file name needs to be stored and recovered. If no Keys are present, the program will complain but will still load. However, without a key you will not be able to communicate.

All this security would be useless if an unauthorized person gains physical access to the resident computer. The password is saved in the registry as a hashed number.

To permit longer packets to be sent, the packets are formatted with a record header that includes the packet length along with version information.

J.A. Coutts
Attached Files

Nice Textboxes version2

$
0
0
Why some functions are so difficult to find. I would like to have some controls without the restrictions for using...this or that themes..manifests or other bad habits..
So i wrote some textboxes. All of them are based in glist (latest edition).
Here I have a TextViewer to display text with line spacing as we wish and wrapping or not. The only limitation is has no drag and drop,and not for this version undo control.. Because is the glist behind this TextViewer can scroll the text holding down the mouse button and doing a move anywhere in the window of the glist

I also have some textboxes with one line only
- a Combobox with auto complete function (shows/hide a listbox of values)
- a Spinner Textbox for a long value. We can alter the value by clicking and writing, by using up down buttons, by using the scroll bar.
- a simple textbox wit centered text that can be edit ...as is, we can use it without edit, just showing text
- a button that can be slide the caption and perform the "click" (by panning right) (2 buttons using here, one to alter the wrapping of the textViewer, and the other to show/hide the paragraphs marks..
- A floating list of values to put in Spinnet TextBbox. We can "call" like a popup menu. See above the spinner textbox, when you right click.

New Version
- ComboBox - works fine.
- CheckBox
- Info popup in a textbox demonstration
for document type
- Simple undo (undo for deleted marked text and for paragraph changes), use control Z
- Control A (select all)
- Double click select word
- Drag and Drop
you can move or copy from and to same document. double click a marked text show the drag icon. This is not the same as holding down the mouse and move. This function is for moving like using a stick the scroll bar.

That's All
...for now
Attached Images
 
Attached Files

[VB6] TaskDialogIndirect: Complete class implementation of Vista+ Task Dialogs

$
0
0
cTaskDialog


cTaskDialog is the sequel to my previous TaskDialogIndirect project, mTaskDialog. This version adds support for all TaskDialogIndirect features, including the progress bar, timer feedback, updating the text and icons while the dialog is open, and events for all the notifications. It's also much easier to use.

What is TaskDialog?

TaskDialog, introduced in Windows Vista, is a massive upgrade to the MessageBox. While not as simple, it offers a huge array of features... custom icons, custom button text, command link style buttons, expanded info button, a footer, a checkbox for 'i read this' or 'don't show this again' type messages, radio buttons, hyperlinks, and more.

This project can be used to create a simple messagebox like the older ones, to an extremely complex dialog with all the features mentioned, even all at once!

Before using cTaskDialog

The TaskDialog was introduced with version 6.0 of the common controls, with Windows Vista. That means a manifest is required for your compiled application, and for VB6.exe in order to use it from the IDE. In addition, your project must start from Sub Main() and initialize the common controls before any forms are loaded. The sample project includes Sub Main(), and see LaVolpe's Manifest Creator to create the manifests.

Setting Up cTaskDialog

Once you've got a project using the modern common controls, cTaskDialog is similar in use to a lot of other class modules, like the other common controls.

To initialize the class, put the following at the start of a form and in the Form_Load code:
Code:

Private WithEvents TaskDialog1 As cTaskDialog

Private Sub Form_Load()
Set TaskDialog1 = New cTaskDialog
End Sub

Now, you're all ready to begin using it. Let's start with a simple messagebox like we've seen before.



Creating this box is very straightforward. Unlike the previous incarnation, you don't have to worry about anything you're not using.

Code:

Private Sub Command2_Click()

With TaskDialog1
    .MainInstruction = "This is a simple dialog."
    .CommonButtons = TDCBF_YES_BUTTON Or TDCBF_NO_BUTTON
    .IconMain = TD_INFORMATION_ICON
    .Title = "cTaskDialog Project"
   
    .ShowDialog

    If .ResultMain = TD_YES Then
        Label1.Caption = "Yes Yes Yes!"
    ElseIf .ResultMain = TD_NO Then
        Label1.Caption = "Nope. No. Non. Nein."
    Else
        Label1.Caption = "Cancelled."
    End If
End With
End Sub

That's all it takes for a basic messagebox. The .Init() call resets the dialog. If you want to re-use all the previous settings and just change a couple things, it can be skipped.

Now that basic usage is covered, let's get down to what you really came for: advanced features!

Here's a few basic changes that make a much more fancy looking dialog:

Code:

    .Init
    .MainInstruction = "You're about to do something stupid."
    .Content = "Are you absolutely sure you want to continue with this really bad idea?"
    .CommonButtons = TDCBF_YES_BUTTON Or TDCBF_NO_BUTTON
    .IconMain = TD_SHIELD_WARNING_ICON 'TD_INFORMATION_ICON
    .Title = "cTaskDialog Project"
   
    .ShowDialog

This produces the following:




The TaskDialog supports several special shield icons that create the colored bar uptop. If you use a regular icon, or a custom icon, it will look like the dialog on the right.

All the other text fields are added the same way, so I'm just going to skip over those. One thing to note, with expanded information set, the little expando button appears automatically when you set those fields and requires no additional code to operate; where it appears is set by a flag, which is described later. Also note that the major text fields can be changed while the dialog is open, just set it again the same way.

One of the big features is the ability to customize the text on the buttons. Due to limitations in VB, I've implemented them by using a .AddButton function. You can assign the button the same id as one of the regular buttons, or give it a unique id. Custom buttons can be removed with .ClearCustomButtons so a full Init() call isn't needed.

Code:

With TaskDialog1
    .Init
    .MainInstruction = "You're about to do something stupid."
    .Content = "Are you absolutely sure you want to continue with this really bad idea?"
    .IconMain = TD_INFORMATION_ICON
    .Title = "cTaskDialog Project"
    .AddCustomButton 101, "YeeHaw!"
    .AddCustomButton 102, "NEVER!!!"
    .AddCustomButton 103, "I dunno?"
   
    .ShowDialog

    Label1.Caption = "ID of button clicked: " & .ResultMain
End With




Note that we have removed the .CommonButtons. If you specify buttons there as well, they will appear in addition to your custom buttons.

Radio buttons are added the exact same way as common buttons; and the ID of the radio button selected is found in the .ResultRad property.

Code:

    .AddRadioButton 110, "Let's do item 1"
    .AddRadioButton 111, "Or maybe 2"
    .AddRadioButton 112, "super secret option"
   
    .ShowDialog

    Label1.Caption = "ID of button clicked: " & .ResultMain
    Label2.Caption = "ID of radio button selected: " & .ResultRad



One of the other biggies are Hyperlinks. These require a few additional steps. First, you need to include TDF_ENABLE_HYPERLINKS in the .Flags property. Then, you add in the hyperlink as normal html, but the url needs to be in quotes, so you'll need chr$(34). Then you'll need to use one of the events for the class. The most common thing to do is just execute the link, so that's what's shown here, but you could also get the URL back from the pointer and do something else with it. You must use ShellExecuteW, not ShellExecuteA (which is normally what just plain ShellExecute points to). The declare is included in the sample project.

Code:

With TaskDialog1
    .Init
    .MainInstruction = "Let's see some hyperlinking!"
    .Content = "Where else to link to but <a href=" & Chr(34) & "http://www.microsoft.com" & Chr(34) & ">Microsoft.com</a>"
    .IconMain = TD_INFORMATION_ICON
    .Title = "cTaskDialog Project"
    .CommonButtons = TDCBF_CLOSE_BUTTON
    .Flags = TDF_ENABLE_HYPERLINKS
   
    .ShowDialog

    Label1.Caption = "ID of button clicked: " & .ResultMain
    Label2.Caption = "ID of radio button selected: " & .ResultRad
   
End With

Private Sub TaskDialog1_HyperlinkClick(ByVal lPtr As Long)

Call ShellExecuteW(0, 0, lPtr, 0, 0, SW_SHOWNORMAL)

End Sub



Let's talk about custom icons. You can have a custom icon for both the main icon and the footer icon.
Thanks to the brilliant idea of Schmidt over here, the option to specify an icon id from either shell32.dll or imageres.dll, the two main Windows icon libraries, has been added. This massively expands the icons you can show without having to provider an hIcon.
TDF_USE_SHELL32_MAINICONID, TDF_USE_SHELL32_FOOTERICONID
TDF_USE_IMAGERES_MAINICONID, TDF_USE_IMAGERES_FOOTERICONID
Simply specify if you're going to use one of those sources by adding the above to the flags (depending on which you're using for one; only one for main and one for footer), and set the icon to the index you want. NOTE: These do not run from 0-# of icons, so if your icon browser is telling you that, you need to use a different one, otherwise the dialog may display the wrong icon, or not show at all if the id doesn't exist.

Code:

With TaskDialog1
    .Init
    .MainInstruction = "Show me the icons!"
    .Content = "Yeah, that's the stuff."
    .Footer = "Got some footer icon action here too."
    .Flags = TDF_USE_SHELL32_MAINICONID Or TDF_USE_IMAGERES_FOOTERICONID
    .IconMain = 18
    .IconFooter = 24
    .Title = "cTaskDialog Project"
    .CommonButtons = TDCBF_CLOSE_BUTTON
   
    .ShowDialog
End With




You can also specify a truly custom icon from a .ico file on disk, in your resource file, or anywhere you can get an hIcon from.
The sample project uses a method I adapted from Leandro Ascierto's cMenuImage. It gets around VB's limitations on icons by adding them to the resource file as a custom resource, and not an icon. This way, you can include any size and any color depth and any number of them inside the .ico. Then, the ResIcontoHICON function will give you the hIcon you need for cTaskDialog. But remember, any other function returning an hIcon will work. Icons can also be updated while the dialog is open by another .IconMain= or .IconFooter= statement. You can use a standard icon for main and custom for footer, and vice versa, or both. When you're going to use a custom icon, you must include TDF_USE_HICON_MAIN/TDF_USE_HICON_FOOTER in the flags.
The icon size can't really be changed much; the main icon will be distorted but not larger if you give it a larger size, although you can make it a smaller size. The footer icon won't change at all.

Code:

With TaskDialog1
    .Init
    .MainInstruction = "What time is it?"
    .Content = "Is is party time yet???"
    .Footer = "Don't you love TaskDialogIndirect?"
    .Flags = TDF_USE_HICON_MAIN Or TDF_USE_HICON_FOOTER
    .IconMain = ResIconTohIcon("ICO_CLOCK", 32, 32)
    .IconFooter = ResIconTohIcon("ICO_HEART", 16, 16)
    .Title = "cTaskDialog Project"
    .CommonButtons = TDCBF_CLOSE_BUTTON
   
    .ShowDialog

    Label1.Caption = "ID of button clicked: " & .ResultMain

   
End With



Due to the severe limitations on what icons can be put in a VB project res file in the actual icon group, I strongly recommend a different method. But if you want to try anyway I believe you can just set pszIcon.. to its ID, and not set any of the icon flags.

The last basic feature is the verification checkbox. Here's an example with that, and all the other text fields. Note also what happens in this example when no buttons are specified anywhere: the OK button appears by default.

Code:

With TaskDialog1
    .Init
    .MainInstruction = "Let's see all the basic fields."
    .Content = "We can really fit in a lot of organized information now."
    .Title = "cTaskDialog Project"
    .Footer = "Have some footer text."
    .CollapsedControlText = "Click here for some more info."
    .ExpandedControlText = "Click again to hide that extra info."
    .ExpandedInfo = "Here's a whole bunch more information you probably don't need."
    .VerifyText = "Never ever show me this dialog again!"
   
    .IconMain = TD_INFORMATION_ICON
    .IconFooter = TD_ERROR_ICON
   
    .ShowDialog
   
    Label1.Caption = "ID of button clicked: " & .ResultMain
End With



One of the major stylistic differences are the CommandLink buttons. When using the Command Link style, the first line is considered the main text, and lines are made into sub-text. Note that the line is broken with vbLf only; not vbCrLf. vbCrLf results in the text not being smaller on Win7 x64, I haven't tested other systems but it should be the same.
With the custom button sample from above, these changes are made:

Code:

    .Flags = TDF_USE_COMMAND_LINKS
    .AddCustomButton 101, "YeeHaw!" & vbLf & "Put some additional information about the command here."



and that is what the dialog now looks like.

That covers all the basic functionality.

Advanced Features

The TaskDialog supports having a progress bar, both regular and marquee. To enable it, include the TDF_SHOW_PROGRESS_BAR or the TDF_SHOW_MARQUEE_PROGRESS_BAR flag (you can switch back and forth between them while the dialog is open if you want). Getting it to show up is the easy part, linking it to actual events in your program is where it gets a little tricky. There's some events that are provided that will help out...

TaskDialog_DialogCreated is triggered when the dialog is displayed, then all the buttons, the radio buttons, the expando button, the checkbox, and hyperlinks all have events when the user clicks them. In addition to that, TaskDialog_Timer is sent approximately every 200ms and includes a variable telling you how many ms has elapsed since the dialog appeared, or since it was reset with the .ResetTimer() call. The example shows a basic counter, but you can go further and enable/disable buttons and use hyperlinks to control things too.

Code:


Private bRunProgress As Boolean
Private lSecs As Long


With TaskDialog1
    .Init
    .MainInstruction = "You're about to do something stupid."
    .Content = "Are you absolutely sure you want to continue with this really bad idea? I'll give you a minute to think about it."
    .IconMain = TD_INFORMATION_ICON
    .Title = "cTaskDialog Project"
    .Footer = "Really, think about it."
    .Flags = TDF_USE_COMMAND_LINKS Or TDF_SHOW_PROGRESS_BAR Or TDF_CALLBACK_TIMER
    .AddCustomButton 101, "YeeHaw!" & vbLf & "Put some additional information about the command here."
    .AddCustomButton 102, "NEVER!!!"
    .AddCustomButton 103, "I dunno?"
    .VerifyText = "Hold up!"
    bRunProgress = True
   
    .ShowDialog

    Label1.Caption = "ID of button clicked: " & .ResultMain
End With


Private Sub TaskDialog1_DialogCreated(ByVal hWnd As Long)
Timer1.Interval = 1000
Timer1.Enabled = True
TaskDialog1.ProgressSetRange 0, 60

End Sub


Private Sub TaskDialog1_Timer(ByVal TimerValue As Long)
If lSecs > 60 Then
    Timer1.Enabled = False
    bRunProgress = False
Else
    TaskDialog1.ProgressSetValue lSecs
    TaskDialog1.Footer = "You've been thinking for " & lSecs & " seconds now..."
End If

End Sub

Private Sub TaskDialog1_VerificationClicked(ByVal Value As Long)
If Value = 1 Then
    Timer1.Enabled = False
    bRunProgress = False
Else
    bRunProgress = True
    Timer1.Enabled = True
End If
End Sub

Private Sub Timer1_Timer()
lSecs = lSecs + 1
End Sub




That's the basic feature set. The class allows an infinite number of customizations to take place from here.
Attached Files

Nice Textboxes version2.1 Plus Varius Selectors

$
0
0
Why some functions are so difficult to find. I would like to have some controls without the restrictions for using...this or that themes..manifests or other bad habits..
So i wrote some textboxes. All of them are based in glist (latest edition).
Here I have a TextViewer to display text with line spacing as we wish and wrapping or not. The only limitation is has no drag and drop,and not for this version undo control.. Because is the glist behind this TextViewer can scroll the text holding down the mouse button and doing a move anywhere in the window of the glist

I also have some textboxes with one line only
- a Combobox with auto complete function (shows/hide a listbox of values)
- a Spinner Textbox for a long value. We can alter the value by clicking and writing, by using up down buttons, by using the scroll bar.
- a simple textbox wit centered text that can be edit ...as is, we can use it without edit, just showing text
- a button that can be slide the caption and perform the "click" (by panning right) (2 buttons using here, one to alter the wrapping of the textViewer, and the other to show/hide the paragraphs marks..
- A floating list of values to put in Spinnet TextBbox. We can "call" like a popup menu. See above the spinner textbox, when you right click.

Version 2
- ComboBox - works fine.
- CheckBox
- Info popup in a textbox demonstration
for document type
- Simple undo (undo for deleted marked text and for paragraph changes), use control Z
- Control A (select all)
- Double click select word
- Drag and Drop
you can move or copy from and to same document. double click a marked text show the drag icon. This is not the same as holding down the mouse and move. This function is for moving like using a stick the scroll bar.

Last Version
This version is almost identical to the one before. When we mark text a up or down movement of caret (or cursor) unmark the text. A second touch is about the showing of scrollbar. It was a small appearance of that scroll bar when showing the form who hold the control, that it isn't pretty, especially for that glists where the items are less or equal of viewing lines. A last touch was for document (textviewer class) for the example with file selector, a missing +1 chenage the line for caret in a drag over event when no header used (drawing) in the glist.

For the Selector Example.
Open Load File Selector and open a txt file (UNICODE or not). A new form opens with one text box (the standard one) and one from textviewer class (a wrapper class for glist4 listbox control). From file menu check enable to write and check the other options to see what happen. Also the textviewer resize as we resize the window, and the wrapping is fast, very fast (enable it from file menu). Also see that classic textbox has flickering. No flickering for Textviewer.

If anyone want the scroll bar only, then that code can be found it in Scrollio example, (I wrote the scroll bar for the scrollio control, as an image/drawing viewer, and then I do a merge of that code to the glist, the one with ...millions of items...that I posted here some months ago).

I have started the major task to, and I have exclude file,folder, color and font selectors from M2000 Environment and Interpreter, and now is time to through the classic textbox.



That's All
...for now

Look #4 for latest versions
Attached Images
 
Attached Files

Nice Textboxes Plus Varius Selectors

$
0
0
Why some functions are so difficult to find. I would like to have some controls without the restrictions for using...this or that themes..manifests or other bad habits..
So i wrote some textboxes. All of them are based in glist (latest edition).
Here I have a TextViewer to display text with line spacing as we wish and wrapping or not. The only limitation is has no drag and drop,and not for this version undo control.. Because is the glist behind this TextViewer can scroll the text holding down the mouse button and doing a move anywhere in the window of the glist

I also have some textboxes with one line only
- a Combobox with auto complete function (shows/hide a listbox of values)
- a Spinner Textbox for a long value. We can alter the value by clicking and writing, by using up down buttons, by using the scroll bar.
- a simple textbox wit centered text that can be edit ...as is, we can use it without edit, just showing text
- a button that can be slide the caption and perform the "click" (by panning right) (2 buttons using here, one to alter the wrapping of the textViewer, and the other to show/hide the paragraphs marks..
- A floating list of values to put in Spinnet TextBbox. We can "call" like a popup menu. See above the spinner textbox, when you right click.

Version 2
- ComboBox - works fine.
- CheckBox
- Info popup in a textbox demonstration
for document type
- Simple undo (undo for deleted marked text and for paragraph changes), use control Z
- Control A (select all)
- Double click select word
- Drag and Drop
you can move or copy from and to same document. double click a marked text show the drag icon. This is not the same as holding down the mouse and move. This function is for moving like using a stick the scroll bar.

Last Version
This version is almost identical to the one before. When we mark text a up or down movement of caret (or cursor) unmark the text. A second touch is about the showing of scrollbar. It was a small appearance of that scroll bar when showing the form who hold the control, that it isn't pretty, especially for that glists where the items are less or equal of viewing lines. A last touch was for document (textviewer class) for the example with file selector, a missing +1 chenage the line for caret in a drag over event when no header used (drawing) in the glist.

For the Selector Example.
Open Load File Selector and open a txt file (UNICODE or not). A new form opens with one text box (the standard one) and one from textviewer class (a wrapper class for glist4 listbox control). From file menu check enable to write and check the other options to see what happen. Also the textviewer resize as we resize the window, and the wrapping is fast, very fast (enable it from file menu). Also see that classic textbox has flickering. No flickering for Textviewer.

If anyone want the scroll bar only, then that code can be found it in Scrollio example, (I wrote the scroll bar for the scrollio control, as an image/drawing viewer, and then I do a merge of that code to the glist, the one with ...millions of items...that I posted here some months ago).

I have started the major task to, and I have exclude file,folder, color and font selectors from M2000 Environment and Interpreter, and now is time to through the classic textbox.



That's All
...for now

Look #5 for latest versions
Attached Images
 
Attached Files

[VB6] NetWkstaUserEnum API wrapper

$
0
0
While most people won't need this I've been seeing threads requesting it lately.

A common problem is that the results of a query against a Jet MDB's active user roster via ADO and SCHEMA_ID_ROSTER returns database client user names and client machine names. But you let all users logon as Jet user "Admin." So you want to try to get Windows logon user names from the machine names.


What NetWkstaUserEnum Does

NetWkstaUserEnum() is a function used to get a list of logged on users at a machine by name. You can also pass it an empty name to get the local machine's logged on users.

This function actually enumerates the user logons and not the users. This includes interactive logons, batch logons, and service logons, so it frequently returns the same name more than once. Since in the course of normal use various system services will impersonate a user to perform functions on their behalf, so a user may be reported even if they have subsequently logged off their interactive session.

There are two "call levels" and Level 1 returns a few additional items most programs won't need.


What WkstaUserEnum.bas Does

This module exposes the EnumUsers() function. This makes Level 0 NetWkstaUserEnum() calls to build a list of user names in the dynamic String array passed to it. As it builds the list it eliminates duplicate entries, making it slightly more useful than some wrapper code I've seen.

You could use Level 1 calls instead if you want the extra info but these additional items aren't too exciting or useful to most programs. If you want this you'll need to decide how to return it, and you may want to eliminate the "duplicate filtering" since the multiple entries for the same user name may not really be unique (others values might vary).


Why Use WkstaUserEnum?

Yes, you can get this information via WMI queries. However WMI is not meant for use in applications, it is an admin scripting tool. It is also fairly "heavy" and depends on the WMI service being installed and running on the local machine and all target systems being queried.


Practical Issues

NetWkstaUserEnum() calls block, and so when querying a remote system there can be delays of many seconds. This is usually because the network is very slow, the remote system is very busy, or the remote system is an oddball device running Samba or something rather than actually being a Windows system.

It also only works for systems that are Windows NT 3.1 or later, or those with a good LAN Manager/MS Networking emulation.

The results returned are a list and may well have multiple user names in most realistic scenarios. It is possible that the first returned result tends to be that of the local console interactive logon (if any) but there are no guarantees. After all, there could be batch logons active with nobody logged on interactively at all!


Requirements

The querying system (running your program) must be Windows NT 4.0 or later. Queried systems should be Windows NT 3.1 or later.

There is no support for Win9x systems at either end.


Usage, Demo

The attached demo shows how easy it is to use. Here is all of the code in the demo's Form1:

Code:

Option Explicit

Private Sub cmdFetch_Click()
    Dim Status As NETAPI_STATUSES
    Dim strUsers() As String
    Dim I As Long

    Status = WkstaUserEnum.EnumUsers(txtServer.Text, strUsers)
    If Status = NERR_SUCCESS Then
        With txtResult
            .Text = ""
            For I = 0 To UBound(strUsers)
                .SelText = strUsers(I)
                .SelText = vbNewLine
            Next
        End With
    ElseIf Status = EXTENDED_EXCEPTION Then
        txtResult.Text = "VB Exception " & CStr(WkstaUserEnum.LastError) & " " _
                      & WkstaUserEnum.LastDescription
    Else
        txtResult.Text = "System Error " & CStr(WkstaUserEnum.LastError) & " " _
                      & WkstaUserEnum.LastDescription
    End If
    txtServer.SetFocus
End Sub

Attached Files

What is the best way to resize only certain things on a form?

$
0
0
I'm coding a chat/server client and I'm having some issues trying to get resizing working correctly.

I have a chat form that looks like this.

Name:  dlc4x.jpg
Views: 73
Size:  26.2 KB

I'm wanting to keep the top labels, textbox, and buttons the same size and in the same exact spot. I want to adjust the chat textbox, the listbox, and the textbox at the bottom that you type the message to. The send button I want to stay the same size also and always to the right of the send textbox. I'm having a really hard time trying to figure out how to code the resizing part of the code.

I could really use some assistance I've tried many things like.

txtchat.height = me.scaleheight - 100 adding the 100 in there to try and take off some for the controls on the top of the form. Also tried

txtchat.height = me.scaleheight - txtsend.height - 100 and a ton of other things. I guess I just don't understand how this resizing works. Any help would be appreciated.
Attached Images
 

[VB6] modLockEnumCase.bas - Enforce Case of Enums

$
0
0
The VB6 IDE has an annoying quirk when it comes to the case of Enum members. Unlike with other identifiers, the IDE doesn't enforce the case of an Enum member as it was declared in the Enum block. That usually causes an Enum member that was manually written to lose its original case, unless a coder typed it carefully enough. The prevalent workaround for this bug is to redeclare the identifiers inside an #If...Then...#End If directive

Code:

Private Enum Constants
    Const1
    Const2
    Const3
End Enum
#If False Then
    Dim
Const1, Const2, Const3
#End If

However, if a project contains a lot of Enums, redeclaring the members in each of them can get quite tedious fast. Nobody seems to have submitted yet a routine to automate this process here in the VB6 CodeBank, so I'm sharing this code snippet I've had for some time now.

Code:

Attribute VB_Name = "modLockEnumCase"
Option Explicit

'modLockEnumCase.bas usage:
'1. Add to project.
'2. Select entire Enum block.
'3. Copy to Clipboard.
'4. Run LockEnumCase() from the Immediate Window. Optionally *suggest* length of each line.
'5. Paste after the Enum block.
'6. Remove from project when no longer needed.


Public Sub LockEnumCase(Optional ByVal LineLen As Integer = 80) 'Adjust length of output lines as desired
Attribute LockEnumCase.VB_Description = "Enforces the case of Enumerations via Conditional Compiler Directives."
    Dim sBlock As String, sLine As String, sText As String, oMatch As Object 'Match

  'See if there's anything to process; quit if no text was copied

    If Clipboard.GetFormat(vbCFText) Then sText = Clipboard.GetText Else Exit Sub
  'Prepend the conditional compiler directive that is set to False
    sBlock = "#If False Then" & vbNewLine
  'Dimension variables that reuses the Enum members' names
    sLine = "Dim "

    With CreateObject("VBScript.RegExp") 'New RegExp
        .Global = True
        .MultiLine = True

      'Strip all comments
      .Pattern = " +'.*$"
        sText = .Replace(sText, vbNullString)

      'Exclude Enum statements
      .Pattern = "(\b(Private|Public)? Enum [A-Za-z]\w*\b)|(\bEnd Enum\b)"
        sText = .Replace(sText, vbNullString)

      'Split multiple expressions in a single line into their own lines
        If InStrB(sText, ":") Then sText = Replace(sText, ":", vbNewLine)

      'This should match most Enum member names, including those enclosed with []
      .Pattern = "^ *([A-Za-z]\w*|\[.+\]) *(?:=|$)"

        For Each oMatch In .Execute(sText)
            sLine = sLine & (oMatch.SubMatches(0&) & ", ")

          'Check if the string being built is exceeding
          'the *suggested* limit of each output line

            If Len(sLine) >= LineLen Then
              'If so, commit this line to the output string
                sBlock = sBlock & (sLine & "_")
              'Begin anew at the next line
                sLine = vbNewLine
            End If
        Next
    End With


  'Finish the conditional compiler directive block, removing empty lines as needed
    sBlock = sBlock & (IIf(sLine <> vbNewLine, sLine, vbNullString) _
                    & vbNewLine & "#End If" & vbNewLine)
  'Overwrite the last comma with a space
    Mid$(sBlock, InStrRev(sBlock, ",")) = " "
  'Try to erase the last underscore on the last line, if present
    On Error Resume Next
    Mid$(
sBlock, InStrRev(sBlock, "_" & vbNewLine & "#")) = " "
    On Error GoTo 0

  'Copy back to the Clipboard
    Clipboard.Clear
    Clipboard.SetText sBlock
End Sub

Attached Files

[VB6] API Open With Dialog with enhanced functionality

$
0
0
All the methods I've seen for bringing up the Open With dialog use rundll32. But Windows Vista and above has a better option: the SHOpenWithDialog API call. This allows a number of different options in addition to modality. After searching, it seems no one has posted a VB6 implementation yet, so I thought others might like the idea of using this as much as I did.


Requirements: The API call is only available on Vista or higher.

Code:

Option Explicit

'Module: mOpenWith
'Version: 0.1
'Author: fafalone
'Purpose: Vista and above provides an API call for the Open With dialog, which offers more options
'        than the previous typical method of using rundll

Public Declare Function SHOpenWithDialog Lib "shell32" (ByVal hWnd As Long, poainfo As OPENASINFO) As Long

Public Enum OPEN_AS_INFO_FLAGS
    OAIF_ALLOW_REGISTRATION = 1 'Enable the "always use this program" checkbox. If not passed, it will be disabled.
    OAIF_REGISTER_EXT = 2 'Do the registration after the user hits the OK button.
    OAIF_EXEC = 4 'Execute file after registering.
    OAIF_FORCE_REGISTRATION = 8 'Force the Always use this program checkbox to be checked. Typically, you won't use the OAIF_ALLOW_REGISTRATION flag when you pass this value.
    OAIF_HIDE_REGISTRATION = 20 'Introduced in Windows Vista. Hide the Always use this program checkbox. If this flag is specified, the OAIF_ALLOW_REGISTRATION and OAIF_FORCE_REGISTRATION flags will be ignored.
    OAIF_URL_PROTOCOL = 40 'Introduced in Windows Vista. The value for the extension that is passed is actually a protocol, so the Open With dialog box should show applications that are registered as capable of handling that protocol.
    OAIF_FILE_IS_URI = 80 'Introduced in Windows 8. The location pointed to by the pcszFile parameter is given as a URI.
End Enum

Public Type OPENASINFO
    pcszFile As Long
    pcszClass As Long 'file type description for registering the type with 'always open', if not set uses extension, as in 'XYZ File'
    oafInFlags As OPEN_AS_INFO_FLAGS
End Type



Public Function OpenWith(sFile As String, lFlags As OPEN_AS_INFO_FLAGS, Optional hWndParent As Long, Optional sClass As String) As Long
Dim oai As OPENASINFO
oai.pcszFile = StrPtr(sFile)
oai.oafInFlags = lFlags
If sClass <> "" Then oai.pcszClass = StrPtr(sClass)
OpenWith = SHOpenWithDialog(hWndParent, oai)
End Function

The sample project attached contains a form that calls the OpenWith function.

OpenWith(sFile As String, lFlags As OPEN_AS_INFO_FLAGS, Optional hWndParent As Long, Optional sClass As String)

sFile - The file to be opened
lFlags - See the descriptions in the BAS; you'll usually want to include OAIF_EXEC to open the file afterwards, and OAIF_ALLOW_REGISTRATION to enable the 'always use this program' box.
hWndParent - You can specify an owner window (e.g. Form1.hWnd) and the dialog will be modal to that form (you can't click on anything on the form until the dialog closes).
sClass - You can optionally specify a file type description for registering the type for always open. If not specified, the file extension would be used (e.g. XYZ File).

Note: Since this is a Unicode function (it takes lpcwstr's, hence the need for strptr()), it should handle unicode file names and unicode path lengths without issue.
Attached Files

[VB6] Image Recovery from Project Files

$
0
0
Not a groundbreaking project by any means. This little project can retrieve images saved within an uncompiled resource file or within project binary files (frx, ctx, dsx, dox, pgx).

Resource files. How to retrieve using just VB functions...
1) BMP: LoadResPicture & SavePicture will retrieve & save in bitmap format
2) ICO: LoadResPicture & SavePicture will only save the extracted icon. If icon contains multiple images, the others will be lost
-- LoadResData for icons generates error.
3) CUR: Same as icons, but worse: changes format from cursor to icon
-- LoadResData for cursors, only bitmap data returned, not cursor header
4) CUSTOM section. Use LoadResData then save returned array to disk.

If the project is compiled, then any good resource hacker (badly named), can use APIs to locate the desired resource item, from the .exe/ocx file, & extract it in its entirety.

If you have the binary files and the actual associated non-binary file to go with it, then...
1) BMP. Note: JPG & GIF images in these binary files maintain their original image format
a. In code, use SavePicture ControlName.Picture
b. In design mode, click on control that has the bitmap image assigned. Find Picture in the property sheet & double click on it. Press Ctrl+C & paste into Paint & then save
2) ICO/CUR. Cannot get the image, VB will not copy them to the clipboard
in code, use SavePicture ControlName.Picture. But same restrictions apply as with LoadResPicture mentioned above for resource files
3) WMF/EMF. In code, use SavePicture ControlName.Picture
-- Should be able to copy to clipboard similar to bitmaps

But if you want a solution that isn't limited to noted restrictions above. This project is one.

Maybe there are other methods out & about. But honestly, not many people will find this useful until they have a corrupted frm file & their only copies of the images were in the frx file which may not be usable to VB any longer, but usable to this project if that frx itself isn't corrupted.
Attached Images
 
Attached Files

[VB6] Using the new IFileOperation interface to replace SHFileOperation on Vista+

$
0
0
cFileOperation 0.1

SHFileOperation has been superseded by IFileOperation on Windows Vista and above. At least the basic parts of it are easy to access in VB6- showing the standard Windows dialog/progress boxes to Move, Copy, or Delete files. While the class handles it, this function also requires us to bring in the IShellItem interface and its relatives into VB, so take a look at the class module code if you ever wanted to use other functions that required this.

Right now this projects just supports the basic calls to Copy/Move/Delete; look for more options, like customizing actions using the .Advise sink method, in future releases.

Requirements
IFileOperation is only available on Windows Vista and higher; this project will not work on XP.
The included olelib.tlb is an upgrade of the standard one and needs to be added as a reference.

Usage Summary
Using the class is fairly straight forward;
-Add a reference to the upgraded olelib.tlb
-Add the class module to the project and go nuts.
-Sample project included to show how the class is called.

Part 1: The Type Library
The easiest way to go about this, due to the extensive dependency tree, was to start with Eduardo Morcillo's olelib. Everything is too tightly interrelated to have separate projects; the conflicts and hours spent re-doing things would simply be unmanageable. So what I've done is take this excellent work, and add in a number of modern interfaces. Old interfaces are the same; if you already use this file in your projects, you can replace it without making any changes to existing code. There's lots to be done with all the new interfaces I've added, and more projects will be forthcoming.

This project contains, at least for the time being while I await an answer on whether its allowed, the upgraded olelib.tlb and the full source to it. You can compile it yourself with the included mk.bat (if your MKTYPLIB.EXE isn't in the standard folder you'll have to edit it).
Among the interfaces added:
IShellItem
IShellItem2
IShellItemArray
IEnumShellItems
IFileOperation
IPropertyChange
IPropertyChangeArray
IObjectWithPropertyKey
IOperationsProgressDialog
IShellLibrary*
ITaskbarList3*
ITaskbarList4*
IActionProgress*
IShellItemImageFactory*
IThumbnailProvider*
* - Not related to the current project, but look for new projects showing their use soon.

Might be a few more I added a long time ago and forgot about, this update is years in the making.

Add olelib.tlb as a reference to your project.

Part 2 - The Class
Once you've added olelib, you're ready to start using cFileOperation. Since this calls the native methods, everything functions the same as in Explorer, including prompts about overwriting, confirmation deletion, etc. No extra code is needed to handle that.
Here are the currently supported calls:

.ParentWindow - Specify the parent window (e.g. Form1.hWnd) to keep the dialogs on top of it.
.SingleFile - For performing operations on a single file.
.SetFileList - For multiple files, specify an array containing a single full path to a file in each item.
.FileList - Retrieve the current file list.
.DestFolder - The destination folder; don't need to set for Delete.
.Flags - Set flags for the operation; uses the standard FileOperationFlags enum (see below).
.CopyFile - Copies the single file.
.CopyFiles - Copies the file list.
.MoveFile - Moves the single file.
.MoveFiles - Moves the file list.
.DeleteFile - Deletes the single file.
.DeleteFiles - Deletes the file list.

File Operation Flags

See MSDN Description of Flags

Can't put it much better than MSDN.


-------
All bug reports, comments, criticisms, and suggestions welcome.
PLEASE NOTE: I don't have access to multiple test systems; everything works on Win7 x64, and everything should work from Vista through 10, but please let met know if there's an issue.
Attached Files

VB6 - Chat Client/Server

$
0
0
This is a 2 part program consisting of a server component and a client component. Because the server component services more than one client, the server must use a Socket Array, which requires an ActiveX Control. Since I cannot post OCX components, I have also provided the OCX code. Instructions on compiling and registering the component are included in the Readme file. To test your new OCX, I have included prjWebTest. Remember to change the NewSocketOCX reference lines in the project and the form.

The server component operates as a Service under the control of the Service Manager. As such, it has no visible interface, and the Administrator uses a client component to monitor the service. There is also daily log files to log access and errors. It offers service in straight text or encrypted modes, in either IPv4 or IPv6. IPv6 has experienced very limited testing due to the lack of a native IPv6 network.

For the Encryption mode, the client passes the User Name (Handle) and the Public Exchange Key (2048 bit) to the server. The server then uses that key to pass a random 256 bit Symmetric Key back to the client. The client then uses the Private Exchange Key to decrypt the Symmetric Key. Because the server is simply reflecting encoded traffic back to all the connected clients, it does not need to decrypt any of the traffic. The Exchange Key pair is created automatically by the operating system if it does not already exist.

Encoded traffic prevents network snooping, but cannot be considered secure without additional security by way of a password or secret token. Anyone with the correct client software can connect and obtain the current Symmetric Key.

J.A. Coutts
Attached Images
 
Attached Files

Using wave-in device

$
0
0
Hello, do you know if is there any way to make work the wave-in device even if it were turned off? I explain myself: I am using mci for playing music and I want to perform a spectrum analyzer, the problem is that I don't know any switch in mci that gives me info on the wave info for I am cappable applying the FFT algo to this data for doing the SA. I am only able to do that turning on the wave-in device and using it for retrieve the wave. That's alright, the problem is that not everybody has the wave-in turned on. Maybe it is possible to send data (music) from mci to the wave-in and retrieve the wave to be able of make the spectrum analyzer.

Regards.
:wave:

[VB6] Use IFileOperation to replace SHFileOperation for modern Copy/Move box/prompts

$
0
0
cFileOperation 0.1

Display the latest version of the copy/move/delete progress dialog and the related prompts.

SHFileOperation has been superseded by IFileOperation on Windows Vista and above. At least the basic parts of it are easy to access in VB6- showing the standard Windows dialog/progress boxes to Move, Copy, or Delete files. While the class handles it, this function also requires us to bring in the IShellItem interface and its relatives into VB, so take a look at the class module code if you ever wanted to use other functions that required this.

From MSDN, advantages to IFileOperation:
Quote:

Use of IShellItem to identify items rather than string paths. SHFileOperation required path and destination strings to terminate in two null characters rather than the standard single null character, which itself was used to delimit multiple paths in the string. Identifying an item through IShellItem is more robust and less prone to programming errors. It also allows you to access non-file system items such as virtual folders. Multiple items in one operation can be passed as an IShellItemArray, IDataObject, or a collection accessed through IEnumShellItems rather than as a string.
More accurate error reporting through HRESULT values in conjunction with an API such as FormatMessage. Return codes from SHFileOperation could be misleading or inaccurate.
Extensibility. As a Component Object Model (COM) interface, IFileOperation can have its capabilities extended by a third-party to meet their specific needs, although this should be a very rare case. Windows provides a default implementation of IFileOperation that should meet the needs of most users.
Better progress feedback. Detailed operation progress, including notifications when specific operations begin and end on individual items as well as the overall progress, can be received during the operation. While SHFileOperation did provide progress UI, it was not as detailed.
More functionality. In addition to the copy, delete, move, and rename functionality provided by SHFileOperation, IFileOperation allows you to apply property values and create new items.
More control over the operation. In addition to the operation flags recognized by SHFileOperation, new flags are recognized in IFileOperation::SetOperationFlags that specify extended operation options.
Different operations can be performed in one call. For instance, you can move a set of files, copy others, rename a folder, and apply properties to yet another item all in one operation. SHFileOperation could only do one operation—copy, move, rename, or delete—at a time.
Right now this projects just supports the basic calls to Copy/Move/Delete; look for more options, like customizing actions using the .Advise sink method, in future releases.

Requirements
IFileOperation is only available on Windows Vista and higher; this project will not work on XP.
The included olelib.tlb is an upgrade of the standard one and needs to be added as a reference.

Usage Summary
Using the class is fairly straight forward;
-Add a reference to the upgraded olelib.tlb
-Add the class module to the project and go nuts.
-Sample project included to show how the class is called.

Part 1: The Type Library
The easiest way to go about this, due to the extensive dependency tree, was to start with Eduardo Morcillo's olelib. Everything is too tightly interrelated to have separate projects; the conflicts and hours spent re-doing things would simply be unmanageable. So what I've done is take this excellent work, and add in a number of modern interfaces. Old interfaces are the same; if you already use this file in your projects, you can replace it without making any changes to existing code. There's lots to be done with all the new interfaces I've added, and more projects will be forthcoming.

This project contains, at least for the time being while I await an answer on whether its allowed, the upgraded olelib.tlb and the full source to it. You can compile it yourself with the included mk.bat (if your MKTYPLIB.EXE isn't in the standard folder you'll have to edit it).
Among the interfaces added:
IShellItem
IShellItem2
IShellItemArray
IEnumShellItems
IFileOperation
IPropertyChange
IPropertyChangeArray
IObjectWithPropertyKey
IOperationsProgressDialog
IShellLibrary*
ITaskbarList3*
ITaskbarList4*
IActionProgress*
IShellItemImageFactory*
IThumbnailProvider*
* - Not related to the current project, but look for new projects showing their use soon.

Might be a few more I added a long time ago and forgot about, this update is years in the making.

Add olelib.tlb as a reference to your project.

Part 2 - The Class
Once you've added olelib, you're ready to start using cFileOperation. Since this calls the native methods, everything functions the same as in Explorer, including prompts about overwriting, confirmation deletion, etc. No extra code is needed to handle that.
Here are the currently supported calls:

.ParentWindow - Specify the parent window (e.g. Form1.hWnd) to keep the dialogs on top of it.
.SingleFile - For performing operations on a single file.
.SetFileList - For multiple files, specify an array containing a single full path to a file in each item.
.FileList - Retrieve the current file list.
.DestFolder - The destination folder; don't need to set for Delete.
.Flags - Set flags for the operation; uses the standard FileOperationFlags enum (see below).
.CopyFile - Copies the single file.
.CopyFiles - Copies the file list.
.MoveFile - Moves the single file.
.MoveFiles - Moves the file list.
.DeleteFile - Deletes the single file.
.DeleteFiles - Deletes the file list.

File Operation Flags

See MSDN Description of Flags

Can't put it much better than MSDN.


-------
All bug reports, comments, criticisms, and suggestions welcome.
PLEASE NOTE: I don't have access to multiple test systems; everything works on Win7 x64, and everything should work from Vista through 10, but please let met know if there's an issue.
Attached Files

Unicode Textbox

$
0
0
Here's my version of a Unicode & RTF textbox.

It's about as full featured as you can get while using the RichTx32.ocx control.

Full Unicode and RTF editing while in the IDE design mode. Just right-click and "Edit" to paste in your Unicode/RTF text.

Every single event, property, and method is passed through (with the exception of the data bound properties).

It's actually a bit like a mini-Unicode-word-processor while you're in the IDE design mode. Be sure to take a look at the Sel... properties. Usually, with the regular RTF box, those are only available at runtime, but with this control, they're all available at design time as well. Mess with them while in "Edit" mode of the control, and you can format your text while you're typing it.

The only downside is that pasted text (while in "Edit" mode), must be RTF (or ascii). There can be Unicode embedded in the RTF, but you can't paste "raw" Unicode. So what does this mean? It means you can paste pretty much anything from WordPad (and Word), and it'll go straight in (Unicode and all). Because, in these circumstances, there'll be an RTF representation of the copy in the clipboard. However, Notepad can do Unicode but it doesn't do RTF. Therefore, if you try to copy-and-paste Unicode from the Notepad, it won't work. However, if you copy from Notepad, paste to WordPad, then copy the same text from WordPad, and then paste into this control, it'll work. That's because WordPad will give you an RTF representation of the Unicode.

From WordPad, you can even paste pictures into it.

Please let me know what you think of it and whether you see any problem/enhancements from which it may benefit. Also, if anyone can figure out the pure-Unicode pasting, I'd be delighted to listen.

Enjoy,
UnicodeTextbox.zip
Attached Files

Reading and Writing UTF-16 and UTF-8 Files

$
0
0
Ok, here's my procrastination for the day. I've long been able to read Unicode (UTF-16) files, but I decided I also wanted to read and write UTF-8 files, so I did it. The attached "test" project is the best way to get it, but here's the essential code for the file IO. Focus specifically on the ReadAsciiOrUnicodeNotepadFile and WriteAsciiOrUnicodeNotepadFile procedures. I thought about making them Get/Let properties, but I think they're better this way. Again, don't forget that the attached ZIP has a nice demo.

UTF8 and UTF16.zip

Code:

Option Explicit
'
Private Declare Function WideCharToMultiByte Lib "kernel32" (ByVal codepage As Long, ByVal dwFlags As Long, ByVal lpWideCharStr As Long, ByVal cchWideChar As Long, ByVal lpMultiByteStr As Long, ByVal cchMultiByte As Long, ByVal lpDefaultChar As Long, ByVal lpUsedDefaultChar As Long) As Long
Private Declare Function MultiByteToWideChar Lib "kernel32" (ByVal codepage As Long, ByVal dwFlags As Long, ByVal lpMultiByteStr As Long, ByVal cbMultiByte As Long, ByVal lpWideCharStr As Long, ByVal cchWideChar As Long) As Long
'
Private Const Utf8CodePage As Long = 65001
'
Public Enum AsciiUnicodeEncoding
    AsciiEncode = 0
    Utf8Encode = 1
    Utf16Encode = 2
End Enum
'

Public Function ReadAsciiOrUnicodeNotepadFile(sFileSpec As String) As String
    ' These are typically .TXT files.  They can be read with notepad.
    Dim iFle As Long
    Dim bb() As Byte
    Dim i As Integer
    Dim s As String
    '
    iFle = FreeFile
    Open sFileSpec For Binary As iFle
    If LOF(iFle) = 0 Then
        Close iFle
        Exit Function
    End If
    '
    Get iFle, , i
    Select Case i
    Case &HFEFF ' UTF16 file header.  First byte = FF, second byte = FE.
        ReDim bb(1 To LOF(iFle) - 2&)
        Get iFle, , bb
        ReadAsciiOrUnicodeNotepadFile = bb ' This directly copies the byte array to the Unicode string (no conversion).
    Case &HBBEF
        ReDim bb(1 To LOF(iFle) - 3&)
        Seek iFle, 4
        Get iFle, , bb
        ReadAsciiOrUnicodeNotepadFile = Utf8toUtf16(bb)
    Case Else ' Assume ascii.
        s = Space$(LOF(iFle))
        Seek iFle, 1
        Get iFle, , s
        ReadAsciiOrUnicodeNotepadFile = s
    End Select
    '
    Close iFle
End Function

Public Sub WriteAsciiOrUnicodeNotepadFile(sFileSpec As String, sData As String, Encoding As AsciiUnicodeEncoding)
    ' These are typically .TXT files.  They can be read with notepad.
    Dim iFle As Long
    '
    iFle = FreeFile
    Open sFileSpec For Binary As iFle
    Select Case Encoding
    Case AsciiEncode
        Put iFle, , sData
    Case Utf8Encode
        Put iFle, , CByte(&HEF)
        Put iFle, , CByte(&HBB)
        Put iFle, , CByte(&HBF)
        Put iFle, , Utf16toUtf8(sData)
    Case Utf16Encode
        Put iFle, , &HFEFF ' This is the Unicode header to a text file.  First byte = FF, second byte = FE.
        Put iFle, , Utf16ByteArrayFromString(sData)
    End Select
    Close iFle
End Sub

Public Function Utf16ByteArrayFromString(s As String) As Byte()
    ' This directly copies the Unicode string into the byte array, using two bytes per character (i.e., Unicode).
    Utf16ByteArrayFromString = s
End Function
 
Public Function Utf16toUtf8(s As String) As Byte()
    ' UTF-8 returned to VB6 as a byte array (zero based) because it's pretty useless to VB6 as anything else.
    Dim iLen As Long
    Dim bbBuf() As Byte
    '
    iLen = WideCharToMultiByte(Utf8CodePage, 0, StrPtr(s), Len(s), 0, 0, 0, 0)
    ReDim bbBuf(0 To iLen - 1) ' Will be initialized as all &h00.
    iLen = WideCharToMultiByte(Utf8CodePage, 0, StrPtr(s), Len(s), VarPtr(bbBuf(0)), iLen, 0, 0)
    Utf16toUtf8 = bbBuf
End Function
 
Public Function Utf8toUtf16(bb() As Byte) As String
    ' Incoming must be a dimensioned byte array with a UTF-8 string in it.
    Dim sBuf As String
    Dim iLen As Long
    '
    iLen = MultiByteToWideChar(Utf8CodePage, 0, VarPtr(bb(LBound(bb))), UBound(bb) - LBound(bb) + 1, 0, 0)
    sBuf = String$(iLen, 0)
    iLen = MultiByteToWideChar(Utf8CodePage, 0, VarPtr(bb(LBound(bb))), UBound(bb) - LBound(bb) + 1, StrPtr(sBuf), Len(sBuf))
    Utf8toUtf16 = sBuf
End Function

EDIT: This is in response to some of the following posts. If the above routine is to correctly read Unicode (UTF-16 and/or UTF-8), those files MUST have the Byte Order Marker (BOM) in the files. For UTF-16 files, they typically DO have their BOM. Many UTF-8 files also have this BOM header. If files are written by a relatively recent version of Windows Notepad, they will have these BOM markers, but there are Unicode files from sources other than notepad.

If you wish for a routine that reads Unicode files without the BOM header (which will primarily be UTF-8 files), you may want to consider incorporating Arnoutdv's routine (in Post #3 below) into your work. For further reading on this entire issue, the following link outlines the problems well:

http://blogs.msdn.com/b/oldnewthing/...7/2158334.aspx
Attached Files

VB6 - DNS Monitor

$
0
0
DNS Monitor is a utility program that allows you to monitor and log DNS requests transiting your network. This program has been around for some time and is by far the most popular download on my Web site. I have never posted the code because it utilized the Dart Service Control (which is not free), and I finally got around to converting it to using the Microsoft NTSvc.ocx control. At the same time, I implemented low level packet filtering within WinPKFilter, so that the program only sees port 53 UDP data. Examining all packets had its advantages, but it was very inefficient.

DNS Monitor hooks the NDIS driver in your windows operating system, and sets the NIC to operate in promiscuous mode. In this mode, you can see all DNS requests on your network if you are using a hub instead of a switch. The advantage of monitoring DNS requests rather than Web GET requests is that these requests are very small and cover services over and above just the World Wide Web. Additionally, most operating systems will cache these requests, so that all you see is the first request. This gives you a fairly concise picture of Internet usage. On my network, I can see traffic on the WiFi part as well because I am using a WiFi hotspot that connects into the same hub. My new Windows Tablet makes an insane number of DNS queries just powering up and loading a home page on Internet Explorer.

There are 2 components to DNS Monitor. The main program is interactive, and allows you to monitor and capture current DNS activity. The only setup required is for the user to confirm which IP Adapter is being utilized. The captured data is logged to daily files stored in the "%windir%\System32\LogFiles\DNS\" directory by date.

DNS Monitor also has an optional service component. This service operates in the background with no user interaction required, even when the user is logged off. It will not however persist through a type 3 Sleep mode. To install the service, simply click on the "Install" button. Once successfully installed, the "Start" button will become active and you can start the service, providing that the active server is "OFFLINE". You can also use the Service Manager (services.msc).

To install DNS Monitor, you must first install WinpkFilter!
http://www.ntkernel.com/downloads/winpkflt_rtl.zip
There is no charge for personal use.

NOTE: On 64 bit operating systems (Vista/Win7/Win8), driver signing is enforced, and must be circumvented! Currently the only way to do that is to use the F8 key on boot up and disable driver signing. The ability to use the Group Policy Editor or modify the BCD file to fullfill this task is no longer available on fully updated systems. Once disabled the driver can be loaded, but permanently signing the driver with a digital signature recognized by Microsoft is prohibitively expensive. What is still available is to run your system in Test Mode. Your driver must still be signed, but you can locally sign your own driver (ndisrd.sys). To make this easier, a small utility is made available from NGOHQ.
http://www.ngohq.com/home.php?page=dseo
This little utility does not have to be installed, but must be run in Administrative Mode. Win 8.1 however is a different kettle of fish. If your computer uses Unified Extensible Firmware Interface (UEFI), it probably uses Secure Boot and hides the TESTSIGNING setting. Secure Boot can be temporarily turned off, TESTSIGNING turned on, and Secure Boot turned back on. However, as of this posting I have not confirmed if TESTSIGNING is still active. I will post more as I uncover it.

J.A. Coutts
Attached Images
 
Attached Files

Radio Buttons as list of buttons and more

$
0
0
I make some additions and a bit of changes that not change the programming schema, but now works fine the trasparency of the control (backstyle=1) (is a copy of the form picture). Also I put a special color to act as text color for seleced item for menu items.
This I done for member Elroy, who wants to duplicate an exist control but he didn't thought that starting something new is better by wrapping code on a RTB control. Every item as a radio button with his thought would be a fresh RTB. I don't like that approach. I would like better to handle a group of selections in list, so i can handle the number without thinking about how big is my form.
You can freely use that code and if you like make it a better control..
Attached Images
 
Attached Files

Textbox validation for integers and float/scientific numbers

Unicode OptionButton

$
0
0
Here's a Unicode Option Button. Just see small sample project. It should be self-explanatory.

One weakness: You can't paste the caption with pure unicode (without an RTF format being in the clipboard). It's best to paste into WordPad, re-copy, and then it'll paste into the Option Button's caption. I know how to paste pure unicode, but it just makes the control quite a bit heavier. You can set the caption at runtime with a string (which is unicode, of course) and it'll correctly go into the caption as unicode.

Enjoy:
UnicodeOptionButton.zip

EDIT: There's also a GroupNum property for creation Option Button groups. No need for separate frames or containers. Initially, it defaults to 0, linking them all together.
Attached Files
Viewing all 1522 articles
Browse latest View live


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