Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

CommonControlDialog 6-VB5-ShowOpen Problem 1

Status
Not open for further replies.

hafod

Technical User
Mar 14, 2005
73
0
0
GB
Hi,
I am having difficulties with what perhaps should be a simple VB programming task, using the ShowOpen Method of the Common control dialog box. I have looked at many beginner books and have reduced the coding to the following to help debug the code. I have attempted to use a filter to open 'txt' files created in Notepad.

When I use the dialog the 'Files of Type box' drop-down is empty -not populated. double clicking on a file gives error Message 53: file Not found. Suprising because a text file 'Log.txt', created in notepad actually exists in the location selected using the Fileopen Dialog. If I set a breakpoint over strFileName the path "c:\temp\log.txt" is correctly contained in the variable. I have tried 'shelling' directly using this path/filename but still get the same error message.


The code is part of a database programming application which logs particular records to a text file. this part ironically the complex part using ADO recordsets works fine!

in summary, I simply want to double click on a txt file selected by the user and it is launched using Notepad.

So, having reduced the problem with still no 'joy', can anyone help identify my problem?

Many thanks in anticipation.


Code:
Private Sub cmdOpenFiles_Click()

Dim StrFileName As String
dbTextFiles.ShowOpen
dbTextFiles.Filter = "Text Files (*.txt)|.txt"
StrFileName = dbTextFiles.FileName
lblFileName.Caption = StrFileName
Shell "notepad.exe" & "StrFileName", vbNornalFocus


End Sub
 
There are a couple problems.

1. You need to set the filter property BEFORE you call the .ShowOpen method.

The way you are shelling to notepad is NOT right. In fact, I would recommend that you 'forget about' notepad and just open the document in it's default application.

Like this...

Code:
Private Sub cmdOpenFiles_Click()

  Dim StrFileName As String

  On Error Goto CancelError

  dbTextFiles.CancelError = True
  dbTextFiles.Filter = "Text Files (*.txt)|.txt"
  dbTextFiles.ShowOpen
  StrFileName = dbTextFiles.FileName
  lblFileName.Caption = StrFileName
  Shell "cmd /c """ & StrFileName & """", vbHide

CancelError:

End Sub

You'll want to use vbHide. Shell essentially opens a command window. It's this command window that will be hidden.

And, lastly, you'll want to handle the case where the user clicks the cancel button.

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Hi George
I will try your source code tomorrow. I am not familiar with the syntax in the following line - could you expand on this? Are these arguments associated with the use of cmd? are there others? Would I need to set the default app for txt files (associations) using Win O/S.

Many thanks for your reply,
Mike

Code:
Shell "cmd /c """ & StrFileName & """", vbHide
 
There is already an association with txt files in the operating system. To verify this, open windows explorer, find a txt file and double click it. Explorer will open the file with whatever the default application is. In most cases, NotePad is the default application for txt files.

Now, looking at the shell command, you will notice that there are a lot of quotes. This line will work (I tested it). The 'extra' quotes exist so that you can accomodate files that have spaces in their name. When building a string in VB, if you want to have a quote within the string, you need to double it. so...

[tt]Shell "cmd /c [!]""[/!]" & StrFileName & "[!]""[/!]", vbHide[/tt]

The highlighted quotes will appear within the string as a single quote.

For example, suppose you have this file:
C:\Program Files\My Application\My Data\This File.txt

Normally, all those spaces would cause a problem. However, by putting quotes around it, it will open properly using notepad.

Does this explanation help?

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Hi George,
Yes, your last post was very helpful indeed to me in understanding the code. i suppose it is much like parsing in SQL (usually a nightmare!), often avoided by the squared brackets on field names where spaces can be problemmatic '[Field Name]' - and avoided and mixed numeric/string variables in a long SQL string literal. I will try your code tomorrow and post a reply - technical issues on PC #2 at present!

Again, many thanks
To be continued .....
 
Hi George,
'Bright and Early Start' today! Thanks for possts yesterday. The modified code correctly displays 'Text Files (*.txt)' in the 'Files Of Type, File Open dialog box. However, when I use the right hand pane to say navigate to 'c\temp', no associated text (.txt) files are displayed despite several located in the folder. Seems the filter is 'filtering out' the .txt files - so selection is not possible! I see what ou mean by managing the 'Cancel' event, but that is not the imperitive now. Solution seems elusive at present.

Any suggestions?
Best regards Mike
 
Starting a Cmd.exe instance just to open a document works, but using the same VB syntax to build up the command string it is just as legit to run NotePad directly.

Running Cmd.exe has the advantage of using file associations to choose the tool to use, but it adds overhead and you lose control over the way the application window opens.

An alternative might be:
Code:
Option Explicit

'Requires Microsoft Layer for Unicode on Windows 9x.
Private Declare Function ShellExecute Lib "shell32" _
    Alias "ShellExecuteA" ( _
    ByVal hWnd As Long, _
    ByVal lpOperation As String, _
    ByVal lpFile As String, _
    ByVal lpParameters As String, _
    ByVal lpDirectory As String, _
    ByVal nShowCmd As Long) As Long

Private Function ShellOpen(ByVal File As String) As Long
    ShellOpen = ShellExecute(Me.hWnd, "Open", File, _
                             vbNullString, vbNullString, vbNormalFocus)
End Function

Private Sub Command1_Click()
    Dim lngResult As Long
    
    lngResult = ShellOpen("some.txt")
    If lngResult <= 32 Then
        MsgBox "Error " & CStr(lngResult) & " calling ShellExecute."
    End If
End Sub
 
Also, the line:

[tt] dbTextFiles.Filter = "Text Files (*.txt)|.txt"[/tt]

... has a typo:

[tt] dbTextFiles.Filter = "Text Files (*.txt)|*.txt"[/tt]
 
Hi dilettante,
Many thanks for your post. I assume your first reply relates to WIN API programming solution (I have no experience of programming the API), but it seems a more flexible, powerfull approach. Unfortunately it reurns an 'Error2' message when executed. I have tried several string literals where you indicate 'some.txt', including an actual path and filename to a txt file. The Open dialog is not displayed. I copied the functions and inserted them (both)into the 'Form Declarations'.

Thanks for your second post also, re the 'typo'. I corrected this but this apparently simple solution still fails to display anything in the 'Files Of Type' combo in the File Open dialog box; but, the text files are correctly filtered and shown in the right hand pane against the chosen 'temp' directory (c\temp ,say).

Double clicking on a text file yields 'Run Time Error 53: File Not Found'. Any suggestions?

Again thanks for your posts

Mike
 
Your "error 2" is "file not found." As given, the example above expects the text file to be in the same path as the EXE unless you provide the full path.

If your Open dialog can't show you any text files I suspect the Filter is still wrong.

Make a new project with just one form. Then add the CommonDialog component to the project toolbox. Then add one CommandButton and one CommonDialog to the form. Finally paste this code into the form:
Code:
Option Explicit

'Requires Microsoft Layer for Unicode on Windows 9x.
Private Declare Function ShellExecute Lib "shell32" Alias _
    "ShellExecuteA" ( _
    ByVal hWnd As Long, _
    ByVal lpOperation As String, _
    ByVal lpFile As String, _
    ByVal lpParameters As String, _
    ByVal lpDirectory As String, _
    ByVal nShowCmd As Long) As Long

Private Function ShellOpen(ByVal File As String) As Long
    ShellOpen = ShellExecute(Me.hWnd, "Open", File, _
                             vbNullString, vbNullString, vbNormalFocus)
End Function

Private Sub Command1_Click()
    Dim lngResult As Long
    
    With CommonDialog1
        .CancelError = True
        .DialogTitle = "Open text file"
        .Filter = "Text Files (*.txt)|*.txt"
        On Error Resume Next
        .ShowOpen
        lngResult = Err.Number
        On Error GoTo 0
        If lngResult = 0 Then
            lngResult = ShellOpen(.FileName)
            If lngResult <= 32 Then
                MsgBox "Error " & CStr(lngResult) & " calling ShellExecute."
            End If
        Else
            MsgBox "User canceled Open dialog."
        End If
    End With
End Sub
Or just use the logic shown above for your CommonDialog, whether you take the long run of running Cmd.exe to start Notepad or not.


VB's Shell() function is a wrapper on the CreateObject() API call. Calling ShellExecute() of Shell32.dll is an alternate route for starting an external process, and no more exotic than running Cmd.exe to start yet a third program. ;-)

I don't like gratuitous use of API calls in VB either, but here it makes sense. The decision is yours of course.

Good luck.
 
Hi dilettante,
Eureka! Solution works well (API).

Still cant resolve issue with simpler approach - but will continue - resolve is what is needed here I suspect. But, I now have a solution to my problem!.

Can you advise whether a similar API programming approach can be used to Save (Save As) an open file. Would this involve only minor changes to say, the arguments used if the same code segments were copied to a new command button (say cmdSave), and two new and modified functions declared on the form.

Again,
many thanks for your help
Mike
 
Save just tells your app WHERE to save something. It is up to you to write the code to actually save the file. You could read it into a textbox, let the user edit it, and then write it back out.

-David
2006 Microsoft Most Valueable Professional (MVP)
2006 Dell Certified System Professional (CSP)
 
You probably want to use the CommonDialog's ShowSave method, but no it won't save anything by itself. It just lets you choose a folder and file to save to.

The API call was just a workaround to do something a little different than what the Shell() function in VB does.


gmmastros' Shell() call using Cmd.exe as he showed should work fine unless you are using Windows 95/98/Me. Then you do the same sort of thing, with Command.com instead.
 
Many thanks dilettante, gmmastros and dglienna for your very helpful contributions on this topic. I can now proceed to further develop my dB VB6 database application, pending of course the next problem. But, the challenge is to resolve these problem oneself first before seeking the help of experts. Therin lies the 'learning overhead'!
Many thanks,
Mike
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top