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

A new custom listbox and example for how to make it a combobox

$
0
0
My old glist..updated with extra functionality.
So now glist (as glist2 control) can act as listbox and with a textbox can act as combo box. You can change charset. List inside listbox isn't a collection but is a dynamic string array.
In the example are three forms. One to show how selected, selected2, scrollselected and softselected events works. One is the old example of 1 million items, and you can scroll the scroll bar and see the list to scrolling accordingly. Also a label display the showing lines, the logical lines (see code) and the scroll lines (the page knowing by scroll bar). Finally the last form show three glist controls that we can show as "popup", and for the left one, we can hold open as we write in textbox, and as we write there is an auto selection in listbox, to show us an item that starts like the text in textbox. Listboxes as combos can also used with arrows, enter, escape, and tab.

Written in vb6 (yes I move from 5 to 6...its time..)
Attached Files

MJPEG Webcam Receiver

$
0
0
Attached to this message is the complete source code for this program. It is designed to receive webcam video, but will work for any video source that has these specifications:
Server Location = 127.0.0.1 (same computer as the VB application that is running)
Network Protocol = TCP/IP
Application Protocol = HTTP
Port Number = 8080
Container Format = AVI (each frame starts the String "00dc" followed by a Long who's value equals the size in bytes of the frame's payload data)
Video Codec = MJPEG (Motion JPEG, where each frame of video is a JPEG image)
Audio Codec = none (no audio is sent)

To get those specs on your stream, the easiest way to do it is to use VLC Player to stream the video and make sure the protocol is set to HTTP, the port number is set to 8080, and that the transcoding options are set to use the above mentioned container format and video codec, and that audio is not sent. I won't explain how to use VLC Player here, as this isn't a VLC forum. However there is a VLC forum you can go to to get help (or if you are like me, and have used it a lot, you may already know how to do this). And make sure you are running VLC on the same computer that you are running this VB6 program on.

Now as for my receiver's functionality, it can connect to and disconnect from a server. It can display the video directly, or process it prior to displaying it, using one of several different algorithms to add various image altering effects to the frames. You'll notice a drop in frame rate from 30fps to something much lower, as processing can't occur any faster than about one to two tenths of a second per frame on an image size of 640x480.
Attached Files

BassPlayerDB

$
0
0
I have seen many folks here and other fora struggling with Window Media Player, the MMControl, and MPI Api calls to create decent Mp3/Wav apps. After a few years working with the Bass library, I'm convinced it is the way to go. Bass was created by Ian Luck at http://www.un4seen.com. The basic package contains the binaries and examples for several languages, including VB. The VB apps all work fine and will give you an idea of how to use the library. The class in this project (cBass.cls) just serves as a wrapper to make it easier to use Bass.

This app is designed for those who have a large collection of music files. It uses an ADO Access database (Music.mdb) to store the info about each mp3/wav file added. When adding music files, it uses the audiogenie3.dll to gather info if the mp3 files have tags. If not you can edit files to store things like album, composer, genre, year, comment, etc in the DB.

If you have your music files centrally located, such as ITunes, it is best to load the entire folder, which can be time comsuming, and then delete such items as desired, but this is not necessary, as you can add files at any time.

Features:
· Select music by category (Artist, Album, Composer, Genre, Year)
· Search for music in the database or in the currently playing list
· Load random lists of music
· Create Playlists that are stored in the database. (There is also a utility under Options to manage/edit/delete Playlists.)
· Add album art to your mp3 files, which is stored in the file's ID3 V2 tag, bmp, jpg, tif, gif, png are supported.

Startup:
At startup, the database is empty and you will be prompted to Use Options/Add Music to enter mp3/wav files to the database. Once you have added music to the database, you will be able to access the player’s features.

Keyboard controls:
Playback:
The Right and Left keys advance/backup the music stream by 5 seconds when the Listview has focus. You can also change
the song’s position using the scroll bar.
Ctrl P – Play the previous song
Ctrl S – Start/Restart the currently selected song
Ctrl Space – Pause/Resume the currently playing song
Ctrl X – Stop the currently playing song
Ctrl N – Play then next song
(Note you can scroll up & down with the arrow keys and play a song by pressing the Return key on the desired item, or you can Double Click an item to play it)

Others:

Ctrl G – Go to the currently playing song (i.e. the playing song has been scrolled out of view)
Ctrl A – Select all songs in the list
Ctrl C – Clear the list
Ctrl R – Remove all selected songs in the list

About Crossfading:
Many people like the music to fade out at the end and start the next song in the list. I have found that about 5 seconds of crossfade/fadeout works pretty well, but you can change this with Options|Preferences. Note that this does not work well with a song that has too much silence at the end. I use Mp3 Trim Pro from http://www.mptrim.com/, which can trim the silence from both the beginning and end of an mp3.
Binaries:
Bass:
http://www.un4seen.com/ Click on 'Bass' at the top left of the page. This will take you to the download page. At the top of the page under the word 'Platform', click on the left most Download link. In this download there are two versions of bass.dll. One is in the root folder and the other in a folder called mp3-free.

If you use the "mp3-free" version, you won't need a license since it uses the OS's MP3 decoder rather than including its own MP3 decoder. It's the same as bass.dll, just without the internal MP3 decoder. As long as Windows Media Player is installed, you will have mp3 codecs installed and the mp3-free version should work fine. If you are not developing a commercial product that uses bass, it doesn't matter and you can use either version. I have the mp3-version in my (XP) System32 folder, but you can put it in the app folder or wherever, as long as windows can find it in its Path.

Audiogenie:
http://sourceforge.net/projects/audiogenie/?source=dlp. This gives you the audiogenie3.dll (also in my System32 folder). The clsAudioGenie in this project is a trimmed down version of the full class which reads/writes tags to many different music file formats. You can get the full class here:
http://en.sourceforge.jp/projects/sf...udioGenie.cls/

The attachment has the VB Files without the binaries.
http://normcook.net/Index.html has this readme file as well as the zip for all the VB files, plus the binaries.
Hope you enjoy it.

Comments/critiques welcome.

Name:  ScreenShot.JPG
Views: 62
Size:  67.6 KB
Attached Images
 
Attached Files

[VB6] ImageList and the Safety Palette

$
0
0
This is really not a code sample as much as a technique to use in writing VB6 programs.

Many of the fancier GUI controls in VB6 accept images assigned from a companion ImageList control. Here I'll use the example of the Toolbar control. If we want to use the modern UX-themed versions of these controls based on Windows Common Controls we also need to use the older version 5 COMCTL32.OCX, but that's a separate issue.

Both the version 5 and version 6 VB ImageList controls are designed only to support images of 2, 16, or 256 colors. In the rare case of 2-color images the ImageList's BackColor property comes into play. Otherwise we normally only care about the MaskColor, when we want transparency.


Palettes

For either 16-color or 256-color bitmaps, all of the images must use the same palette. When they don't, you can end up with frustrating symptoms. Often the background or the whole images "go black" after you save your Project and when you run the compiled program.

I don't know why this happens, but it seems to be due to the way these controls persist the bitmaps into the Project's .FRX files.


Better ICO and BMP Files

The VS 6.0 graphics we got with VB6 were meant for another era. Many of them were holdovers from the Win3.x 16-bit era, and look it.

There are newer sets of icons and graphics available for newer versions of Visual Studio, though you'll have to work with them a little to use them with VB6. See:

Visual Studio Image Library

The smaller VS2012 Image Library.zip download there offers plenty to browse through for some better images.


Converting Images

If you want to use 24- or 32-bit images you won't be able to use the standard VB controls. So when you need to do that you'll need 3rd party controls or some other technique.

However quite a lot of the stuff in VS2012 Image Library.zip is usable after some tweaking.

The article Colors: The Safety Palette can be useful. The best thing I found there was a sample image called IC27432.gif under the subheading Get the Safety Palette.


Steps to Convert 24-bit Bitmaps

Go get IrfanView or another utility that can save and load .PAL files.

I grabbed 6 bitmaps from the VS download to demonstrate. Create a folder such as "Original 24-bit" and another such as "Standard 8-bit." Copy 24-bit BMP files to play with there.

Download IC27432.gif, open it in IrfanView, and export its palette. These are also included in the attached archive below.

Then for each bitmap file:

  • Open the bitmap from "Original 24-bit" in IrfanView.
  • Import the IC27432.pal, converting the image to 8-bit.
  • Save as... the new bitmap as BMP format into "Standard 8-bit."


Now you have 8-bit BMPs all using the Safety palette that you can use safely in ImageList controls!

Be sure you set the MaskColor of your ImageLists as well. Many of these use magenta (&H00FF00FF&) as the MaskColor instead of the old default gray shade (&H00C0C0C0&)


Results

Not too bad really. Note that there is only so much you can do with 16x16 images to make them look good though.

Name:  sshot.png
Views: 58
Size:  10.7 KB

Here I don't really care for the shading on the Left-justify icon, it's a little dark. But you can always tweak that as long as you avoid altering the palette.

The archive has the demo Project as well as the BMPs' before and after versions.
Attached Images
 
Attached Files

How do I define joystick pedal all the specific command in Visual Basic? Please help

$
0
0
I need codeBank define joystick pedal ..
for example , define up arrow to click a command .. and so on ..

A Listbox for millions items, transparent background, and changeable charset

$
0
0


This is my glist a big listbox as you see!

New,
This is the right version, wich is very fast for adding 1000000 items, and Vscroll bar using "logical lines" no lines (the visible lines of the usercontrol).

I add a new form to show how this listbox help to have previews when scroll the caret by mouse movemnet, and that previews are labels which response to a click event and perform software selection on the list. When the move is fast then the previews are not changed. So if that was images the walking through the list can be done without time consuming image preview for each item. When we select an item form preview list then the selection didn't fire a "selected" event but a "softselected" so maybe we can leave it without code...What we want is done, no selected event produced and that is right because the selection was made by preview list for a list item.

glistCharset shows how you can have any charset to your listbox...(ordinary listbox they don't change charset even they change the property). I change font to Verdana (unicode) and a put several charset, kyrilic, tourkish...etc
Name:  listbox.JPG
Views: 37
Size:  22.5 KB
Attached Images
 
Attached Files

A new custom listbox with pan function.

$
0
0
My old glist..updated with extra functionality.
So now glist (as glist2 control) can act as listbox and with a textbox can act as combo box. You can change charset. List inside listbox isn't a collection but is a dynamic string array.
In the example are three forms. One to show how selected, selected2, scrollselected and softselected events works. One is the old example of 1 million items, and you can scroll the scroll bar and see the list to scrolling accordingly. Also a label display the showing lines, the logical lines (see code) and the scroll lines (the page knowing by scroll bar). Finally the last form show three glist controls that we can show as "popup", and for the left one, we can hold open as we write in textbox, and as we write there is an auto selection in listbox, to show us an item that starts like the text in textbox. Listboxes as combos can also used with arrows, enter, escape, and tab.

Written in vb6 (yes I move from 5 to 6...its time..)

Updated optimized code.
I put Xp styles, and a normal listbox. One glist and one standard listbox for 10000 items each need 17 seconds when 1 milion items in glist need 9.5 seconds. I have a form with an array of glist, two of them, and load 10000 item each in 2.5 seconds.

classic Listbox cannot use listindex grater than 32767. So when you fill 100000 items you get a wrong listindex. Where you find so many items? In a hard disk. If you want to put all images in a list...simply you can't with classic listbox.

The new glist has pan function. In my old version i use pan to read more of a line that was hidden by the frame. Now i put events so in an example below you find left and right pan to act as page up or down (these are from code outside the control so you can define other functions to perform). I inspired from android, when you throw tasks,.for closing purpose. This glist can serve with many ways, because it is open and not need to do much to display graphics, icons and text instead a simple line text. In my last example two glist operate one the other...so if you scroll one exactly the same scroll happen to second..If you click one, the same do to other. The idea is to make each list as a column of data, and you can hide scrollbar without losing the functionality. One scrollbar for all listboxes. So you can make a grid...
And all from a simple custom control...with no ocx or something special needed.

This is free code.
Attached Files

Liistbox and EditBox Unicode and Transparent.

$
0
0
I work some hours to revision an old control who made for the IDE of M2000, with capability to display all utf16 usinf Arial Unicode MS. I have gList and gTextBox with some forms as examples. Drag and drop (unicode allways) can do if you select 2 or more lines. Cntrl X and V also work.


********New********** I added Unicode support.
I send again the file...I found a variable with an annoying keystroke...r before save it...
...Coming a textbox with unicode supprort based in this control

My old glist..updated with extra functionality.
So now glist (as glist2 control) can act as listbox and with a textbox can act as combo box. You can change charset. List inside listbox isn't a collection but is a dynamic string array.
In the example are three forms. One to show how selected, selected2, scrollselected and softselected events works. One is the old example of 1 million items, and you can scroll the scroll bar and see the list to scrolling accordingly. Also a label display the showing lines, the logical lines (see code) and the scroll lines (the page knowing by scroll bar). Finally the last form show three glist controls that we can show as "popup", and for the left one, we can hold open as we write in textbox, and as we write there is an auto selection in listbox, to show us an item that starts like the text in textbox. Listboxes as combos can also used with arrows, enter, escape, and tab.

Written in vb6 (yes I move from 5 to 6...its time..)

Updated optimized code.
I put Xp styles, and a normal listbox. One glist and one standard listbox for 10000 items each need 17 seconds when 1 milion items in glist need 9.5 seconds. I have a form with an array of glist, two of them, and load 10000 item each in 2.5 seconds.

classic Listbox cannot use listindex grater than 32767. So when you fill 100000 items you get a wrong listindex. Where you find so many items? In a hard disk. If you want to put all images in a list...simply you can't with classic listbox.

The new glist has pan function. In my old version i use pan to read more of a line that was hidden by the frame. Now i put events so in an example below you find left and right pan to act as page up or down (these are from code outside the control so you can define other functions to perform). I inspired from android, when you throw tasks,.for closing purpose. This glist can serve with many ways, because it is open and not need to do much to display graphics, icons and text instead a simple line text. In my last example two glist operate one the other...so if you scroll one exactly the same scroll happen to second..If you click one, the same do to other. The idea is to make each list as a column of data, and you can hide scrollbar without losing the functionality. One scrollbar for all listboxes. So you can make a grid...
And all from a simple custom control...with no ocx or something special needed.

This is a free code.

New glist with unicode output. In the example i also use a picturebox as unicode label. Textboxes cannot display unicode.
Attached Files

VB6 - Elevated Privileges

$
0
0
Ever since Microsoft introduced UAC (User Access Control) with Vista, you sometimes need to know if your application is running with administrative privileges. A quick search on the Net revealed some confusion about the use of the GetTokenInformation call. Using this call with the TOKEN_ELEVATION_TYPE parameter will yield the correct result as long as UAC is enabled. But if UAC is disabled or the built-in Administrator account is being utilized, the wrong result is returned. Using TOKEN_ELEVATION, the correct result is returned regardless of the state of UAC. The small program below demonstrates the difference on a Vista machine with UAC disabled, as well as returning the various user directories.

All Users Directory: C:\ProgramData
Default Users Directory: C:\Users\Default
General User Directory: C:\Users
Current User Directory: C:\Users\couttsj
Using TOKEN_ELEVATION_TYPE,
couttsj is not using elevated privileges, or UAC is turned off!
Using TOKEN_ELEVATION,
couttsj is using elevated privileges!

J.A. Coutts
Code:

Option Explicit

Private Const TOKEN_QUERY = (&H8)
Private Const TOKEN_ELEVATION_TYPE As Long = 18
Private Const TOKEN_ELEVATION As Long = 20
Private Declare Function GetAllUsersProfileDirectory Lib "userenv.dll" Alias "GetAllUsersProfileDirectoryA" (ByVal lpProfileDir As String, lpcchSize As Long) As Boolean
Private Declare Function GetDefaultUserProfileDirectory Lib "userenv.dll" Alias "GetDefaultUserProfileDirectoryA" (ByVal lpProfileDir As String, lpcchSize As Long) As Boolean
Private Declare Function GetProfilesDirectory Lib "userenv.dll" Alias "GetProfilesDirectoryA" (ByVal lpProfileDir As String, lpcchSize As Long) As Boolean
Private Declare Function GetUserProfileDirectory Lib "userenv.dll" Alias "GetUserProfileDirectoryA" (ByVal hToken As Long, ByVal lpProfileDir As String, lpcchSize As Long) As Boolean
Private Declare Function GetCurrentProcess Lib "kernel32" () As Long
Private Declare Function OpenProcessToken Lib "advapi32.dll" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, ByRef TokenHandle As Long) As Long
Private Declare Function GetTokenInformation Lib "advapi32.dll" (ByVal TokenHandle As Long, ByVal TokenInformationClass As Long, TokenInformation As Any, ByVal TokenInformationLength As Long, ReturnLength As Long) As Long

Private Sub Form_Activate()
    Dim sBuffer          As String
    Dim lRetLen          As Long
    Dim CurrentUser      As String
    Dim hToken          As Long
    Dim tkElevation      As Long
    Dim N%
    'create a string buffer
    sBuffer = String(255, 0)
    'retrieve the all users profile directory
    If GetAllUsersProfileDirectory(sBuffer, 255) = 0 Then _
        Err.Raise Err.LastDllError, , "Could not retrieve the all users profile directory!"
    'show the result
    Print "All Users Directory: " & StripTerminator(sBuffer)
    sBuffer = String(255, 0)
    If GetDefaultUserProfileDirectory(sBuffer, 255) = 0 Then _
        Err.Raise Err.LastDllError, , "Could not retrieve the default users profile directory!"
    Print "Default Users Directory: " & StripTerminator(sBuffer)
    sBuffer = String(255, 0)
    If GetProfilesDirectory(sBuffer, 255) = 0 Then _
        Err.Raise Err.LastDllError, , "Could not retrieve general users profile directory!"
    Print "General User Directory: " & StripTerminator(sBuffer)
    sBuffer = String(255, 0)
    If OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, hToken) = 0 Then _
        Err.Raise Err.LastDllError, , "Could not retrieve current Process Handle!"
    If GetUserProfileDirectory(hToken, sBuffer, 255) = 0 Then _
        Err.Raise Err.LastDllError, , "Could not retrieve the current users profile directory!"
    CurrentUser = StripTerminator(sBuffer)
    Print "Current User Directory: " & StripTerminator(sBuffer)
    N% = InStrRev(CurrentUser, "\")
    If N% > 0 Then CurrentUser = Mid$(CurrentUser, N% + 1)
    If GetTokenInformation(hToken, TOKEN_ELEVATION_TYPE, tkElevation, 4, lRetLen) = 0 Then
        Err.Raise Err.LastDllError, , "Could not retrieve Token Information!"
    Else
        Print "Using TOKEN_ELEVATION_TYPE,"
        Select Case tkElevation
            Case 1
                Print CurrentUser & " is not using elevated privileges," _
                    & " or UAC is turned off!"
            Case 2
                Print CurrentUser & " is using elevated privileges!"
            Case 3
                Print CurrentUser & " is not using elevated privileges!"
        End Select
    End If
    If GetTokenInformation(hToken, TOKEN_ELEVATION, tkElevation, 4, lRetLen) = 0 Then
        Err.Raise Err.LastDllError, , "Could not retrieve Token Information!"
    Else
        Debug.Print tkElevation
        Print "Using TOKEN_ELEVATION,"
        Select Case tkElevation
            Case 0
                Print CurrentUser & " is not using elevated privileges!"
            Case Else
                Print CurrentUser & " is using elevated privileges!"
        End Select
    End If
End Sub

Resizing ListView to Form and Vice Versa

$
0
0
I had a form designed where only a portion of the Listview is showing.
I wanted to Resize the Form and have the LIstview resize with it, but limit the Form Resizing to the
Maximum number of columns in the Listview.
The following code works well for this situation.



Code:

Private Sub Form_Resize()

  Dim i As Integer
  Dim iWidth As Integer
 
  '---------------------------
 
  '---------------------------
  'Listview and Form Resizing
  '--------------------------

  'Keep Miniumu Form Width = Design Width
  If Form1.ScaleWidth < lvTable.Width Then
      Exit Sub
  End If

  'Sum the Column Widths
  With lvTable
      For i = 1 To .ColumnHeaders.Count
        iWidth = iWidth + .ColumnHeaders(i).Width
      Next
  End With

  'Make sure Listview Resizes with Form
  lvTable.Width = Form1.ScaleWidth
 
  'Keep Max Form Width = Listview Width
  If Form1.ScaleWidth > iWidth Then
      Form1.Width = iWidth
  End If
 
End Sub

[VB6] Bare Bones Worker Thread

$
0
0
This is an example of how you can use very simple worker threads in VB6 without an ActiveX EXE or a third party threading library. There are severe limitations on what you can accomplish this way, but enough to still make the technique useful:

Quote:

I am trying to have my program check is a mapped network drive is actually connected, and change the curDrive variable based on the result. It works okay, but if the drive is still mapped and the drive is not available, there is a long delay while the program tries to connect (4-6 seconds). I tried two methods and both ways have this delay.

This Demo program shows one way to deal with this by having a UserControl call GetFileAttributes() on a worker thread and use a Timer control to poll for eventual completion. The same technique can be used for other long running API calls. For example doing drive mapping within your program by calling WNetUseConnection().

The key is to avoid anything that requires COM, thread-local storage, and other VB environmental factors to be initialized. This radically limits the statements you can use, rules out VB exception handling, method calls, and so on.


One way to accomplish the task at hand might be to use VB's GetAttr() function. However that is only helpful if we could use error handling since what we want here is to detect success or failure and not the attributes themselves.

So this takes us to directly calling the GetFileAttributes() API. A solution, however calls to entrypoints defined using VB Declare statements requires the use of infrastructure that is not available to simple worker threads.

We can avoid this by defining the API call in the type library GetFileAttributes.tlb we reference in our program. The ODL source is also provided here and can be recompiled if necessary using the MIDL compiler from a Windows SDK.

Code:

[
    uuid(D03ED253-E130-4f20-A145-A5AE627A0875),
    helpstring("Kernel32 Query Subset Type Library")
]
library Kernel32Subset
{
    [
        helpstring("Some queries."),
        dllname("Kernel32")
    ]
    module Queries
    {
        [
            helpstring("Retrieve file system attributes for a specified file or directory."),
            entry("GetFileAttributesW")
        ]
        long int _stdcall GetFileAttributes([in] long int lpFileName);
    };
};


Third party threading libraries would let us do more by creating new COM Apartments we can run code in. However for simple tasks like this we can get along without them, since sadly they are seldom made available in "thin and lightweight" DLLs. Those that I can think of all tend to wrap a ton of things into one giant DLL. Not that these other things aren't useful, but usually you just don't need them.

This technique avoids any additional runtime dependencies at all.


To test from within the VB6 IDE, which should always be run with full administrative privileges (i.e. elevated), you will need to set up drive mapping in that context. While this didn't matter in the old pre-Vista days things have changed and drive mappings exist separately for each user context (elevated and standard).

So I am including another Project (MapTemp) which you should compile first. Run MapTemp.exe elevated (right-click "Run as administrator"). Here you can provide a file share and credentials and it will temporarily map the share to an available drive letter which it will report to you.

Name:  sshot1.png
Views: 116
Size:  10.3 KB

Note that it does this on the UI thread, and in some cases it will take long enough that MapTemp becomes "unresponsive." Just wait it out, but this does show exactly the sort of thing that has been addressed within the drive query Demo!

Now you can test the Demo.vbp drive query Project from within the elevated IDE. After testing, either click the Unmap button or just close MapTemp and it will eliminate the temporary mapping.

Name:  sshot2.png
Views: 75
Size:  7.8 KB


A more "realistic" test is to compile the Demo, do a persistant drive mapping via Explorer, etc. and then reboot. When the system comes back up go ahead and run Demo without elevation, and enter the drive letter you mapped. This way you'll see more delay and the Demo's UI should remain responsive (drag it around on the screen, etc.).
Attached Images
  
Attached Files

[RESOLVED] Convert your application to Shareware (many ways..)

$
0
0
This project is created in vb6 for converting your vb6 compiled exe's to shareware you can set expiry to days,counts or date..you can set trial key or full secret codes to unlock the application.Just take a view Download it write a comment below :)
P.S: i don't know the original author of this project but I'm not :D

Attachment removed by Moderator since PlanetSourceCode does not allow source code to be posted on another website without the authors permission. You can find the source here

[VB6] Harden Your Applications Against Hijacking

$
0
0
Defending software from piracy and abuse is a game of attrition. After all, unless you stick to remote server code you put everything the cracker needs right into his hands. Even when you don't provide public downloads you can't trust your legitimate users, who may well employ less scrupulous people to do their burger flipping. So you want to take advantage of as much security as you can afford, and you do this in layers that impede various points of access.

Remember, people who insist that "security by obscurity" isn't security all are probably trying to sell you some expensive and awkward cryptographic tool. Then you end up with passwords and keys for that which you have to secure through obscurity anyway!

The demise of Windows XP makes many new security technologies introduced with Vista practical to use in more applications, and Vista even improved on a few that came along during XP's long gasping at life. You can finally feel free to abort execution whenever your sensitive applications are being run on an insecure pre-Vista system!


Name:  Status.png
Views: 47
Size:  24.5 KB


Hijacking Stealth

One of the simple things you can do is add some stealth to thwart application hijacking.

We see forum thread after thread on the use of "spy" tools and window spelunking (window enumeration and pattern sniffing) to try to get the handles of controls in your application to try to make it dance like a puppet. The usual motivation is try to steal functionality from the free EXE version of software you have written when they want to avoid paying for the licensed full-function EXE with an Automation interface or DLL you sell. Don't discount the copy/paste coder who simply can't handle an API and finds copy/paste hijacks easier to use instead either.

VB6 comes with a set of "windowless controls" that were primarily meant for use in custom OCXs meant to be run within the context of IE web pages. These duplicate a number of the intrinsic VB6 controls, and while Microsoft claims not to support them they still work just fine even as late as Windows 7 and probably Windows 8.1. They don't replace all other controls and they have a few quirks here and there, but use as many of them as practical - they're mostly "drop in replacements" for the intrinsic controls.


Code Stealth

Another common defensive technique is to try to make code spelunking harder.

This usually consists of combining some manual obfuscation with native code compiles. Sensitive logic can be housed in classes with obscure and misleading names. Every little bit helps, and to keep the burden on yourself lower you might restrict this practice to your most sensitive logic, such as anything dealing with encryption keys. Class names that look like a hex value (e.g. "D009A67C") can be effective, or even proper names can work ("Cynthia" or "AbdulHakkim" or "BabeRuth"). Silly? Not as much as you might think.


Data Stealth

And what about data?

Well, some of it may be sensitive and the rest of it not so much. Some may be within your EXE and the rest in external files. Focus on the most sensitive information to get the most bang for your extra effort.

Just like class names, you can obscure data (particularly text) in your EXE to help fend off those code spelunkers. You can put data into custom resources in compressed and/or obfuscated form. Even XORing text with a decently long "key" pattern is better than doing nothing. When you only need ASCII text then ANSI is safe, though if you actually use characters above &H7F you might be better off using UTF-8 encoding before XORing.

The same can apply to data in external files, but you might want to use somewhat stronger encryption. Don't go overboard though. There is no reason to make things too hard on yourself unless you're guarding State Secrets.


How Can Windows Help?

Beginning prior to Vista but maturing since then we have a number of stealthing and hardening techniques available. Most of these defend against attempts to probe or modify your code to take control of it through modification or hacks like DLL Injection.


Code Signing

This isn't always practical because you need to acquire and maintain code signing certificates as well as guard your "reputation" to avoid certificate expiration or revokation. Still, it is the only tool Windows offers to guard your EXE against modification by a cracker.

However even this isn't as valuable as it might be. The "bar to entry" is so high that users are accustomed to installing and running programs that are not signed at all or have suspicious (self-signed, expired, etc.) certificates.


Hardware Protections

This is really the NX ("no execute") or DEP ("Data Execution Prevention") technology that was added to x86 and x64 CPUs over a decade ago. It isn't compatible with all programs, but any clean VB6 program and most of the libraries it would use certainly should be.

Starting with Vista, Windows has supplemented this with ASLR (Address Space Layout Randomization) or Dynamic Basing. This makes it tougher to probe your code using cracker tools that use techniques originally intended for binary debuggers.

Both DEP and ASLR are opt-in technologies, though the savvy PC user has changed his system DEP setting from Windows Client "opt-in" to "opt-out" so that DEP is applied to processes by default.

Since you can't trust users (after all the crackers are "users") you can do a few things.

When your EXE is linked you can specify "Hard DEP" and opt into ASLR. When your EXE is run you can detect whether DEP is active and if not try to turn on "Soft DEP" and if this fails terminate excution.


More Windows Protections

Structured Exception Handler Overwrite Protection (SEHOP) must be done by your application installer. It involves writing a registry key into HKLM.

Heap Metadata Protection can be accomplished in code when your program starts.

At this point I suggest you read the Microsoft white paper that was produced a few years ago after Vista technology was finally widely deployed:

Windows ISV Software Security Defenses

This brings together many of the new application security features Vista brought to the table. I'm a little shocked that these aren't very well known to VB6 programmers, I haven't found anything on the topic after many web searches. Though aimed at C/C++ programmers much of it also applies to other native code compilers.


The Code

Finally we've reached the sample code. Here are several items you can use to help implement some of Microsoft's recommendations that apply to VB6 programs.


Using the HullIntegrity class

Create an instance, call the RaiseShields() method.

RaiseShields() returns True when heap corruption detection and DEP have successfully been opted into or were already in effect.

If it returns False then FailReason and LastSysError can be used to perform additional failure analysis programmatically, or for reporting to the user why your program has decided not to run.

Corbomite = True means "permanent DEP" was set on PE file.

Maximum = True means running under Windows Vista or later. Might not return True when your application runs with appcompat version lies (XP, etc.).

The VerifyHullIntegrity demo Project illustrates basic use.

Ideally you would terminate if RaiseShields() returns False or if Corbomite or Maximum are False after the call. Terminating when run under Windows XP is a judgement call, but a safer one each day now that XP support has ended. You might choose to set Maximum = True even for Windows XP SP3 by calling GetVersionEx() and evaluating the results of that. XP SP2 and earlier aren't nearly as safe though.


Using the HardenPE utility

This can be as simple as dragging your compiled EXE's, DLL's, or OCX's icon onto HardenPE.exe's icon and dropping it there. Running HardenPE.exe with no dropped file will let you browse to the PE file to be "hardened."

You could easily make a non-GUI version of this for use in scripted builds.


Using the QueryPE utility

Just like using hardenPE but it doesn't make any changes. It just reports the current status of the DEP and ASLR attributes.


DEP opt-in, Address space layout randomization opt-in

Can be accomplished at runtime via HullIntegrity.RaiseShields() call.

Better accomplished by "hard opt-in" which HardenPE.exe does for you.


/SAFESEH exception handler protection

Not tested with VB6 EXEs. Requires a newer Link.exe than VB6 ships with (version 8.0 or later?) and interception of the Link run during VB6 *Make* to use this switch.


SEHOP opt-in

Not tested. Accomplished during installation by writing a special registry entry for your application.

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\
Image File Execution Options\MyExecutable.exe]
"DisableExceptionChainValidation"=dword:00000000


Heap corruption detection

Can be accomplished at runtime via HullIntegrity.RaiseShields() call.


Testing

  • Compile all three Projects: HardenPE, QueryPE, and VerifyHullIntegrity.
  • Run VerifyHullIntegrity and examine the MsgBox.
  • Drag VerifyHullIntegrity.exe onto Query.PE.exe, drop. Examine the MsgBox.
  • Drag VerifyHullIntegrity.exe into HardenPE.exe, drop. Examine the MsgBox.
  • Run VerifyHullIntegrity again, examine the MsgBox.
  • Drag VerifyHullIntegrity.exe onto Query.PE.exe, drop again. Examine the MsgBox.



Additional Reading

On the effectiveness of DEP and ASLR

Quote:

DEP (Data Execution Prevention) and ASLR (Address Space Layout Randomization) have proven themselves to be important and effective countermeasures against the types of exploits that we see in the wild today. Of course, any useful mitigation technology will attract scrutiny, and over the past year there has been an increasing amount of research and discussion on the subject of bypassing DEP and ASLR. In this blog post we wanted to spend some time discussing the effectiveness of these mitigations by providing some context for the bypass techniques that have been outlined in attack research.
Inside the Windows Vista Kernel: Part 3

Quote:

This series has so far covered Windows Vista kernel enhancements related to processes, I/O, memory management, system startup, shutdown, and power management. In this third and final installment, I take a look at features and improvements in the areas of reliability, recovery, and security.
Attached Images
 
Attached Files

Liistbox and EditBox 3.5 Unicode and Transparent.

$
0
0
In this example are my best gEditbox and gListbox. As for glistbox nothing new, except I put a label to saw what happen if you choose listindex above 32768 in an ordinary listbox (not happen to glistbox)

I have include examples. You need to download a unicode free font like freesans, or you can change font name to Arial Ms Unicode if you want to see Chinese symbols, or just use tahoma or verdana for Cyrillic or other languages...

You can export doc that open with word (as UTF16 doc). You can import with copy and paste (using ctrl+V), or you can drag and drop from and to Word, or any other gEditBox.
gEditBox can colotize text by using a palette.

I also inlcude a second example (gEditBox3_5) with a gEditbox in a resizable form, and introduce how you can reformat text with the wrapping process. What is missing for now is a fast undo redo process. But I am working about it. I check that last example with 5000+ lines...colorized and perform word wrapping..as you type. Also there is an export to html.

**************************//********************************************************//************************
Update version of geditbox (drag and drop work fine, and backspace delete empty lines in word wrapping state)
Attached Files

Convert MD5 (Hash) To Original Text

$
0
0
hi
i convert a value to MD5 (Hash), now how can convert to original value?

[RESOLVED] Convert MD5 (Hash) To Original Text

$
0
0
hi
i convert a value to MD5 (Hash), now how can convert to original value?

Blur Form Or Explorer when Click on button for 30 Sec

$
0
0
hi
Up to now use from Avast antivirus?
when we want disable that,explorer dark and blur...
if in vb6 can do it? when click on button form a little dark Or a little opaque?
As shown:
Name:  dark.jpg
Views: 43
Size:  36.4 KB
Name:  dark.jpg
Views: 43
Size:  36.4 KB
Attached Images
 

[vb6.0] Pragmatically Enable/Disable notification and UAC

$
0
0
Hi,

This code will allow you to pragmatically enable/disable both the notification and the UAC

Code:

'Pragmatically enable/disable both the notification and the UAC
'Author: Nightwalker83
'Date: 19/07/2014
'http://aaronspehr.net/
Option Explicit

Private Declare Function RtlAdjustPrivilege Lib "NTDLL" (ByVal Privilege As Long, ByVal Enable As Boolean, ByVal Client As Boolean, WasEnabled As Long) As Long
Private Declare Function RegSetValueExA Lib "advapi32.dll" (ByVal hKey As Long, ByVal lpValueName As String, ByVal Reserved As Long, ByVal dwType As Long, lpData As Long, ByVal cbData As Long) As Long
Private Declare Function RegOpenKeyEx Lib "advapi32.dll" Alias "RegOpenKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, ByVal ulOptions As Long, ByVal samDesired As Long, phkResult As Long) As Long
Private Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As Long) As Long

Public Sub DisableUac()
    Dim lKey As Long
   
    Call RtlAdjustPrivilege(17, True, True, 0)
    If RegOpenKeyEx(&H80000002, "SOFTWARE\Microsoft\Security Center", 0&, &H20000 Or &H2& Or &H4&, lKey) = 0& Then
        If (RegSetValueExA(lKey, "UACDisableNotify", 0, 4, 0, 4) = 0&) Then
            RegCloseKey lKey
        End If
    End If
    If RegOpenKeyEx(&H80000002, "SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", 0&, &H20000 Or &H2& Or &H4&, lKey) = 0& Then
        If (RegSetValueExA(lKey, "EnableLUA", 0, 4, 0, 4) = 0&) Then
            RegCloseKey lKey
        End If
    End If
End Sub

Public Sub EnableUac()
    Dim lKey As Long
   
    Call RtlAdjustPrivilege(17, True, True, 0)
    If RegOpenKeyEx(&H80000002, "SOFTWARE\Microsoft\Security Center", 0&, &H20000 Or &H2& Or &H4&, lKey) = 0& Then
        If (RegSetValueExA(lKey, "UACDisableNotify", 0, 4, 1, 4) = 0&) Then
            RegCloseKey lKey
        End If
    End If
    If RegOpenKeyEx(&H80000002, "SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", 0&, &H20000 Or &H2& Or &H4&, lKey) = 0& Then
        If (RegSetValueExA(lKey, "EnableLUA", 0, 4, 1, 4) = 0&) Then
            RegCloseKey lKey
        End If
    End If
End Sub


Nightwalker

Test two vb codes for changes

$
0
0
This is a small program, based on gEditBox. I made this for gEditBox because I have some customize..custom controls and I want to find the differences.
It is a fast coding (one day) so...I do the basics...Two edit boxes, on with auto colorizing vb6 code (my way), and the other to put by three way code for testing similarity.

There is also a small gEditbox for searching.
No word wrapping enabled here for clarity. Also form isn't sizable (you can arrange controls better if you like).
From left there are buttons for:
1. Clear Up (clear "up" textbox - ctrl a and delete is the same but slower). "Up" is the name of up textbox...

- We want to find from Up textbox the similarities with the "Down" textbox. (You may think that these are the same....but the Up textbox..colorize the code, and the searching is like a moving in chess...we going forward but we looking from the other side to our side. This is my first such a search routine...Any idea for to help for a better code is appreciated.

2. Load Up (we load from a temporary test.doc file in %temp%.

3. Copy Down...(copy from Up to Down)

Under Search Box, Buttons up (search in UP editbox), and down (search in DOWN editbox) Searching means also moving to next. In search box we write something to be "like" not equal (also automatic embedded asterisks in fron and behind the searching string). Another way to search is by automatic select word, or you can select a part of a line and perform search in this or the other editbox (from any of these).

4. Clear Mark
This colorize the code "again" the color in Up editbox and colorize with one "neutral" color the down editbox. Because when we do a search (our scope) both editboxes changes colors.

There is a frame named Down Text with these buttons:
5. Clear Down - Same as for UP.
6. Mark new or changed lines of code (our goal)
7.Move Top Line (because searching done from cursor, we set cursor to top, first line)
8. Move to change. All changes lines are colored, so this is very helping
9. Move Up as Down. Moving up to same line in number. Maybe not the same line as content.

10. Save down. AS you see we load Up but we save Down. This is for making at the down the merging...So we need to feed data to Up and export only from Down. We can copy to clipboard, or we can drag (7941 lines has the gEditBox code...end perform good), and we can save to test.doc as unicode utf16 with doc extension (open with Word).
Name:  tester.jpg
Views: 131
Size:  87.4 KB
Attached Images
 
Attached Files

[VB6] Scrollio Picture Viewer UserControl

$
0
0
This isn't anything amazing but I haven't seen an equivalent here packaged for easy reuse.

Scrollio is a simple VB6 UserControl with no dependencies that provides a scrollable view of any StdPicture. In addition to scrollbars it allows zooming, either to fit its window or to a specified zoom factor.

When the ZoomFit property is True Scrollio will rescale to match any resizing done by the container's (Form's) logic.

VB6's LoadPicture() has some image file type limitations, so if you need to be able to load PNG or TIFF images you could use the GDI+ Flat API or the convenient WIA 2.0 wrapper library.


Name:  sshot.png
Views: 47
Size:  21.5 KB


The control itself is fairly small, and almost all of the attachment archive's size comes from the rest of the demo Project ("Scrolliodo") and even more from the sample images provided.


To use it in your own Projects just copy Scrollio.ctl and Scrollio.ctx to your Project's folder and then do an "Add file..." in the IDE to add Scrollio.ctx to your Project.


Tested on Windows 95 OSR2, Windows XP SP3, Windows Vista SP2, and Windows 7 SP1.
Attached Images
 
Attached Files
Viewing all 1512 articles
Browse latest View live