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

Here's a better way to generate random nums than using Rnd

$
0
0
Using Rnd always gives you the same set of numbers, whenever you start the program. Even if you use Randomize first to set a random number seed at the start of the program, it will eventually cycle through all the numbers (plus there are certain patterns of numbers that you can see under certain situations). You can get a much better random number generator (in fact, cryptographically secure level of randomness) if you used the crypto API functions. Here's a simple program I made to demonstrate how to use the crypto API to generate random numbers.

Code:

Private Declare Function CryptAcquireContext Lib "advapi32.dll" Alias "CryptAcquireContextA" (ByRef phProv As Long, ByVal pszContainer As String, ByVal pszProvider As String, ByVal dwProvType As Long, ByVal dwFlags As Long) As Long
Private Declare Function CryptReleaseContext Lib "advapi32.dll" (ByVal hProv As Long, ByVal dwFlags As Long) As Long
Private Declare Function CryptGenRandom Lib "advapi32.dll" (ByVal hProv As Long, ByVal dwLen As Long, ByRef pbBuffer As Any) As Long

Private Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)

Dim hProv As Long
Dim Quit As Boolean

Private Sub Form_Load()
    Dim a As Long
    CryptAcquireContext hProv, vbNullString, vbNullString, 1, 0
   
    If hProv = 0 Then
        Unload Me
        Exit Sub
    End If
   
    Show
    Do Until Quit
        CryptGenRandom hProv, 4, a
        Cls
        Print a
        Sleep 100
        DoEvents
    Loop

End Sub

Private Sub Form_Unload(Cancel As Integer)
    Quit = True
    If hProv Then CryptReleaseContext hProv, 0
End Sub

Just paste the above code into your Form1, and make sure that its AutoRedraw property is set to True. Then run the program, it will generate a new random number every tenth of a second (that's what "Sleep 100" is for). I have it doing that instead of running at max speed, so as not to max out your CPU cycles and cause unnecessary heating of your computer if you leave it running for a while. If you don't intend to have it running for a long time, you can remove the Sleep 100 line of code, so it can run at maximum speed (limited only by your CPU speed). Just close the Form1 window to end the program (make sure you DON'T use the stop button in the VB6 IDE, or the Unload event won't fire, and it won't run the required cleanup function CryptReleaseContext.

CryptGenRandom will NEVER repeat a set of numbers, and will NEVER produce any visible pattern of numbers.

Viewing all articles
Browse latest Browse all 1448

Trending Articles



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