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

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

VB6-JACMail Crypto Service

$
0
0
SECURE EMAIL - JACMail2 Companion Program

Making email secure is easier said than done. Some people are under the illusion that TLS (Transport Layer Security) provides protection, but nothing could be further from the truth. As the name suggests, TLS only provides protection during a single transport leg. It does not protect the message at the source or the destination, nor any of the MTA's in between. In one respect TLS is overkill because it encrypts everything, when in reality the only component that needs to be encrypted is the message itself. The body header does not need to be encrypted.

The only way to truly protect a message is to encrypt it at source, and decrypt it at the final destination. PGP does this and has been around for ages, but has not gained very wide acceptance. The difficulty is that it requires the use of Public/Private key pairs, and most non-technical users have difficulty managing keys.

I wrote my own email client program because of dissatisfaction with what was commercially available. I even went so far as to implement TLS, but abandoned it after I realized how little protection it offered. Then I wrote an algorithm that embedded the key within the encrypted message. However, I again abandoned that effort because I could not guarantee that some hacker would not decompile my program and discover the algorithm. The worst part is that like most encryption systems, you never know when the system has become compromised.

So I set out to design a system that would work with existing mail systems and did not require the use of Public/Private keys.

1. Sender creates Random Key (eg. EE F2 26 2A BF C1 BC 7A). Key can be any size up to 512 bits.

2. Sender hashes the key, derives a new key from the hash, encrypts the message (not including message header), and encodes the message using Base64 (eg. XLVWGcE6aiWA5y94Bw==).

3. Sender then forwards the encrypted/encoded message as text (not flagged as encoded). It then hashes the encrypted/encoded message, derives a key from the hash, and uses it to encrypt the Random Key (eg. EE F2 26 2A BF C1 BC 7A is encrypted to 37 98 D9 A1 25 6D 1D 49). The encrypted Random Key, as well as the numeric value from the Message-ID (eg 41827.5099189815) are saved in a database.

4. Receiver retrieves the message, sees that it is encoded, and initiates decryption.

5. Receiver app displays a list of known encryption sources using the domain name from the Message-ID (eg <41827.5099189815@key.domain.com>). If the incoming Message-ID Domain Name is not included in the list, the receiver is prompted to add it to the list with a warning. This step provides a degree of protection against phishing.

6. At this point, both the sender and the receiver possess the encrypted message and the sender possesses the encrypted key. The receiver then connects with the Message-ID Domain Name on a specified port, and sends the Message-ID to the Sender. The Message-ID server doesn't necessarily have to be the actual server that sent the message, but it must have access to the encrypted Random Key and the Message-ID.

7. The sender server looks up the Message-ID, and recovers the associated encrypted Random Key. It then sends the encrypted Random Key back to the receiver, and saves the IP address and date/time used to recover the key. This step provides protection against the contents of the message being modified. Subsequent requests from non-authorized addresses are ignored.

8. The receiver hashes the encrypted/encoded message, derives a key from the hash, and uses it to decrypt the Random Key. The receiver then decodes and decrypts the message, and saves the encrypted Random Key.

9. Subsequent requests to decrypt the message use the saved key.

10. The sender now knows when the message was read. Subsequent requests for the key would be highly suspicious and are blocked, with manual intervention required to unblock. If it is later discovered that an unauthorized request was made for the key from an unknown IP address, the contents of the message have probably been compromised, and appropriate measures should be taken. With most encryption systems, one never knows when or if the system has been compromised. For that reason, Asymmetric Encryption systems now require 2048 bit keys, and rather extreme security measures to protect the Private key.

J.A. Coutts

Note: The JACMailSvc program requires the Microsoft NT Service Control (NTSVC.ocx), which is readily available on the Net.
Attached Files

VB6-JACMail2 Email Client

$
0
0
<P>JACMail Version 2 is very similar to Version 1 on the surface. Under the hood however, there have been substantial changes. JACMail is an Email Client Program designed to allow fast and efficient recovery of email from a POP3 server, and the sending of email through an SMTP server. It is primarily oriented towards text based messaging with attachments, and does not directly support highly formatted HTML based email or embedded objects. It receives and stores both text/plain and text/html messages, and Web based emails (HTML) can be sent to your default browser for viewing. It also supports Plain Authentication based POP3 and multiple mailboxes. The mailboxes are stored in an Access database utilising ODBC.
</P>
<P>The code uses IP Version independent system calls, so it will only work on Windows systems that actively support both IPv4 and IPv6. That more or less restricts it to Windows Vista or later. It has been tested on Windows Vista, Win 7, and Win 8.1, and utilises the following standard components and references:<BR>
RICHED32.DLL<BR>
RICHTX32.OCX<BR>
COMDLG32.OCX<BR>
MSSTDFMT.DLL<BR>
MSBIND.DLL<BR>
MSADODC.OCX<BR>
MSDATGRD.OCX<BR>
which the user must have available in order to compile the program.
</P>
<P>Unlike Version 1, this version is Unicode comapatible. It is NOT Unicode compliant. Email still requires ASCII.
</P>
<P>Version 2 supports message encryption. Although any JACMail2 Client can receive and decrypt messages sent by JACMail2, the sending of encrypted messages requires a server component (posted as a separate item).
</P>
J.A. Coutts
Attached Files

Registry Editor - demonstrates how to use various registry related API functions.

$
0
0
Registry Editor is a basic utility for editing the Windows registry. The user can view, create, modify, and delete keys and their values. It shows how the REG_BINARY data type can be handled by converting data to and from an escape sequence of hexadecimal characters. It can also detect which hive keys are present. You can see this by running the program in various compatibility modes such as those for Windows 98 and XP.

The program also demonstrates how to use registry related API functions such as RegCreateKeyEx, RegEnumKeyEx, RegEnumValue, RegQueryInfoKey, and RegQueryValueEx.
Attached Files

Select query in visual basic 6

$
0
0
Hi guys,

I'm a newbie to this forum and to vb6.I just want to ask some help for my query.

I have a table prodmaster with fields pieceCode,dozenCode,caseCode, proddesc ,inventoryUnit.
example: pieceCode | dozenCode | caseCode | proddesc | inventoryUnit
110 111 112 Apple 72

note: inventory unit is constant and all code refers to one item only
I also have a flexgrid and a txtinvno.text

If I put invoice number in the textbox say inv#00152
My flexgrid displays all the products issued in that invoice (inv#00152) and those products may be served in dozen,in piece or in case.


what I want to do now is if my flexgrid(2,1)=rs!pieceCode or flexgrid(2,1)=rs!dozenCode or flexgrid(2,1)=rs!caseCode then flexgrid(2,2)=flexgrid(2,2)/rs!inventoryUnit.

the value of flexgrid(2,1) piececode,dozencode,or casecode of the product issued since we serve some items in piece,dozen, or case.
the value of flexgrid(2,2) is the quantity issued.

.
can anybody out there help me? what should be my query for this.


I tried Select * from prodmaster where prodCode='"& flexgrid(2,1) &"' or dozenCode='"& flexgrid(2,1) &"' or caseCode='"& flexgrid(2,1) &"' ,

I know it can't be done this way,

help please.

Scroll Bar with LONG value...updated

$
0
0
This is an example (the scrollio picture viewer that I convert to take dib) with new control LargeBar
Now I can open a 20 Mpixel photo and select zoom 2000%.

The code of scrollbar is small. Return from vertical to horizontal bar automatic (we can change manual if we want). No flickering and has tab stop so we can use keyboard, arrows and pageup and pagedown,

For history the original scrollio from dilettante is here http://www.vbforums.com/showthread.p...er-UserControl

New version of scrollio, a dilettante's simple picture viewer. But now can open jpg and rotate according the exif property.
ScrollBar updated to work perfect and with a good looking design. Now we can export and import from clipboard as DIB (without loosing dpi). Also i have a menu to see someone how the image can be with 300 dpi as 1:1 ratio (1 pixel of image for 1 pixel of screen). Also I put two pictureboxes, one grab and fit the scrollio image (the part we saw) and the other is using to print two axes on a small picture of the dib inside scrollio, marking the movement of pointer above viewer. As we move on the picture, or the picture, we see the exact coordinates in pixels, in any size and any scrolling position (pure mathematics).
Also I put a slider as a scale controller...and you can see how fast dib works. Also I put a drawing over the displayed image as a target...to demonstrate how we can print on the picturebox (the displayed part of scrollio).

scrollio.image is the picturebox
scrollio,dib is the cDibSection
When the image was ending from the painting send an event PaintEnd so we can draw on image or we can grab it
Also there is a new event, a mousemove, at the "paper" the picturebox inside scrollio, that fires in any state of button, and before processed in the command for hand scrolling. This is needed for taking the current x and y, when no action for redrawing needed..So with that I insert action to have a feedback;
Attached Files

VB6-SubNet representation

$
0
0
Applying a mask to an IP address is relatively straight forward in "C". You simply do a bit wise "AND" between the two. Because Visual Basic does not do bit arithmetic very well, it is a little more complicated.

Both IPv4 and IPv6 drop leading zeros, so they are an inconsistent length. IPv4 uses four bytes (32 bits), displayed as decimal numbers separated by dots (eg. 192.168.1.2), whereas IPv6 uses 16 bytes (128 bits) displayed as hexadecimal numbers separated by colons (eg. 2001:0:53aa:64c:406:8e9d:934b:458d). IPv6 is even more difficult to work with, as a group of zero elements can be replaced with a double colon (eg. 2620:0:ccc::2). The easiest way to work with them is to convert them to byte arrays, but since they are almost always transmitted and displayed as text, I found the best way is to convert them both to hexadecimal strings and padd the leading zeros.

Classless Inter-Domain Routing (CIDR) representation is the same(eg. 192.168.1.2/32 & 2001:0:53aa:64c:406:8e9d:934b:458d/128) for both. The part behind the "/" is the number of significant bits. For example, 192.168.1.0/24 is the same as using 192.168.1.0 with a netmask of 255.255.255.0.

The attached program allows you to enter an IPv4 or IPv6 network using CIDR. The program then converts the network into a fixed length starting address and a fixed length netmask. For example, 2620:0:ccc::2/120 is converted to: 262000000ccc00000000000000000000/FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00
Notice that the last 2 in the address has been dropped. That is because the last byte (8 bits) is insignificant, so the starting address is actually 2620:0:ccc::0.

Once you have defined the network, you can enter an address in the bottom text box to see if it belongs to the defined subnet.

J.A. Coutts
Attached Files

[VB6] JPEG-compressed TIFF File Reader (GDI+)

$
0
0
You probably know that GDI+ is useful for loading various image formats, but GDI+ also has issues with every format it loads. For TIFFs specifically, one of the compression options it won't support is JPEG compression. Well, GDI+ does support loading/writing JPEGs, so it isn't that difficult to get these JPEG pages loaded when all is said and done.

The attached txt file is a VB class. After you save it to disk, rename it to .cls
I've also included a JPEG encoded TIFF file for you to play with, but they aren't that hard to find on the web.

A note here. I did not attempt to handle JPEG-6 compression, just JPEG-7. The v6 is pretty old nowadays and if I find the time, maybe I'll play with it. Only have 1 example with v6 encoding, most you will find now is v7.

So, to play.
1) Download the txt file & rename it .cls
2) Create a new project and add that class to your project
3) On your form, add two controls: combobox and commandbutton
4) Set the combobox style to 2
5) Paste this code to your form & run project
6) Drag/drop a TIFF onto the form
Code:

Option Explicit

Private Declare Function GdipDeleteGraphics Lib "GdiPlus.dll" (ByVal mGraphics As Long) As Long
Private Declare Function GdipDrawImageRectRectI Lib "GdiPlus.dll" (ByVal hGraphics As Long, ByVal hImage As Long, ByVal dstX As Long, ByVal dstY As Long, ByVal dstWidth As Long, ByVal dstHeight As Long, ByVal srcX As Long, ByVal srcY As Long, ByVal srcWidth As Long, ByVal srcHeight As Long, ByVal srcUnit As Long, ByVal imageAttributes As Long, ByVal Callback As Long, ByVal callbackData As Long) As Long
Private Declare Function GdipCreateFromHDC Lib "GdiPlus.dll" (ByVal hDC As Long, hGraphics As Long) As Long
Private Declare Sub GdiplusShutdown Lib "gdiplus" (ByVal Token As Long)
Private Declare Function GdiplusStartup Lib "gdiplus" (Token As Long, inputbuf As Any, Optional ByVal outputbuf As Long = 0) As Long
Private Type GdiplusStartupInput
    GdiplusVersion          As Long
    DebugEventCallback      As Long
    SuppressBackgroundThread As Long
    SuppressExternalCodecs  As Long
End Type

Private m_Token As Long
Private m_TIFF As cTIFFreader

Private Sub Form_Load()
    If Me.Combo1.Style <> 2 Then
        Me.Show
        DoEvents
        MsgBox "The combo box must be set to Style=2", vbExclamation + vbOKOnly
        Unload Me
        Exit Sub
    End If

    Call pvCreateToken
    If m_Token = 0 Or m_Token = -1 Then
        Me.Show
        DoEvents
        MsgBox "Failed to start up GDI+", vbExclamation + vbOKOnly
        Unload Me
        Exit Sub
    End If
    Set m_TIFF = New cTIFFreader
   
    Me.ScaleMode = vbPixels
    Me.Combo1.Move 0, 0, Me.ScaleWidth \ 2
    Me.Command1.Move Me.Combo1.Width + 6, 0, Me.Command1.Width, Me.Combo1.Height
    Me.Command1.Caption = "Refresh"
    Me.OLEDropMode = vbOLEDropManual
    Me.Move (Screen.Width - 10245) \ 2, (Screen.Height - 6585) \ 2, 10245, 6585
End Sub

Private Sub Form_Unload(Cancel As Integer)
    Set m_TIFF = Nothing
    If Not (m_Token = 0& Or m_Token = -1&) Then pvDestroyToken
End Sub

Private Function pvCreateToken() As Boolean
    Dim GSI As GdiplusStartupInput
    On Error Resume Next
    If Not m_Token = -1 Then
        GSI.GdiplusVersion = 1&
        Call GdiplusStartup(m_Token, GSI)
        If m_Token = 0 Then
            m_Token = -1&
        Else
            pvCreateToken = True
        End If
    End If
End Function

Private Sub pvDestroyToken()
    If Not (m_Token = 0 Or m_Token = -1) Then GdiplusShutdown m_Token
    m_Token = 0&
End Sub

Private Sub Command1_Click()
    Call Combo1_Click
End Sub

Private Sub Combo1_Click()
    If Not m_TIFF.ImageCount = 0& Then
       
        Dim hGraphics As Long, w As Long, h As Long, sngRatio As Single
        Dim x As Long, Y As Long, cx As Long, cy As Long
        Const UnitPixel As Long = 2&
       
        m_TIFF.Index = Combo1.ListIndex + 1
        w = m_TIFF.Width
        h = m_TIFF.Height
        cy = Me.ScaleHeight - Combo1.Height
        If Me.ScaleWidth / w > cy / h Then
            sngRatio = cy / h
        Else
            sngRatio = Me.ScaleWidth / w
        End If
        If sngRatio > 1! Then sngRatio = 1&
        cx = w * sngRatio
        cy = h * sngRatio
        x = (Me.ScaleWidth - cx) \ 2
        Y = ((Me.ScaleHeight - Combo1.Height) - cy) \ 2 + Combo1.Height
       
        Me.Cls
        GdipCreateFromHDC Me.hDC, hGraphics
        GdipDrawImageRectRectI hGraphics, m_TIFF.Handle, x, Y, cx, cy, 0, 0, w, h, UnitPixel, 0, 0, 0
        GdipDeleteGraphics hGraphics
    End If
End Sub

Private Sub pvReset()
    Dim t As Long, sItem As String
    Combo1.Clear
    For t = 1 To m_TIFF.ImageCount
        sItem = t & ". " & m_TIFF.Width(t) & " x " & m_TIFF.Height(t)
        sItem = sItem & "  DPI: " & CLng(m_TIFF.DPI_Horizontal(t)) & " x " & CLng(m_TIFF.DPI_Vertical(t))
        Combo1.AddItem sItem
    Next
    If Combo1.ListCount Then
        Combo1.ListIndex = 0
    Else
        MsgBox "No images were loaded"
    End If
End Sub

Private Sub Form_OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, x As Single, Y As Single)
    If Data.Files.Count Then
        m_TIFF.FileName = Data.Files.Item(1)
        Call pvReset
    End If
End Sub

Attached Files

Query Assistant - connect to databases and execute queries.

$
0
0
What is the Query Assistant?
A complete application that makes connecting to databases, executing and executing queries easier.

What can it do?
1. Connect to database using Microsoft ADO as specified by a connection string in a settings file.
2. If required, request the user for a password and/or user name and fill in the respective place holders in the connection string.
3. Load a query specified as a command line argument or as selected by the user from inside the program's interface.
4. Display input boxes for controlled input as specified by input place holders inside, if present, a query.
5. Execute a series of queries in a batch.
6. Export a query's results to a text file or Microsoft Excel spreadsheet.
7. Attach the file with the query's results to an e-mail, fill in the sender, recipient, subject, and body as specified in a settings file and then send it.
8. Insert data such the date, time, an operating system environment variable's value, an input box's value into a query or e-mail.

It also comes with an extensive help file describing:
1. What the program does.
2. The supported settings.
3. The supported command line arguments.
4. The supported file types for exported query results.
5. How to define input place holders in a query.
6. How to insert data into an e-mail or query.
7. How create a tiny example database, query and, settings file.
8. How to view a description for each control inside the interface.

An image showing the program's main interface, Microsoft Excel and Outlook:
Name:  qa.jpg
Views: 68
Size:  49.4 KB
Attached Images
 
Attached Files

[VB6] ListViewCustomSort Helper Class

$
0
0
I did a search here but couldn't find an existing implementation. There are several out there in the wild, dating back to an old Randy Birch example base on an even older MS KB item on sorting by date columns. So clearly people have been doing this since the early VB5 days, 1997-1998 or so.

ListViewCustomSort .cls and its companion ListViewCustomSortStatic.bas attempt to do the same thing written from scratch based on the Windows SDK. Since I wanted to make something more readily reusable it made sense to start writing anew based on the Common Controls ListView documentation.

This should be quicker with a better user experience than other techniques, for example creating extra "hidden" (width = 0) columns to sort on. However that's a perfectly viable solution as well. It just eats more memory.


What it Does

ListViewCustomSort works with both ActiveX ListView controls, the one in COMCTL32.OCX and the one in MSCOMCTL.OCX.

While you can use the existing sorting properies exposed by both ListViews for simple text sorts in ascending or descending order, there isn't a "custom sort" option and Compare Event like that provided by other controls such as the MSHFlexGrid.

ListViewCustomSort works in parallel with a ListView to provide such an event for custom sorting. While this version only handles single-column sorts you could enhance it to provide more than one column's text to the Compare Event handler.

In your Compare Event handler you get the column text of two rows to compare and you return a comparison result. In order to do something like a date or numeric compare you must compare ItemText1 and ItemText2 returning a numeric result:

Code:

'Return values:
'
'  -1 = Less Than
'    0 = Equal
'    1 = Greater Than

This usually requires some data conversion and conditional logic.


Using ListViewCustomSort

You must add ListViewCustomSortStatic.bas and ListViewCustomSort.cls to your project that uses ListViews. ListViewCustomSortStatic.bas is needed in order to implement the required API callback function.

Then in Forms with ListView controls where you want to do custom sorting, you add a separate instance of the ListViewCustomSort Class WithEvents in order to get a custom-sort Compare Event for each ListView. If your ListViews have identical sets of columns you can get by with a single ListViewCustomSort instance.

Then you write your Compare Event handler(s) to perform the custom sort comparisons.

To perform the custom sort you set ListViewCustomSort's .Ascending (Boolean) and .SortKey (Long: ListView column index, base 0) properties, and optionally its .TextMax (Long: max text width, default 256). Then you call the .Sort() method passing the ListView control reference.


The Demo

ListViewCustomSort is included in the attached archive which includes a self-contained demonstration project. This demo creates three columns of random data: a String, a Date, and a Single column.

ListViewCustomSort isn't need for the first column's data, but it is used for the other two which require some extra effort to make sorting work properly.

Name:  sshot.png
Views: 78
Size:  36.4 KB

The source code of Form1.frm may help make usage a little clearer:

Code:

Option Explicit

Private WithEvents ListViewCustomSort As ListViewCustomSort

Private Function MakeName() As String
    Const LETTERS As String = "abcdefghijklmnopqrstuvwxyz"
    Dim I As Long
    Dim IMax As Long
    Dim J As Long
    Dim Words() As String

    IMax = Int(3 * Rnd()) + 1
    ReDim Words(IMax)
    For I = 0 To IMax
        For J = 1 To Int(8 * Rnd()) + 2
            Words(I) = Words(I) & Mid$(LETTERS, Int(26 * Rnd()) + 1, 1)
        Next
        Words(I) = StrConv(Words(I), vbProperCase)
    Next
    MakeName = Join$(Words, " ")
End Function

Private Sub cmdSortBy_Click(Index As Integer)
    Select Case Index
        Case 0
            With ListView1
                .SortKey = 0
                .SortOrder = IIf(chkAscending.Value = vbChecked, lvwAscending, lvwDescending)
                .Sorted = True
            End With

        Case 1, 2
            ListViewCustomSort.Sort ListView1, Index, chkAscending.Value = vbChecked
    End Select
End Sub

Private Sub Form_Load()
    Dim I As Long

    Randomize

    Set ListViewCustomSort = New ListViewCustomSort

    With ListView1.ColumnHeaders
        .Add , , "Col 0", 3600, lvwColumnLeft
        .Add , , "Col 1", 1080, lvwColumnRight
        .Add , , "Col 2", 1080, lvwColumnRight
    End With
    With ListView1
        With .ListItems
            For I = 1 To 1000
                With .Add(, , MakeName()) 'String.
                    .SubItems(1) = Format$(DateAdd("d", -Int(1000 * Rnd()), Date), "m/d/yyyy") 'Date.
                    .SubItems(2) = CStr(20000! * Rnd() - 10000!) 'Single.
                End With
            Next
        End With
        Set .SelectedItem = Nothing
    End With
End Sub

Private Sub Form_Resize()
    If WindowState <> vbMinimized Then
        With Picture1
            .Move 0, ScaleHeight - .Height
            ListView1.Move 0, 0, ScaleWidth, .Top
        End With
    End If
End Sub

Private Sub ListViewCustomSort_Compare( _
    ByVal SortKey As Long, _
    ByVal Ascending As Boolean, _
    ItemText1 As String, _
    ItemText2 As String, _
    Cmp As Long)

    Dim Parts() As String
    Dim Date1 As Date
    Dim Date2 As Date
    Dim Single1 As Single
    Dim Single2 As Single

    Select Case SortKey
        Case 1
            Parts = Split(ItemText1, "/")
            Date1 = DateSerial(CInt(Parts(2)), CInt(Parts(0)), CInt(Parts(1)))
            Parts = Split(ItemText2, "/")
            Date2 = DateSerial(CInt(Parts(2)), CInt(Parts(0)), CInt(Parts(1)))
           
            Cmp = Sgn(CLng(Date1) - CLng(Date2))

        Case 2
            Single1 = CSng(ItemText1)
            Single2 = CSng(ItemText2)

            Cmp = Sgn(Single1 - Single2)
    End Select
    If Not Ascending Then Cmp = -Cmp
End Sub

Attached Images
 
Attached Files
Viewing all 1325 articles
Browse latest View live




Latest Images