Frequently Asked VB Questions-VBForums
Results 1 to 21 of 21

Thread: Frequently Asked VB Questions

  1. #1

    Thread Starter
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Philippines
    Posts
    10,591

    Arrow Frequently Asked VB Questions

    In order to make this thread as tidy as possible pls. PM me all your comments, suggestions, improvements, modifications.... And pls. post only those that are only truly "Frequently Asked Questions".... Thanks!

    1. How to read/write ini?

    VB Code:
    1. Option Explicit
    2.  
    3. 'declares for ini controlling
    4. Private Declare Function GetPrivateProfileSection Lib "kernel32" Alias "GetPrivateProfileSectionA" (ByVal lpAppName As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long
    5.  
    6. Private Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpDefault As String, ByVal
    7. lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long
    8.  
    9. Private Declare Function WritePrivateProfileSection Lib "kernel32" Alias "WritePrivateProfileSectionA" (ByVal lpAppName As String, ByVal lpString As String, ByVal lpFileName As String) As Long
    10.  
    11. Private Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpString As Any, ByVal lpFileName As String) As Long
    12.  
    13. Private Sub Form_Load()
    14. On Error Resume Next
    15.  
    16. Dim File As String, OFLen As Double,  Str As String
    17.  
    18. File = "C:\temp.txt"
    19. OFLen = FileLen(File)
    20.  
    21. 'write few example sections:
    22. WriteIniSection File, "Test1", ""
    23. WriteIniSection File, "Test2", "Here shoud be found some text"
    24.  
    25. 'write few ini strings
    26. WriteIni File, "Test3", "Ini1", "This is ini 1"
    27. WriteIni File, "Test1", "Ini2", "This is ini 2"
    28.  
    29. 'inform we're written the data
    30. MsgBox Format((FileLen(File) - OFLen) / 1024, "0.00") & " KB data written to " & Chr(34) & File & Chr(34)
    31.  
    32. 'read the ini file
    33. Str = Str & "Test2 section: " & vbTab & ReadIniSection(File, "Test2") & vbCrLf
    34. Str = Str & "Test1 section: " & vbTab & ReadIniSection(File, "Test1") & vbCrLf
    35. Str = Str & "Ini1 string: " & vbTab & ReadIni(File, "Test3", "Ini1") & vbCrLf
    36. Str = Str & "Ini2 string: " & vbTab & ReadIni(File, "Test1", "Ini2") & vbCrLf
    37.  
    38. 'show data
    39. MsgBox Str
    40.  
    41. 'end application
    42. End
    43.  
    44. End Sub
    45.  
    46. '// INI CONTROLLING PROCEDURES
    47.  
    48. 'reads ini string
    49. Public Function ReadIni(Filename As String, Section As String, Key As String) As String
    50. Dim RetVal As String * 255, v As Long
    51. v = GetPrivateProfileString(Section, Key, "", RetVal, 255, Filename)
    52. ReadIni = Left(RetVal, v - 1)
    53. End Function
    54.  
    55. 'reads ini section
    56. Public Function ReadIniSection(Filename As String, Section As String) As String
    57. Dim RetVal As String * 255, v As Long
    58. v = GetPrivateProfileSection(Section, RetVal, 255, Filename)
    59. ReadIniSection = Left(RetVal, v - 1)
    60. End Function
    61.  
    62. 'writes ini
    63. Public Sub WriteIni(Filename As String, Section As String, Key As String, Value As String)
    64. WritePrivateProfileString Section, Key, Value, Filename
    65. End Sub
    66.  
    67. 'writes ini section
    68. Public Sub WriteIniSection(Filename As String, Section As String, Value As String)
    69. WritePrivateProfileSection Section, Value, Filename
    70. End Sub
    2. How to send e-mail?
    Have a look at this official FAQ article: How do I send an email using Outlook

    3.How to work with registry?
    VB Code:
    1. 'Savesetting
    2. Private Sub Form_Unload(Cancel As Integer)
    3.    SaveSetting "RegCust", "Startup", "Backup", strDate
    4.    SaveSetting "RegCust", "Startup", "LastEntry",intLastEntry
    5. End Sub
    6. 'GetSetting
    7. Private Sub Form_Load()
    8.    Dim intLastEntry As Integer
    9.    intLastEntry = GetSetting("RegCust", "Startup", _
    10.    "LastEntry", "0")
    11. End Sub
    12. 'DeleteSetting
    13. Private Sub cmdDelKey_Click()
    14.    DeleteSetting "RegCust", "StartUp", "LastEntry"
    15. End Sub
    16. Private Sub cmdDelSection_Click()
    17.    DeleteSetting "RegCust", "StartUp"
    18. End Sub
    19. Private Sub cmdUnInstall_Click()
    20.    DeleteSetting "RegCust"
    21. End Sub
    4. How to open Password protected Access db?
    VB Code:
    1. 'connection to secure database
    2. Dim Cnn As ADODB.Connection
    3.  
    4. 'In the place where you want to establish your connection, such
    5. 'as the Initialize event of a class module, enter the following:
    6.  
    7. Dim strConnect As String
    8. Set Cnn = New ADODB.Connection
    9.  
    10. 'Substitute your own User IDs, Password, Data Source, and System
    11. 'database in the connection string below
    12.     strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    13.         "Password=MyPassword;User ID=Administrator;" & _
    14.         "Data Source=C:\AccessDBs\DB1.mdb;" & _
    15.         "Persist Security Info=True;" & _
    16.         "Jet OLEDB:System database=C:\AccessDBs\system.mdw"
    17.  
    18. 'if you don't need you can eliminate the last line in connection string
    19.  
    20.     With Cnn
    21.         .CursorLocation = adUseClient
    22.         .Open strConnect
    23.     End With
    5. How to save image in db?
    Have a look at this official FAQ article: Database - How can I store images (or other files) in a database?

    6. How to write/read text file?
    VB Code:
    1. 'write
    2. Option Explicit
    3. 'Set a reference to Microsoft Scripting Runtime
    4. Private Sub Command1_Click()
    5.     Dim fs As FileSystemObject
    6.     Dim ts As TextStream
    7.      
    8.     Set fs = New FileSystemObject
    9.     'To write
    10.     Set ts = fs.OpenTextFile("C:\mytestfile.txt", ForWriting, True)
    11.     ts.WriteLine "I Love"
    12.     ts.WriteLine "VB Forums"
    13.     ts.Close
    14.      
    15.     'To Read
    16.     If fs.FileExists("C:\mytestfile.txt") Then
    17.         Set ts = fs.OpenTextFile("C:\mytestfile.txt")
    18.          
    19.         Do While Not ts.AtEndOfStream
    20.             MsgBox ts.ReadLine
    21.         Loop
    22.         ts.Close
    23.     End If
    24.     Set ts = Nothing
    25.     Set fs = Nothing
    26. End Sub
    27.  
    28. 'read
    29. Function FileText(ByVal filename As String) As String
    30.     Dim handle As Integer
    31.      
    32.     ' ensure that the file exists
    33.     If Len(Dir$(filename)) = 0 Then
    34.         Err.Raise 53  ' File not found
    35.     End If
    36.      
    37.     ' open in binary mode
    38.     handle = FreeFile
    39.     Open filename$ For Binary As #handle
    40.     ' read the string and close the file
    41.     FileText = Space$(LOF(handle))
    42.     Get #handle, , FileText
    43.     Close #handle
    44. End Function

    7. How to fix invalid characters in sql criteria?
    VB Code:
    1. Crit="Mark's"
    2. strSQL = "SELECT * FROM MyTable WHERE ComField ='" & CleanText(Crit) & "'"
    3. Public Function CleanText(strIn As String) As String
    4.     On Error GoTo VBError
    5.     Dim iAcnt As Long
    6.     Dim strString As String
    7.     Dim vLimit As Long
    8.     vLimit = Len(strIn)
    9.     For iAcnt = 1 To vLimit
    10.         Select Case Asc(Mid$(strIn, iAcnt, 1))
    11.         Case 10, 13
    12.             strString = strString & Mid$(strIn, iAcnt, 1)
    13.         Case 124
    14.             strString = strString & "!"
    15.         Case 39
    16.             strString = strString & "''"
    17.         Case 34
    18.             strString = strString & """"
    19.         Case Is < 32
    20.             strString = strString & " "
    21.         Case Is > 126
    22.             strString = strString & " "
    23.         Case Else
    24.             strString = strString & Mid$(strIn, iAcnt, 1)
    25.         End Select
    26.     Next
    27.     CleanText = strString
    28.     CleanText = Trim$(CleanText)
    29. Exit Function
    30. VBError:
    31.     MsgBox "VBError in Sub Parse_SQL_Text : " & Err.Number & " - " & Err.Description
    32.     Resume Next
    33. End Function

    8. How to dynamically add controls?
    VB Code:
    1. Dim WithEvents vTextBox As TextBox
    2. Set vTextBox = Controls.Add("vb.textbox", "DeeU")

  2. #2

    Thread Starter
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Philippines
    Posts
    10,591

    Re: Frequently Asked Questions

    9. How to terminate a process?
    VB Code:
    1. Option Explicit
    2. 'on win2k you need the following:
    3. Private Const PROCESS_TERMINATE = &H1
    4. 'On nt 9X the following could be enough:
    5. Private Const PROCESS_ALL_ACCESS = &H1F0FFF
    6. 'in any case, let us use both...
    7. Private Const MAX_PATH As Integer = 260
    8.  
    9. Private Type PROCESSENTRY32
    10.   dwSize As Long
    11.   cntUsage As Long
    12.   th32ProcessID As Long
    13.   th32DefaultHeapID As Long
    14.   th32moduleID As Long
    15.   cntThreads As Long
    16.   th32ParentProcessID As Long
    17.   pcPriClassBase As Long
    18.   dwFlags As Long
    19.   szExeFile As String * MAX_PATH
    20. End Type
    21.  
    22. Private Declare Function CreateToolHelpSnapshot Lib "kernel32" Alias "CreateToolhelp32Snapshot" (ByVal lFlags As Long, ByVal lProcessID As Long) As Long
    23. Private Declare Function ProcessFirst Lib "kernel32" Alias "Process32First" (ByVal hSnapShot As Long, uProcess As PROCESSENTRY32) As Long
    24. Private Declare Function ProcessNext Lib "kernel32" Alias "Process32Next" (ByVal hSnapShot As Long, uProcess As PROCESSENTRY32) As Long
    25. Private Declare Function TerminateProcess Lib "kernel32" (ByVal ApphProcess As Long, ByVal uExitCode As Long) As Long
    26. Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
    27. Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
    28.  
    29. Public Function KillApp(myName As String) As Boolean
    30.     Dim uProcess As PROCESSENTRY32
    31.     Dim rProcessFound As Long
    32.     Dim hSnapShot As Long
    33.     Dim szExename As String
    34.     Dim exitCode As Long
    35.     Dim myProcess As Long
    36.     Dim iFound As Integer
    37.    
    38.     On Error GoTo ErrHandler
    39.    
    40.     Const TH32CS_SNAPPROCESS As Long = 2&
    41.    
    42.     uProcess.dwSize = Len(uProcess)
    43.     hSnapShot = CreateToolHelpSnapshot(TH32CS_SNAPPROCESS, 0&)
    44.     rProcessFound = ProcessFirst(hSnapShot, uProcess)
    45.    
    46.     Do While rProcessFound
    47.        iFound = InStr(1, uProcess.szExeFile, Chr(0)) - 1
    48.        If iFound > 0 Then
    49.            szExename = LCase$(Left$(uProcess.szExeFile, iFound))
    50.        
    51.            If Right$(szExename, Len(myName)) = LCase$(myName) Then
    52.                
    53.                myProcess = OpenProcess(PROCESS_ALL_ACCESS Or PROCESS_TERMINATE, False, uProcess.th32ProcessID)
    54.                KillApp = TerminateProcess(myProcess, exitCode)
    55.                Call CloseHandle(myProcess)
    56.                
    57.                
    58.                'if you have only one, exit here:
    59.                'Exit Function
    60.                'if you think you may have more than one,
    61.                'let this go on
    62.            End If
    63.            rProcessFound = ProcessNext(hSnapShot, uProcess)
    64.        End If
    65.     Loop
    66.     Call CloseHandle(hSnapShot)
    67.     Exit Function
    68. ErrHandler:
    69.     MsgBox Err.Description
    70. End Function

    10. How to allow only one instance of app?
    VB Code:
    1. 'Sol. 1
    2. 'in sub main or from_load...
    3. If App.PrevInstance = True Then
    4.     MsgBox "Already running...."
    5.     End
    6. End If
    7.  
    8. 'Sol. 2
    9. Option Explicit
    10.  
    11. Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
    12. Public Sub Main()
    13.     Dim m_hWnd As Long
    14.  
    15.     'Change Form1 to your form Caption.
    16.     m_hWnd = FindWindow(vbNullString, "Form1")
    17.     If m_hWnd > 0 Then
    18.         MsgBox "Program " & App.Title & " is already running..."
    19.         Unload Form1
    20.         Exit Sub
    21.     End If
    22.  
    23.     'Change Form1 to your form name.
    24.     Form1.Show
    25. End Sub

    11. How to correctly end app?
    VB Code:
    1. Dim frm as Form
    2. For Each frm in Forms
    3.   if frm.hWnd<> Me.hWnd then
    4.     Unload frm
    5.   End If
    6. Next
    12. How to delete a file?
    VB Code:
    1. 'Sol. 1
    2. Kill C:\Your_Folder\Yourfile.EXE
    3.  
    4. 'Sol. 2
    5. Dim fso As Object
    6. Set fso = CreateObject("Scripting.FileSystemObject")
    7. fso.Deletefile ("c:\windows\desktop\doc1.doc")
    8.  
    9. 'Sol. 3 (Move to recycle bin)
    10. Private Type SHFILEOPSTRUCT
    11.     hWnd As Long
    12.     wFunc As Long
    13.     pFrom As String
    14.     pToAs String
    15.     fFlagsAs Integer
    16.     fAborted As Boolean
    17.     hNameMaps As Long
    18.     sProgress As String
    19.     End Type
    20.     Private Const FO_DELETE = &H3
    21.     Private Const FOF_ALLOWUNDO = &H40
    22.  
    23.  
    24. Private Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long
    25.  
    26. ' Delete a single file
    27. lResult = ShellDelete("DELETE.ME")
    28. ' Delete several files
    29. lResult = ShellDelete("DELETE.ME", "LOVE_LTR.DOC", "COVERUP.TXT")
    30.  
    31.  
    32. Public Function ShellDelete(ParamArray vntFileName() As Variant) As Long
    33.     Dim I As Integer
    34.     Dim sFileNames As String
    35.     Dim SHFileOp As SHFILEOPSTRUCT
    36.  
    37.  
    38.     For I = LBound(vntFileName) To UBound(vntFileName)
    39.         sFileNames = sFileNames & vntFileName(I) & vbNullChar
    40.     Next
    41.     sFileNames = sFileNames & vbNullChar
    42.  
    43.  
    44.     With SHFileOp
    45.         .wFunc = FO_DELETE
    46.         .pFrom = sFileNames
    47.         .fFlags = FOF_ALLOWUNDO
    48.     End With
    49.     ShellDelete = SHFileOperation(SHFileOp)
    50. End Function

    13. How to make a form always on top?
    VB Code:
    1. Private Declare Function SetWindowPos Lib "user32" (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long
    2.  
    3. Private Const SWP_NOMOVE = &H2
    4. Private Const SWP_NOSIZE = &H1
    5. Private Const HWND_TOPMOST = -1
    6.  
    7. SetWindowPos FormName.hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE Or SWP_NOSIZE

    14. Block keyboard and mouse (win98)
    VB Code:
    1. 'Sol. 1
    2. Private Declare Function BlockInput Lib "user32" (ByVal fBlock As Long) As Long
    3. Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
    4. Private Sub Form_Activate()
    5.  DoEvents
    6.  'block the mouse and keyboard input
    7.  BlockInput True
    8.  'wait 10 seconds before unblocking it
    9.  Sleep 10000
    10.  'unblock the mouse and keyboard input
    11.  BlockInput False
    12. End Sub
    13.  
    14. 'Sol. 2
    15. private sub command1_click()
    16. dim aa
    17. aa=shell("rundll keyboard,disable") 'this line will disable the Keyboard
    18. End Sub
    19.  
    20. private sub command2_click()
    21. dim aa
    22. aa=shell("RUNDLL MOUSE,DISABLE") 'this line will disable the Mouse
    23. End Sub

    15. How to disable the Close (X) button on form?
    VB Code:
    1. Option Explicit
    2.  
    3. Public Declare Function GetSystemMenu Lib "user32" _
    4.     (ByVal hwnd As Long, _
    5.      ByVal bRevert As Long) As Long
    6.  
    7. Public Declare Function RemoveMenu Lib "user32" _
    8.     (ByVal hMenu As Long, _
    9.      ByVal nPosition As Long, _
    10.      ByVal wFlags As Long) As Long
    11.  
    12. Public Const MF_BYPOSITION = &H400&
    13.  
    14.  
    15. Public Sub DisableCloseWindowButton(frm As Form)
    16.  
    17.     Dim hSysMenu As Long
    18.  
    19.     'Get the handle to this windows
    20.     'system menu
    21.     hSysMenu = GetSystemMenu(frm.hwnd, 0)
    22.  
    23.     'Remove the Close menu item
    24.     'This will also disable the close button
    25.     RemoveMenu hSysMenu, 6, MF_BYPOSITION
    26.  
    27.     'Lastly, we remove the seperator bar
    28.     RemoveMenu hSysMenu, 5, MF_BYPOSITION
    29.  
    30. End Sub
    31. '--end code block
    32. Now call the DisableCloseWindowButton from your forms load event.
    33.  
    34. Private Sub Form_Load()
    35.     DisableCloseWindowButton Me
    36. End Sub

    16. How to get IP?
    http://www.vbforums.com/showthread.php?t=338329

    17. How to Shell and wait?
    VB Code:
    1. Option Explicit
    2. Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
    3. Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
    4. Const INFINITE = -1&
    5. Private Function shellAndWait(ByVal fileName As String) As Long
    6.     Dim executionStatus As Long
    7.     Dim processHandle As Long
    8.     Dim returnValue As Long
    9.     'Execute the application/file
    10.     executionStatus = Shell(fileName, vbNormalFocus)
    11.      
    12.     'Get the Process Handle
    13.     processHandle = OpenProcess(&H100000, True, executionStatus)
    14.      
    15.     'Wait till the application is finished
    16.     returnValue = WaitForSingleObject(processHandle, INFINITE)
    17.      
    18.     'Send the Return Value Back
    19.     shellAndWait = returnValue
    20. End Function
    21.  
    22. Private Sub Command1_Click()
    23.     'launch the application and wait
    24.     Dim fileName As String
    25.     Dim retrunValue As Long
    26.      
    27.      
    28.     fileName = "EXCEL.EXE"
    29.     retrunValue = shellAndWait(fileName)
    30.      
    31.     If retrunValue = 0 Then
    32.         MsgBox "Application executed and was finished"
    33.     End If
    34. End Sub

    18. How to deal with SysTray?
    http://www.vbforums.com/showthread.p...hlight=systray

    19. How to autocomplete combobox?
    VB Code:
    1. Option Explicit
    2. public Const CB_FINDSTRING = &H14C
    3. Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
    4.  
    5. Function AutoComplete(cbCombo As ComboBox, sKeyAscii As Integer, Optional bUpperCase As Boolean = True) As Integer
    6.     Dim lngFind As Long, intPos As Integer, intLength As Integer
    7.     Dim tStr As String
    8.    
    9.     With cbCombo
    10.         If sKeyAscii = 8 Then
    11.             If .SelStart = 0 Then Exit Function
    12.             .SelStart = .SelStart - 1
    13.             .SelLength = 32000
    14.             .SelText = ""
    15.         Else
    16.             intPos = .SelStart
    17.             tStr = .Text
    18.             If bUpperCase = True Then
    19.                 .SelText = UCase(Chr(sKeyAscii))
    20.             Else
    21.                 .SelText = UCase(Chr(sKeyAscii))
    22.             End If
    23.         End If
    24.        
    25.         lngFind = SendMessage(.hwnd, CB_FINDSTRING, 0, ByVal .Text)
    26.  
    27.         If lngFind = -1 Then
    28.             .Text = tStr
    29.             .SelStart = intPos
    30.             .SelLength = (Len(.Text) - intPos)
    31.             AutoComplete = 0
    32.             Exit Function
    33.         Else
    34.             intPos = .SelStart
    35.             intLength = Len(.List(lngFind)) - Len(.Text)
    36.             .SelText = .SelText & Right(.List(lngFind), intLength)
    37.             .SelStart = intPos
    38.             .SelLength = intLength
    39.         End If
    40.     End With
    41. End Function

  3. #3
    Frenzied Member sciguyryan's Avatar
    Join Date
    Sep 2003
    Location
    Wales
    Posts
    1,763

    Re: Frequently Asked Questions

    20. How can I copy the contents of one listbox to another?

    VB Code:
    1. Dim I As Integer
    2. For I = 0 To lstName1.Count
    3.     lstName2.AddItem lstName1.List(I)
    4. Next I

    21. I get an error number 7 message when trying to run my program, why?

    This is an error that states that you have run out of memory. See here for information on the possible causes and solutions.

    22. How do I open a webpage in the defult browser?

    Simple, use the ShellExecute API Call as shows below

    VB Code:
    1. Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
    2.     ByVal hWnd As Long, _
    3.     ByVal lpOperation As String, _
    4.     ByVal lpFile As String, _
    5.     ByVal lpParameters As String, _
    6.     ByVal lpDirectory As String, _
    7.     ByVal nShowCmd As Long) As Long
    8.  
    9. Private Sub OpenURL(strURL As String)
    10.     ShellExecute Me.hWnd, "open", strURL, vbNullString, "C:\", ByVal 1&
    11.     ' Change the last perameter to 0& if you do not whant to show the window.
    12. End Sub

    Just call the OpenURL sub with the URL of the webpage to open as its perameter.


    23. How do I open a file type with its default application?

    Again, use the ShellExecute AI function.

    VB Code:
    1. Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
    2.     ByVal hWnd As Long, _
    3.     ByVal lpOperation As String, _
    4.     ByVal lpFile As String, _
    5.     ByVal lpParameters As String, _
    6.     ByVal lpDirectory As String, _
    7.     ByVal nShowCmd As Long) As Long
    8.  
    9. Private Sub OpenAFile(strFileLocation As String)
    10.     If Dir$(strFileLocation) = "" Then
    11.         Exit Sub
    12.     End If
    13.     ShellExecute Me.hWnd, "open", strURL, vbNullString, "C:\", ByVal 1&
    14.     ' Change the last perameter to 0& if you do not whant to show the window.
    15. End Sub

    Just call the OpenAFile sub with the path of the file to open as its perameter.

    24. How can I check if a file exists?

    VB Code:
    1. Private Function CheckPath(strPath As String) As Boolean
    2.     If Dir$(strPath) <> "" Then
    3.         CheckPath = True
    4.     Else
    5.         CheckPath = False
    6.     End If
    7. End Function

    Just call the above function with the path of the file to check as its perameter

    25. How do I create a "browse for folder" dialog box?

    Use this Module kindly provided by manavo11.

    26. How do I make my application start up with Windows?

    Have a look at this thread, a good example was posted there.

    26. How do I shutdown / restart / logoff a computer?

    Again an API call holds the answer:

    VB Code:
    1. Private Const EWX_LOGOFF = 0
    2. Private Const EWX_SHUTDOWN = 1
    3. Private Const EWX_REBOOT = 2
    4. Private Const EWX_FORCE = 4
    5. Private Declare Function ExitWindowsEx Lib "user32.dll" ( _
    6.     ByVal uFlags As Long, _
    7.     ByVal dwReserved As Long) As Long

    To Shutdown Windows call this:

    VB Code:
    1. Call ExitWindowsEx(EWX_SHUTDOWN, 0)

    To Restart Windows call this:

    VB Code:
    1. Call ExitWindowsEx(EWX_REBOOT, 0)

    To logoff Windows call this:

    VB Code:
    1. Call ExitWindowsEx(EWX_LOGOFF, 0)


    27. How do I create a form that is not square shaped?

    Have a lok at this thread. Some useful links were posted there.

    Cheers,

    RyanJ
    Last edited by sciguyryan; May 31st, 2005 at 01:13 PM.
    My Blog.

    Ryan Jones.

  4. #4
    Frenzied Member sciguyryan's Avatar
    Join Date
    Sep 2003
    Location
    Wales
    Posts
    1,763

    Re: Frequently Asked Questions

    28. What does the $ notation after a variable name mean?

    Those were the old-BASIC style for declaring variables that are not often used anymore. The full list is included below.

    String: $
    Integer: %
    Long: &
    Single: !
    Double: #
    Currency: @

    29. How do i get the hard disk ID number?

    VB Code:
    1. Private Function DriveSerial(strDrive As String) As String
    2.     ' Returns the drive serial number.
    3.     Dim FSO As Object
    4.     Set FSO = CreateObject("Scripting.FileSystemObject")
    5.     If Len(strDrive) > 3 Then
    6.         Exit Sub
    7.     End If
    8.     If (FSO.GetDrive(strDrive).IsReady = True) And (Not GetDriveType(strDrive) = 5) Then
    9.         DriveSerial = CStr(FSO.GetDrive(strDrive).SerialNumber)
    10.     Else
    11.         DriveSerial = "Not Available"
    12.     End If
    13. End Property

    30. How can I get a list of all the fonts installed on the system?

    VB has a built in array of these as part of the Screen object, it is called:

    VB Code:
    1. Screen.Fonts

    31. Howcan I tell if Internet Explorer is running?

    Use the following function.

    VB Code:
    1. Private Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" ( _
    2.     ByVal lpClassName As String, _
    3.     ByVal lpWindowName As String) As Long
    4.  
    5.  
    6. Private Function IsIERunning() As Boolean
    7.     Dim lngRet As Long
    8.     lngRet = FindWindow("IEFrame", vbNullString)
    9.     If lngRet <> 0 Then
    10.         IsIERunning = True
    11.     Else
    12.         IsIERunning = False
    13.     End If
    14. End Function

    Just call the IsIERunning function, it will return a boolean value representing if it is, or if not running

    Cheers,

    RyanJ
    Last edited by sciguyryan; Jun 5th, 2005 at 09:11 AM.
    My Blog.

    Ryan Jones.

  5. #5

    Thread Starter
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Philippines
    Posts
    10,591

    Re: Frequently Asked Questions

    32. How to pause computer?
    VB Code:
    1. Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
    2. Private Sub PauseComputer(byval vMSec as long)
    3.     Sleep vMSec
    4. End Sub

    33. How to seek in a file?
    VB Code:
    1. private Function GetLastLine(byval FileName as string) as string
    2.     Dim iFile as Integer
    3.     Dim lFileLen as Long
    4.     Dim sBuffer as string
    5.     Dim iPos as Integer
    6. '
    7. ' You might need to play with the offset depending on how big
    8. ' your 'lines' usually are in the file
    9. '
    10.     Const OFFSET as Long = 160
    11. '
    12. ' The line delimiter string - in this case I'm using VBCRLF, it
    13. ' could just be LF in some cases, again, be careful
    14. '
    15.     Const FINDSTR as string = vbCrLf
    16. '
    17.     iFile = FreeFile
    18.     sBuffer = Space$(OFFSET)
    19. '
    20.     Open FileName for binary Access Read as #iFile
    21.     seek #iFile, (LOF(iFile) - OFFSET)
    22.     get #iFile, , sBuffer
    23.     Close #iFile
    24. '
    25.     iPos = InStrRev(sBuffer, FINDSTR)
    26.     If iPos = 0 then
    27.         GetLastLine = sBuffer
    28.     else
    29.         GetLastLine = mid$(sBuffer, iPos + len(FINDSTR))
    30.     End If
    31. '
    32. End Function

    34. How to get computer name?
    VB Code:
    1. Private Const MAX_COMPUTERNAME_LENGTH As Long = 31
    2. Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
    3. Private Sub Form_Load()
    4.  Dim dwLen As Long
    5.  Dim strString As String
    6.  'Create a buffer
    7.  dwLen = MAX_COMPUTERNAME_LENGTH + 1
    8.  strString = String(dwLen, "X")
    9.  'Get the computer name
    10.  GetComputerName strString, dwLen
    11.  'get only the actual data
    12.  strString = Left(strString, dwLen)
    13.  'Show the computer name
    14.  MsgBox strString
    15. End Sub

    35. How to create shortcut?
    VB Code:
    1. 'Sol. 1
    2. 'add a reference to Windows Script Host Model
    3. Dim WshShell As New WshShell
    4.     Dim oShellLink As WshShortcut
    5.      
    6.     'Create and save the shortcut
    7.     'Here, it is important the the extension end by .lnk
    8.     Set oShellLink = WshShell.CreateShortcut( "C:\TestLink.lnk" )
    9.     With oShellLink
    10.  
    11.     'Shortcut to which file (can be anything, .exe, .doc, ...)
    12.         .TargetPath = "C:\WINNT\SYSTEM32\calc.exe"
    13.         .WindowStyle = 1
    14.         .IconLocation = "C:\WINNT\SYSTEM32\calc.exe, 0"
    15.         .Arguments = ""
    16.         .Save
    17.     End With
    18.      
    19.     Set WshShell = Nothing
    20.     Set oShellLink = Nothing
    21.  
    22. 'Sol. 2
    23. Sub CreateShortCut(File As String, icon As String, iconindex As Long, Target As String)
    24.     Dim intFreeFile As Integer
    25.     File = File & ".url"
    26.     intFreeFile = FreeFile
    27.     Open File For Output As intFreeFile
    28.     Print #intFreeFile, "[InternetShortcut]"
    29.     Print #intFreeFile, "URL=" & Target
    30.     Print #intFreeFile, "IconFile=" & icon
    31.     Print #intFreeFile, "Iconindex=" & iconindex
    32.     Close intFreeFile
    33. End Sub
    34.  
    35. CreateShortCut "File","icon","0","c:"

    36. How to close an application?
    VB Code:
    1. Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
    2. Private Declare Function PostMessage Lib "user32" Alias "PostMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
    3. Const WM_CLOSE = &H10
    4. Private Sub Form_Load()
    5. Dim winHwnd As Long
    6. Dim RetVal As Long
    7. winHwnd = FindWindow(vbNullString, "Calculator")
    8. If winHwnd <> 0 Then
    9. PostMessage winHwnd, WM_CLOSE, 0&, 0&
    10. Else
    11. MsgBox "The Calculator is not open."
    12. End If
    13. End Sub

    37. How to make a from transparent?
    VB Code:
    1. Public Const GWL_EXSTYLE = (-20)
    2. Public Const WS_EX_TRANSPARENT = &H20&
    3. Public Const SWP_FRAMECHANGED = &H20
    4. Public Const SWP_NOMOVE = &H2
    5. Public Const SWP_NOSIZE = &H1
    6. Public Const SWP_SHOWME = SWP_FRAMECHANGED Or _
    7. SWP_NOMOVE Or SWP_NOSIZE
    8. Public Const HWND_NOTOPMOST = -2  
    9.  
    10.  Declare Function SetWindowLong Lib "user32" _
    11. Alias "SetWindowLongA" _
    12. (ByVal hwnd As Long, ByVal nIndex As Long, _
    13. ByVal dwNewLong As Long) As Long
    14. Declare Function SetWindowPos Lib "user32" _
    15. (ByVal hwnd As Long, ByVal hWndInsertAfter _
    16. As Long, ByVal x As Long, ByVal y As Long, _
    17. ByVal cx As Long, ByVal cy As Long, _
    18. ByVal wFlags As Long) As Long  
    19.  
    20. 'Add a commandbutton with following code to Form1
    21.  
    22. Private Sub Command1_Click()
    23. SetWindowLong Me.hwnd, GWL_EXSTYLE, _
    24. WS_EX_TRANSPARENT
    25. SetWindowPos Me.hwnd, HWND_NOTOPMOST, _
    26. 0&, 0&, 0&, 0&, SWP_SHOWME
    27. End Sub  
    28.  
    29. ' The ShowInTaskbar property should be set to False and the BorderStyle to 0-None.

    38. How to create a hotkey?
    VB Code:
    1. 'Module Code
    2.  
    3. Declare Function SendMessage Lib "user32" Alias _
    4. "SendMessageA" (ByVal hwnd As Long, _
    5. ByVal wMsg As Long, ByVal wParam As Long, _
    6. lParam As Long) As Long
    7.  
    8. Declare Function DefWindowProc Lib "user32" _
    9. Alias "DefWindowProcA" (ByVal hwnd As Long, _
    10. ByVal wMsg As Long, ByVal wParam As Long, _
    11. ByVal lParam As Long) As Long
    12.  
    13. Public Const WM_SETHOTKEY = &H32
    14. Public Const WM_SHOWWINDOW = &H18
    15. Public Const HK_SHIFTA = &H141 'Shift + A
    16. Public Const HK_SHIFTB = &H142 'Shift * B
    17. Public Const HK_CONTROLA = &H241 'Control + A
    18. Public Const HK_ALTZ = &H45A
    19.  
    20. 'The value of the key-combination has to
    21. 'declared in lowbyte/highbyte-format
    22.  
    23. 'That means as a hex-number: the last two
    24. 'characters specify the lowbyte (e.g.: 41 = a),
    25. 'the first the highbyte (e.g.: 01 = 1 = Shift)
    26.  
    27. 'Form Code
    28.  
    29. Private Sub Form_Load()
    30. Me.WindowState = vbMinimized
    31. 'Let windows know what hotkey you want for
    32. 'your app, setting of lParam has no effect
    33. erg& = SendMessage(Me.hwnd, WM_SETHOTKEY, _
    34. HK_ALTZ, 0)
    35. 'Check if succesfull
    36. If erg& <> 1 Then
    37. MsgBox "You need another hotkey", vbOKOnly, _
    38. "Error"
    39. End If
    40.  
    41. 'Tell windows what it should do, when the hotkey
    42. 'is pressed -> show the window!
    43. 'The setting of wParam and lParam has no effect
    44.  
    45. erg& = DefWindowProc(Me.hwnd, WM_SHOWWINDOW, _
    46. 0, 0)
    47. End Sub
    48.  
    49. 'When the user presses ALT+Z Form1 is shown.

  6. #6
    Frenzied Member sciguyryan's Avatar
    Join Date
    Sep 2003
    Location
    Wales
    Posts
    1,763

    Re: Frequently Asked Questions

    39. How do I get the current logged in username?

    VB Code:
    1. Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" ( _
    2.     ByVal lpBuffer As String, _
    3.     nSize As Long) As Long
    4.  
    5. Private Function UserName() As String
    6.     Dim strBuffer As String
    7.     Dim lngSize As Long
    8.     strBuffer = Space$(255)
    9.     lngSize = Len(strBuffer)
    10.     Call GetUserName(strBuffer, lngSize)
    11.     UserName = Left$(strBuffer, lngSize)
    12. End Function

    Simple call the UserName() function :)

    40. How can I make it so a compoents can be dragged around the screen?

    Use the following code, changing Object to the components name.

    VB Code:
    1. ' These are global variables! Put them at the top of your form.
    2. Dim intX As Integer
    3. Dim intY As Integer
    4.  
    5. Private Sub Object_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
    6.     If Button = vbLeftButton Then
    7.         intX = X
    8.         intY = Y
    9.         Object.MousePointer = vbSizeAll
    10.     End If
    11. End Sub
    12.  
    13. Private Sub Object_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
    14.     If Button = vbLeftButton Then
    15.         Object.Left = (Object.Left - intX) + X
    16.         Object.Top = (Object.Top - intY) + Y
    17.     End If
    18. End Sub
    19.  
    20. Private Sub Object_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
    21.     Object.MousePointer = vbDefault
    22. End Sub

    41. How can I add music to my exe?

    Use the mciSendString API function. This can play MIDI, MP3, and WAV files. :)

    42. How do I create a random number between xxx and xxx?

    Use the following function.

    VB Code:
    1. Private Function MakeRandom(intLowest As Integer, intHighest As integer) As Long
    2.     Ramdomize
    3.     Dim intTemp As Integer
    4.     If intLowest > intHighest Then
    5.         intTemp = intLowest
    6.         intLowest = intHighest
    7.         intHighest = intTemp
    8.     End If
    9.     MakeRandom = CLng((intHighest - intLowest + 1) * Rnd + intLowest)
    10. End Function

    43. How do I add multiple patterns to the Pattern property of a FileListBox?

    Quite simple, just seperate all the file types with a semi-colon (;).
    E.G. If you wanted to show all DLL and all OCX files then you would do the following:

    VB Code:
    1. filFileListboxName.Pattern = "*.dll;*.ocx"

    44. How do I zip / un-zip files using VB?

    Have a look here - that is a good example of how it can be done.

    Cheers,

    RyanJ
    Last edited by sciguyryan; Jul 7th, 2010 at 02:09 AM.
    My Blog.

    Ryan Jones.

  7. #7
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: Frequently Asked Questions

    45. How do I scroll to the bottom of a multi-line textbox?
    VB Code:
    1. Text1.SelStart = Len(Text1)

    46. How do I get the number of lines in a text file?
    VB Code:
    1. Function NumLines(FileName As String) As Long
    2. Dim ff As Integer
    3. Dim strBuff As String
    4. Dim str() As String
    5.   ff = FreeFile
    6.   Open FileName For Input As #ff
    7.   strBuff = Input(LOF(ff), ff)
    8.   Close #ff
    9.   str() = Split(strBuff, vbCrLf)
    10.   NumLines = UBound(str) - LBound(str) + 1
    11. End Function

  8. #8

    Thread Starter
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Philippines
    Posts
    10,591

    Re: Frequently Asked Questions

    47. How to clear all textboxes in a form?
    VB Code:
    1. Public Sub ClearTextBoxes(frmClearMe As Form)
    2.  
    3.  Dim txt As Control
    4.  
    5. 'clear the text boxes
    6.  For Each txt In frmClearMe
    7.  
    8.   If TypeOf txt Is TextBox Then txt.Text = ""
    9.  
    10.  Next
    11.  
    12. End Sub

    48. How to cut,copy and paste in MSFlexGrid?
    VB Code:
    1. Private Sub EditCut()
    2.     'Cut the selection and put it on the Clipboard
    3.     EditCopy
    4.     EditDelete
    5. End Sub
    6.  
    7. Private Sub EditCopy()
    8.     'Copy the selection and put it on the Clipboard
    9.     Clipboard.Clear
    10.     Clipboard.SetText MSFlexGrid1.Clip
    11. End Sub
    12.  
    13. Private Sub EditPaste()
    14.     'Insert Clipboard contents
    15.     If Len(Clipboard.GetText) Then MSFlexGrid1.Clip = _
    16.          Clipboard.GetText
    17. End Sub
    18.  
    19. Private Sub EditDelete()
    20.     'Deletes the selection
    21.     Dim i As Integer
    22.     Dim j As Integer
    23.     Dim strClip As String
    24.     With MSFlexGrid1
    25.         For i = 1 To .RowSel
    26.             For j = 1 To .ColSel
    27.                 strClip = strClip & "" & vbTab
    28.             Next
    29.             strClip = strClip & vbCr
    30.         Next
    31.         .Clip = strClip
    32.     End With
    33. End Sub
    34.  
    35. Private Sub EditSelectAll()
    36.     'Selects the whole Grid
    37.     With MSFlexGrid1
    38.         .Visible = False
    39.         .row = 1
    40.         .col = 1
    41.         .RowSel = .Rows - 1
    42.         .ColSel = .Cols - 1
    43.         .TopRow = 1
    44.         .Visible = True
    45.     End With
    46. End Sub

    49. How to search a listbox?
    VB Code:
    1. Option Explicit
    2. Private Declare Function SendMessage Lib "User32" _
    3. Alias "SendMessageA" (ByVal hWnd As Long, ByVal _
    4. wMsg As Integer, ByVal wParam As Integer, lParam _
    5. As Any) As Long
    6. Const LB_FINDSTRING = &H18F
    7.  
    8. Private Sub Form_Load()
    9. With List1
    10. .Clear
    11. .AddItem "CPU"
    12. .AddItem "RAM"
    13. .AddItem "ROM"
    14. .AddItem "Cache"
    15. .AddItem "Motherboard"
    16. .AddItem "Hard Disk"
    17. .AddItem "Floppy Disk"
    18. End With
    19. End Sub
    20.  
    21. Private Sub Text1_Change()
    22. List1.ListIndex = SendMessage(List1.hWnd, LB_FINDSTRING, -1, ByVal
    23. Text1.Text)
    24. Text1.Text = List1.Text
    25. End Sub

    50. How to search and highlight string in textbox?
    VB Code:
    1. Public Function searchHighlight(srchTextBox As textBox, srchString As String)
    2.     On Error Resume Next
    3.     Dim A As Integer
    4.     Call srchTextBox.SetFocus
    5.     SendKeys ("^{HOME}")
    6.     A = 1
    7.  
    8.  
    9.     Do Until A = Len(srchTextBox.text)
    10.         'if word was found...
    11.  
    12.  
    13.         If Mid$(UCase$(srchTextBox.text), A, Len(srchString)) = UCase$(srchString) Then
    14.             'highlight the word
    15.  
    16.  
    17.             For A = 1 To Len(srchString)
    18.                 SendKeys ("+{RIGHT}")
    19.             Next A
    20.             Exit Do
    21.         End If
    22.         'if word isnt found or a return is found
    23.         '     , dont do anything
    24.  
    25.  
    26.         If Mid(srchTextBox.text, A, 1) = Chr$(13) Then
    27.         Else
    28.             'go to next line
    29.             SendKeys ("{RIGHT}")
    30.         End If
    31.         A = A + 1
    32.         If A > Len(srchTextBox.text) Then Exit Do
    33.     Loop
    34. End Function

    51. How to make the title bar flash?
    VB Code:
    1. Private Declare Function FlashWindow _
    2. Lib "user32" (ByVal hwnd As Long, _
    3. ByVal bInvert As Long) As Long
    4.  
    5. Private Sub tmrFlash_Timer()
    6.  
    7. Dim lngRet As Long
    8. '// Flash the window
    9. lngRet = FlashWindow(Me.hwnd, 1)
    10. End Sub
    11.  
    12. Private Sub cmdFlash_Click()
    13. '// Flash every 0.5 seconds
    14. tmrFlash.Interval = 500
    15. tmrFlash.Enabled = True
    16. End Sub
    17.  
    18. Private Sub Form_Load()
    19. '// Don't start flashing yet
    20. tmrFlash.Enabled = False
    21. End Sub

    52. How to find out how long Windows has been running?
    VB Code:
    1. Declare Function GetTickCount& Lib "kernel32" ()
    2.  
    3. Private Sub cmdWinRun_Click()
    4. MsgBox GetTickCount
    5. End Sub

    53. How to compact Access database using ado?
    VB Code:
    1. Public Sub CompactDB()
    2.     'Microsoft Jet and Replication objects
    3.     Dim objJE As New JRO.JetEngine, strSource As String, strTarget As String
    4.     DoEvents
    5.     Busy True
    6.     strSource = "  "
    7.     strTarget = " "    
    8. objJE.CompactDatabase "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strSource & ";", "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strTarget & ";Jet OLEDB:Engine Type=4;"
    9.     Busy False
    10.     'Engine type:
    11.     'Access 97 = 4
    12.     'Access 2000 = 5
    13. End Sub

    54. How to determine if app is running in IDE?
    VB Code:
    1. Public Function IsIDE() As Boolean
    2.     On Error GoTo ErrHandler
    3.     'because debug statements are ignored when
    4.     'the app is compiled, the next statment will
    5.     'never be executed in the EXE.
    6.     Debug.Print 1 / 0
    7.     IsIDE = False
    8. Exit Function
    9. ErrHandler:
    10.     'If we get an error then we are
    11.     'running in IDE / Debug mode
    12.     IsIDE = True
    13. End Function

  9. #9
    Frenzied Member sciguyryan's Avatar
    Join Date
    Sep 2003
    Location
    Wales
    Posts
    1,763

    Re: Frequently Asked Questions

    55. How can I use command line perameters in my program

    Command line parameters are automatically assigned to a string variable called Command$.

    I would suggest the use of something like the following: (Assuming you have used a space to seperate each parameter)

    VB Code:
    1. Dim strParameters() As String
    2. strParameters = Split(Command$, " ")
    3.  
    4. Select Case strParameters(0)
    5.     Case "inimake"
    6.         ' Do soemthing here
    7.     Case Else
    8.         ' Do something else here.
    9. End Select

    Of corse you'll need to add error checking and the such

    56. How can I check is my application is minamized?

    Quite simple:

    VB Code:
    1. If Me.WindowState = vbMinimized Then
    2.     ' Your program is minimized
    3. End If

    57. How can I find the number of the lowest and highest element in an array?

    To find the lowest element number you can use the LBound function.

    To find the last element number in the array you can use the UBound function.

    58. How can I disable the "X" Minamize and Maxamize buttons in a MID form?

    Have a look here. That link contains all the information you will need.

    59. How can I disable Ctrl + Alt + Delete? How can I send Ctrl + Alt + Delete using the SendKeys function?

    There are no shure ways to do these. Some will only work in Windows 98 and then it does not work all the time so to put it simply just take it that you cannot do the above tasks.

    Cheers,

    RyanJ
    Last edited by sciguyryan; Jun 1st, 2005 at 05:58 AM.
    My Blog.

    Ryan Jones.

  10. #10
    Moderator
    Join Date
    Jan 2005
    Location
    Sydney
    Posts
    13,621

    Re: Frequently Asked Questions

    60. How to get the correct path of a special folder (e.g. My Documents, Program Files)
    Code:
     Const CSIDL_DESKTOP                    As Long = &H0
     Const CSIDL_INTERNET                   As Long = &H1
     Const CSIDL_PROGRAMS                   As Long = &H2
     Const CSIDL_CONTROLS                   As Long = &H3
     Const CSIDL_PRINTERS                   As Long = &H4
     Const CSIDL_PERSONAL                   As Long = &H5
     Const CSIDL_FAVORITES                  As Long = &H6
     Const CSIDL_STARTUP                    As Long = &H7
     Const CSIDL_RECENT                     As Long = &H8
     Const CSIDL_SENDTO                     As Long = &H9
     Const CSIDL_BITBUCKET                  As Long = &HA
     Const CSIDL_STARTMENU                  As Long = &HB
     Const CSIDL_MYDOCUMENTS                As Long = &HC
     Const CSIDL_MYMUSIC                    As Long = &HD
     Const CSIDL_MYVIDEO                    As Long = &HE
     Const CSIDL_DESKTOPDIRECTORY           As Long = &H10
     Const CSIDL_DRIVES                     As Long = &H11
     Const CSIDL_NETWORK                    As Long = &H12
     Const CSIDL_NETHOOD                    As Long = &H13
     Const CSIDL_FONTS                      As Long = &H14
     Const CSIDL_TEMPLATES                  As Long = &H15
     Const CSIDL_COMMON_STARTMENU           As Long = &H16
     Const CSIDL_COMMON_PROGRAMS            As Long = &H17
     Const CSIDL_COMMON_STARTUP             As Long = &H18
     Const CSIDL_COMMON_DESKTOPDIRECTORY    As Long = &H19
     Const CSIDL_APPDATA                    As Long = &H1A
     Const CSIDL_PRINTHOOD                  As Long = &H1B
     Const CSIDL_LOCAL_APPDATA              As Long = &H1C
     Const CSIDL_ALTSTARTUP                 As Long = &H1D
     Const CSIDL_COMMON_ALTSTARTUP          As Long = &H1E
    
     Const CSIDL_COMMON_FAVORITES           As Long = &H1F
     Const CSIDL_INTERNET_CACHE             As Long = &H20
     Const CSIDL_COOKIES                    As Long = &H21
     Const CSIDL_HISTORY                    As Long = &H22
     Const CSIDL_COMMON_APPDATA             As Long = &H23
     Const CSIDL_WINDOWS                    As Long = &H24
     Const CSIDL_SYSTEM                     As Long = &H25
     Const CSIDL_PROGRAM_FILES              As Long = &H26
     Const CSIDL_MYPICTURES                 As Long = &H27
     Const CSIDL_PROFILE                    As Long = &H28
     Const CSIDL_PROGRAM_FILES_COMMON       As Long = &H2B
     Const CSIDL_COMMON_TEMPLATES           As Long = &H2D
     Const CSIDL_COMMON_DOCUMENTS           As Long = &H2E
     Const CSIDL_COMMON_ADMINTOOLS          As Long = &H2F
     Const CSIDL_ADMINTOOLS                 As Long = &H30
     Const CSIDL_CONNECTIONS                As Long = &H31
     Const CSIDL_COMMON_MUSIC               As Long = &H35
     Const CSIDL_COMMON_PICTURES            As Long = &H36
     Const CSIDL_COMMON_VIDEO               As Long = &H37
     Const CSIDL_RESOURCES                  As Long = &H38
     Const CSIDL_RESOURCES_LOCALIZED        As Long = &H39
     Const CSIDL_COMMON_OEM_LINKS           As Long = &H3A
     Const CSIDL_CDBURN_AREA                As Long = &H3B
     Const CSIDL_COMPUTERSNEARME            As Long = &H3D
     
    Public Declare Function SHGetPathFromIDList Lib "shell32.dll" Alias "SHGetPathFromIDListA" _
        (ByVal pidl As Long, _
         ByVal pszPath As String) _
        As Long
        
    Public Declare Function SHGetSpecialFolderLocation Lib "shell32.dll" _
        (ByVal hwndOwner As Long, _
         ByVal nFolder As Long, _
         ByRef pidl As Long) _
        As Long
     
     Public Function GetSpecialFolder(ByVal CSIDL As Long) As String
        Dim pidl    As Long
        Dim strPath As String
        dim lngPos  As Long
        
        Dim csidltopidl As Long
        
        If (csidl) Then
            If SHGetSpecialFolderLocation(frmRef.hWnd, csidl, pidl) = 0 Then _
                csidltopidl = pidl
          Else
            csidltopidl = 0&
        End If
        
        strPath = Space$(260)
        
        If SHGetPathFromIDList(ByVal pidl, ByVal strPath) Then
            lngPos = InStr(strPath, Chr$(0))
            If (lngPos) Then _
                GetSpecialWinFolder = Left$(strPath, lngPos - 1)
       End If
    End Function
    61. a) Get the hWnd of a combo box's edit portion
    Code:
    Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
        (ByVal hWndParent As Long, _
         ByVal hWndChildAfter As Long, _
         ByVal lpszClass As String, _
         ByVal lpszTitle As String) _
        As Long
    
    Public Function GetComboBoxEdithWnd(ByVal hWnd As Long) As Long
       GetComboBoxEdithWnd = FindWindowEx(hWnd, 0, "EDIT", vbNullString)
    End Function
    in order to...

    b) Add Windows' URL and file path auto-completion to a textbox or combo box

    Code:
    Private Declare Function SHAutoComplete Lib "shlwapi.dll" _
        (ByVal hWndEdit As Long, _
         ByVal dwFlags As Long) _
        As Long
    
    Public Enum SHAutoCompleteFlags
       SHACF_DEFAULT = &H0
       SHACF_FILESYSTEM = &H1
       SHACF_URLHISTORY = &H2
       SHACF_URLMRU = &H4
       SHACF_USETAB = &H8
       SHACF_URLALL = (SHACF_URLHISTORY Or SHACF_URLMRU)
       SHACF_FILESYS_ONLY = &H10
       SHACF_FILESYS_DIRS = &H20
       SHACF_AUTOSUGGEST_FORCE_ON = &H10000000
       SHACF_AUTOSUGGEST_FORCE_OFF = &H20000000
       SHACF_AUTOAPPEND_FORCE_ON = &H40000000
       SHACF_AUTOAPPEND_FORCE_OFF = &H80000000
    End Enum
    
    Public Function AutoComplete(ByVal hWnd As Long, _
                                 ByVal penmFlags As SHAutoCompleteFlags) _
                                As Long
        AutoComplete = (SHAutoComplete(hWnd, penmFlags))
    End Function
    Edit: Left out a couple of API declares, thanks CVMichael
    Last edited by penagate; Jun 1st, 2005 at 12:28 PM. Reason: Window's vs. Windows'

  11. #11
    PowerPoster
    Join Date
    Feb 2002
    Location
    Canada, Toronto
    Posts
    5,716

    Re: Frequently Asked Questions

    Dee-u, I like your code, but I have a problem with point 50.
    I would not trust "SendKeys" since it sends the keys on window(control) that curently selected, even if you select it first, you don't know for sure that maybe another app may change the selection right after that...
    Also, checking character by character is a slow process.

    Anyways, I think this is better:
    50. How to search and highlight string in textbox?
    VB Code:
    1. Public Sub searchHighlight(srchTextBox As TextBox, srchString As String)
    2.     Dim Pos As Long
    3.    
    4.     Pos = InStr(1, srchTextBox.Text, srchString, vbTextCompare)
    5.    
    6.     If Pos > 0 Then
    7.         srchTextBox.SetFocus
    8.        
    9.         srchTextBox.SelStart = Pos - 1
    10.         srchTextBox.SelLength = Len(srchString)
    11.     End If
    12. End Sub

  12. #12
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: Frequently Asked VB Questions

    62. How can I do high-resolution timing?

    Define these functions
    VB Code:
    1. Option Explicit
    2.  
    3. Private Declare Function QueryPerformanceCounter Lib "Kernel32" _
    4.                                  (X As Currency) As Boolean
    5. Private Declare Function QueryPerformanceFrequency Lib "Kernel32" _
    6.                                  (X As Currency) As Boolean
    7.  
    8. Private Type TimerData
    9.     StartCount As Currency
    10.     StopCount As Currency
    11.     Overhead As Currency
    12.     Frequency As Currency
    13. End Type
    14.  
    15. 'returns the number of seconds elapsed between StopCount and StartCount
    16. 'Assumes that InitPerformanceTimer has been called
    17. Private Function ElapsedTime(MyData As TimerData) As Single
    18.  With MyData
    19.     ElapsedTime = (.StopCount - .StartCount - .Overhead) / .Frequency 'seconds
    20.  End With
    21. End Function
    22.  
    23. 'Initializes the data structure so that the ElapsedTime function can be called
    24. 'Returns false if the High-resolution timer is not supported
    25. Private Function InitPerformanceTimer(MyData As TimerData) As Boolean
    26.     Dim Ctr1 As Currency, Ctr2 As Currency
    27.     With MyData
    28.       If QueryPerformanceCounter(Ctr1) Then
    29.           QueryPerformanceCounter Ctr2
    30.           QueryPerformanceFrequency .Frequency
    31.           '1/Freq*10000 is resolution of timer in seconds
    32.           Debug.Print "QueryPerformanceCounter minimum resolution: 1/" & _
    33.                       .Frequency * 10000; " seconds"
    34.           'This overhead is present for each call to API
    35.           .Overhead = Ctr2 - Ctr1
    36.           Debug.Print "API Overhead: "; .Overhead / .Frequency; "seconds"
    37.           InitPerformanceTimer = True
    38.         Else
    39.           Debug.Print "High-resolution counter not supported."
    40.           InitPerformanceTimer = False
    41.         End If
    42.     End With
    43. End Function

    Use it like this
    VB Code:
    1. Private Sub Command1_Click()
    2.     Dim MyData As TimerData
    3.     Dim i As Integer, b As Integer
    4.     If Not InitPerformanceTimer(MyData) Then
    5.         'sorry, no can do
    6.         MsgBox "High-resolution counter not supported"
    7.         Exit Sub
    8.     Else
    9.         With MyData
    10.             b = 0
    11.             'get start time
    12.             QueryPerformanceCounter .StartCount
    13.             'perform some task you want to time
    14.             For i = 1 To 100
    15.                 b = b + i
    16.             Next i
    17.             'get stop time
    18.             QueryPerformanceCounter .StopCount
    19.             'get elapsed time
    20.             MsgBox "Elapsed time is " & CStr(ElapsedTime(MyData) * 1000) & " milliseconds."
    21.         End With
    22.     End If
    23. End Sub

    63. How do I get a String from a long pointer?
    This question comes up when trying to use certain API functions, and when processing certain Windows messages.
    There are two cases to consider.

    1. You "own" the string buffer that the pointer points to.
    In this case you just need to provide the buffer space and modify the string a little once it's been returned.
    Here is an example that gets a window caption.
    VB Code:
    1. Option Explicit
    2. Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
    3.  
    4. Private Function GetText(TargethWnd As Long) As String
    5. Dim lpString As String
    6. Dim maxStr As Long
    7.     maxStr = 100
    8.     lpString = Space(maxStr)
    9.     If GetWindowText(TargethWnd, lpString, maxStr) = 0 Then
    10.         MsgBox "GetWindowText failed"
    11.         GetText = ""
    12.     Else
    13.         GetText = Left(lpString, InStr(lpString, Chr(0)) - 1)
    14.     End If
    15. End Function

    2. The second case is one where the OS "owns" the buffer and you must copy the string data into a VB String variable.
    This example gets string data that is pointed to by a long pointer inside the CopyData Structure.
    If you have the declarations
    VB Code:
    1. Option Explicit
    2.  
    3. Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
    4.  
    5. Private Type COPYDATASTRUCT
    6.         dwData As Long
    7.         cbData As Long
    8.         lpData As Long
    9. End Type
    10. Dim MyData As COPYDATASTRUCT
    11. Dim X As String

    Then you can get the data using this function
    VB Code:
    1. 'This function returns the string pointed to by pstr
    2. 'strCNT is the number of characters in the string
    3. 'strings from dlls are terminated with a null character
    4. Function StrFromPtr(pStr As Long, Optional strCNT As Long = 256) As String
    5.  Dim bTemp As Byte
    6.  Dim i As Long
    7.  Dim X As String
    8.  X = ""
    9.  For i = 0& To strCNT - 1
    10.    CopyMemory bTemp, ByVal pStr + i, 1
    11.    'convert LF to CR & LF
    12.    If bTemp = 10 Then
    13.      X = X & vbCrLf
    14.    Else
    15.      X = X & Chr(bTemp)
    16.    End If
    17.  Next i
    18.  StrFromPtr = X
    19. End Function
    Using it like so:
    VB Code:
    1. X = StrFromPtr(MyData.lpData, MyData.cbData)

    64. How do I do video Capture from VB?
    Check out this excellent port of Vidcap32 to VB
    http://www.shrinkwrapvb.com/vbvidcap.htm
    Last edited by moeur; Jun 2nd, 2005 at 03:28 PM.

  13. #13
    Software Eng. Megatron's Avatar
    Join Date
    Mar 1999
    Location
    Canada
    Posts
    11,287

    Re: Frequently Asked VB Questions

    You might want to edit your first post to include a table on contents.

  14. #14
    Frenzied Member sciguyryan's Avatar
    Join Date
    Sep 2003
    Location
    Wales
    Posts
    1,763

    Re: Frequently Asked VB Questions

    63. How do I load a Word / Excel file using VB without using Shell, ShellExecute or, without adding an office reference to my project?

    Use the following code:

    Word:

    VB Code:
    1. Dim wdWord As Object
    2. Dim wdDocument As Object
    3. Set wdWord = CreateObject("Word.Application")
    4. Set wdDocument = CreateObject("Word.Document")
    5. Set wdDocument = wdWord.Documents.Open("Path_To_Some_File_Here.doc")

    Excel:

    VB Code:
    1. Dim exExcel As Object
    2. Set exExcel = CreateObject("Excel.Application")
    3. exExcel.Workbooks.Open ("Path_To_Some_File_Here.xls")
    4. exExcel.Visible = True

    Cheers,

    RyanJ
    Last edited by sciguyryan; Jun 2nd, 2005 at 04:47 PM.
    My Blog.

    Ryan Jones.

  15. #15
    Former Admin/Moderator MartinLiss's Avatar
    Join Date
    Sep 1999
    Location
    San Jose, CA
    Posts
    32,825

    Re: Frequently Asked Questions

    Quote Originally Posted by dee-u
    9. How to terminate a process?
    VB Code:
    1. Option Explicit
    2. 'on win2k you need the following:
    3. Private Const PROCESS_TERMINATE = &H1
    4. 'On nt 9X the following could be enough:
    5. Private Const PROCESS_ALL_ACCESS = &H1F0FFF
    6. 'in any case, let us use both...
    7. Private Const MAX_PATH As Integer = 260
    8.  
    9. Private Type PROCESSENTRY32
    10.   dwSize As Long
    11.   cntUsage As Long
    12.   th32ProcessID As Long
    13.   th32DefaultHeapID As Long
    14.   th32moduleID As Long
    15.   cntThreads As Long
    16.   th32ParentProcessID As Long
    17.   pcPriClassBase As Long
    18.   dwFlags As Long
    19.   szExeFile As String * MAX_PATH
    20. End Type
    21.  
    22. Private Declare Function CreateToolHelpSnapshot Lib "kernel32" Alias "CreateToolhelp32Snapshot" (ByVal lFlags As Long, ByVal lProcessID As Long) As Long
    23. Private Declare Function ProcessFirst Lib "kernel32" Alias "Process32First" (ByVal hSnapShot As Long, uProcess As PROCESSENTRY32) As Long
    24. Private Declare Function ProcessNext Lib "kernel32" Alias "Process32Next" (ByVal hSnapShot As Long, uProcess As PROCESSENTRY32) As Long
    25. Private Declare Function TerminateProcess Lib "kernel32" (ByVal ApphProcess As Long, ByVal uExitCode As Long) As Long
    26. Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
    27. Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
    28.  
    29. Public Function KillApp(myName As String) As Boolean
    30.     Dim uProcess As PROCESSENTRY32
    31.     Dim rProcessFound As Long
    32.     Dim hSnapShot As Long
    33.     Dim szExename As String
    34.     Dim exitCode As Long
    35.     Dim myProcess As Long
    36.     Dim iFound As Integer
    37.    
    38.     On Error GoTo ErrHandler
    39.    
    40.     Const TH32CS_SNAPPROCESS As Long = 2&
    41.    
    42.     uProcess.dwSize = Len(uProcess)
    43.     hSnapShot = CreateToolHelpSnapshot(TH32CS_SNAPPROCESS, 0&)
    44.     rProcessFound = ProcessFirst(hSnapShot, uProcess)
    45.    
    46.     Do While rProcessFound
    47.        iFound = InStr(1, uProcess.szExeFile, Chr(0)) - 1
    48.        If iFound > 0 Then
    49.            szExename = LCase$(Left$(uProcess.szExeFile, iFound))
    50.        
    51.            If Right$(szExename, Len(myName)) = LCase$(myName) Then
    52.                
    53.                myProcess = OpenProcess(PROCESS_ALL_ACCESS Or PROCESS_TERMINATE, False, uProcess.th32ProcessID)
    54.                KillApp = TerminateProcess(myProcess, exitCode)
    55.                Call CloseHandle(myProcess)
    56.                
    57.                
    58.                'if you have only one, exit here:
    59.                'Exit Function
    60.                'if you think you may have more than one,
    61.                'let this go on
    62.            End If
    63.            rProcessFound = ProcessNext(hSnapShot, uProcess)
    64.        End If
    65.     Loop
    66.     Call CloseHandle(hSnapShot)
    67.     Exit Function
    68. ErrHandler:
    69.     MsgBox Err.Description
    70. End Function

    10. How to allow only one instance of app?
    VB Code:
    1. 'Sol. 1
    2. 'in sub main or from_load...
    3. If App.PrevInstance = True Then
    4.     MsgBox "Already running...."
    5.     End
    6. End If
    7.  
    8. 'Sol. 2
    9. Option Explicit
    10.  
    11. Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
    12. Public Sub Main()
    13.     Dim m_hWnd As Long
    14.  
    15.     'Change Form1 to your form Caption.
    16.     m_hWnd = FindWindow(vbNullString, "Form1")
    17.     If m_hWnd > 0 Then
    18.         MsgBox "Program " & App.Title & " is already running..."
    19.         Unload Form1
    20.         Exit Sub
    21.     End If
    22.  
    23.     'Change Form1 to your form name.
    24.     Form1.Show
    25. End Sub

    11. How to correctly end app?
    VB Code:
    1. Dim frm as Form
    2. For Each frm in Forms
    3.   if frm.hWnd<> Me.hWnd then
    4.     Unload frm
    5.   End If
    6. Next
    12. How to delete a file?
    VB Code:
    1. 'Sol. 1
    2. Kill C:\Your_Folder\Yourfile.EXE
    3.  
    4. 'Sol. 2
    5. Dim fso As Object
    6. Set fso = CreateObject("Scripting.FileSystemObject")
    7. fso.Deletefile ("c:\windows\desktop\doc1.doc")
    8.  
    9. 'Sol. 3 (Move to recycle bin)
    10. Private Type SHFILEOPSTRUCT
    11.     hWnd As Long
    12.     wFunc As Long
    13.     pFrom As String
    14.     pToAs String
    15.     fFlagsAs Integer
    16.     fAborted As Boolean
    17.     hNameMaps As Long
    18.     sProgress As String
    19.     End Type
    20.     Private Const FO_DELETE = &H3
    21.     Private Const FOF_ALLOWUNDO = &H40
    22.  
    23.  
    24. Private Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long
    25.  
    26. ' Delete a single file
    27. lResult = ShellDelete("DELETE.ME")
    28. ' Delete several files
    29. lResult = ShellDelete("DELETE.ME", "LOVE_LTR.DOC", "COVERUP.TXT")
    30.  
    31.  
    32. Public Function ShellDelete(ParamArray vntFileName() As Variant) As Long
    33.     Dim I As Integer
    34.     Dim sFileNames As String
    35.     Dim SHFileOp As SHFILEOPSTRUCT
    36.  
    37.  
    38.     For I = LBound(vntFileName) To UBound(vntFileName)
    39.         sFileNames = sFileNames & vntFileName(I) & vbNullChar
    40.     Next
    41.     sFileNames = sFileNames & vbNullChar
    42.  
    43.  
    44.     With SHFileOp
    45.         .wFunc = FO_DELETE
    46.         .pFrom = sFileNames
    47.         .fFlags = FOF_ALLOWUNDO
    48.     End With
    49.     ShellDelete = SHFileOperation(SHFileOp)
    50. End Function

    13. How to make a form always on top?
    VB Code:
    1. Private Declare Function SetWindowPos Lib "user32" (ByVal hwnd As Long, ByVal hWndInsertAfter As Long, ByVal x As Long, ByVal y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long
    2.  
    3. Private Const SWP_NOMOVE = &H2
    4. Private Const SWP_NOSIZE = &H1
    5. Private Const HWND_TOPMOST = -1
    6.  
    7. SetWindowPos FormName.hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE Or SWP_NOSIZE

    14. Block keyboard and mouse (win98)
    VB Code:
    1. 'Sol. 1
    2. Private Declare Function BlockInput Lib "user32" (ByVal fBlock As Long) As Long
    3. Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
    4. Private Sub Form_Activate()
    5.  DoEvents
    6.  'block the mouse and keyboard input
    7.  BlockInput True
    8.  'wait 10 seconds before unblocking it
    9.  Sleep 10000
    10.  'unblock the mouse and keyboard input
    11.  BlockInput False
    12. End Sub
    13.  
    14. 'Sol. 2
    15. private sub command1_click()
    16. dim aa
    17. aa=shell("rundll keyboard,disable") 'this line will disable the Keyboard
    18. End Sub
    19.  
    20. private sub command2_click()
    21. dim aa
    22. aa=shell("RUNDLL MOUSE,DISABLE") 'this line will disable the Mouse
    23. End Sub

    15. How to disable the Close (X) button on form?
    VB Code:
    1. Option Explicit
    2.  
    3. Public Declare Function GetSystemMenu Lib "user32" _
    4.     (ByVal hwnd As Long, _
    5.      ByVal bRevert As Long) As Long
    6.  
    7. Public Declare Function RemoveMenu Lib "user32" _
    8.     (ByVal hMenu As Long, _
    9.      ByVal nPosition As Long, _
    10.      ByVal wFlags As Long) As Long
    11.  
    12. Public Const MF_BYPOSITION = &H400&
    13.  
    14.  
    15. Public Sub DisableCloseWindowButton(frm As Form)
    16.  
    17.     Dim hSysMenu As Long
    18.  
    19.     'Get the handle to this windows
    20.     'system menu
    21.     hSysMenu = GetSystemMenu(frm.hwnd, 0)
    22.  
    23.     'Remove the Close menu item
    24.     'This will also disable the close button
    25.     RemoveMenu hSysMenu, 6, MF_BYPOSITION
    26.  
    27.     'Lastly, we remove the seperator bar
    28.     RemoveMenu hSysMenu, 5, MF_BYPOSITION
    29.  
    30. End Sub
    31. '--end code block
    32. Now call the DisableCloseWindowButton from your forms load event.
    33.  
    34. Private Sub Form_Load()
    35.     DisableCloseWindowButton Me
    36. End Sub

    16. How to get IP?
    http://www.vbforums.com/showthread.php?t=338329

    17. How to Shell and wait?
    VB Code:
    1. Option Explicit
    2. Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
    3. Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
    4. Const INFINITE = -1&
    5. Private Function shellAndWait(ByVal fileName As String) As Long
    6.     Dim executionStatus As Long
    7.     Dim processHandle As Long
    8.     Dim returnValue As Long
    9.     'Execute the application/file
    10.     executionStatus = Shell(fileName, vbNormalFocus)
    11.      
    12.     'Get the Process Handle
    13.     processHandle = OpenProcess(&H100000, True, executionStatus)
    14.      
    15.     'Wait till the application is finished
    16.     returnValue = WaitForSingleObject(processHandle, INFINITE)
    17.      
    18.     'Send the Return Value Back
    19.     shellAndWait = returnValue
    20. End Function
    21.  
    22. Private Sub Command1_Click()
    23.     'launch the application and wait
    24.     Dim fileName As String
    25.     Dim retrunValue As Long
    26.      
    27.      
    28.     fileName = "EXCEL.EXE"
    29.     retrunValue = shellAndWait(fileName)
    30.      
    31.     If retrunValue = 0 Then
    32.         MsgBox "Application executed and was finished"
    33.     End If
    34. End Sub

    18. How to deal with SysTray?
    http://www.vbforums.com/showthread.p...hlight=systray

    [B]19. ...[/Highlight]
    In Number 12, you should check for the possibility of the user Canceling the dialog. You do that by looking at If FileOperation.fAnyOperationsAborted which will be True in that case.

  16. #16
    New Member
    Join Date
    Mar 2008
    Posts
    2

    Re: Frequently Asked VB Questions

    Thank you

  17. #17
    Super Moderator RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    59,704

    Re: Frequently Asked VB Questions

    Most of this stuff is already in the API FAQ or other FAQs.
    VB/Office Guru™ (AKA: Gangsta Yoda™ )
    I dont answer coding questions via PM. Please post a thread in the appropriate forum.

    Microsoft MVP 2006-2011
    Office Development FAQ (VBA, VB 6, VB.NET, C#)
    Senior Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    • Star Wars Gangsta Rap • Reps & Rating Posts • VS.NET on Vista (New) • Multiple .NET Framework Versions (New) • Office Primary Interop Assemblies • VB/Office Guru™ Word SpellChecker™.NET • VB/Office Guru™ Word SpellChecker™ VB6 • VB.NET Attributes Ex. • Outlook Global Address List • API Viewer utility • .NET API Viewer Utility •
    System: Intel Core 2 Extreme Ed., 2 WD Raptor 10K RPM 150 GB HDs RAID 1, 2 GBs DDR2 667 MHz RAM, 3 Viewsonic 17" LCDs, Windows Vista RTM, IE 7, Office 2007

  18. #18
    New Member
    Join Date
    Sep 2008
    Posts
    11

    Re: Frequently Asked VB Questions

    are all this codes available in VB 6.0?
    cause thats the vb version i am using right now for my thesis.
    reply asap pls..
    thank you so much!

  19. #19

    Thread Starter
    Software Carpenter dee-u's Avatar
    Join Date
    Feb 2005
    Location
    Philippines
    Posts
    10,591

    Re: Frequently Asked VB Questions

    Quote Originally Posted by pyrojoker03
    are all this codes available in VB 6.0?
    cause thats the vb version i am using right now for my thesis.
    reply asap pls..
    thank you so much!
    Yes this is all in Visual Basic 6.0 but as Rob says most of the stuffs here are already in the official FAQ section which contains more topics and more elaborate on their explanations.

  20. #20
    Member
    Join Date
    Apr 2008
    Posts
    46

    Re: Frequently Asked VB Questions

    thanks a ton for all these codes put together in one location. Is very useful for me.

  21. #21
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    36,812

    Re: Frequently Asked VB Questions

    As dee-u said most of these, along with many other things, are in our Classic VB FAQs (in the FAQ forum, which is shown near the top of our home page) - all organised in an easier to read format.

    This thread was created while the FAQs were in progress, and several of the posts here are duplicated in the FAQs (often with more explanation and/or alternative methods of doing the same thing).

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.