Hàm mở Dialog đa dụng, nhận diện nút cancel

Liên hệ QC

kidoto

Thành viên mới
Tham gia
18/12/07
Bài viết
19
Được thích
3
Vấn đề này có nhiều rồi, nhưng trường hợp này hơi khác, cho nên biện pháp dialogbox1.filename ="" không hiệu quả nữa, cụ thể như sau:

PHP:
Public Function OpenDialogF _
                        ( _
                                  cdopen As CommonDialog, _
                            ByVal strFilter As String, _
                            Optional strAutoFileName As String, _
                            Optional blnOpen0_Save1 As Byte _
                        ) _
                        As String
    
    Dim Traloi As Integer, strTemp As String
    
    '--------------------------------------------------
    'blnOpen0_Save1 = 0 thi day la tac vu mo file
    'blnOpen0_Save1 = 1 thi day la tac vu luu file
    'Ham tra ve gia tri path Name string
    '--------------------------------------------------
    If Trim(strFilter) = "" Then strFilter = "All file (*.*)|*.*"
Luu:
    With cdopen
        .Filter = strFilter
        If blnOpen0_Save1 = 1 Then
                .FileName = strAutoFileName
                .DialogTitle = "Luu file"
                .ShowSave
        Else
                .DialogTitle = "Mo file"
                .ShowOpen
        End If
        If cdopen.CancelError = True Then
                OpenDialogF = ""
                Exit Function
        End If
        If cdopen.Action = vbCancel Then
                OpenDialogF = ""
                Exit Function
        End If
        If Len(.FileName) = 0 Then
            strTemp = ""
            OpenDialogF = strTemp
            Exit Function
        Else
            strTemp = .FileName
        End If
    End With

    'kiem tra file co ton tai hay chua?
    If blnOpen0_Save1 = 1 Then
        If FileExists(strTemp) Then        
            Traloi = MsgBox("File da ton tai. Ban co muon ghi de len khong?", vbYesNo + vbQuestion)
            If Traloi = vbNo Then
                strTemp = ""
                GoTo Luu
            End If
        End If
    End If
    OpenDialogF = strTemp
End Function

Public Function FileExists(sFile As String) As Boolean
    On Error Resume Next
    FileExists = ((GetAttr(sFile) And vbDirectory) = 0)
End Function

Ví dụ sử dụng:

strSave = OpenDialogF(CommonDialog1, "mdb file (*.mdb)|*.mdb", "File luu tru - Tinh thep", 1)

Hàm này có khả năng khá tốt trong mở, hay đóng file, khá tiện dụng khi đưa ra ý tưởng có tên file mặc định (dành cho máy cái người "lười biếng" :D), tuy nhiên, Khi đó giá trị trả về của fileName luôn có len>0 mặc dù người dùng nhấn nút cancel :(( (vì nó có filename = tên mặc định), trừ khi người dùng xóa tên file mặc định đi rồi mới click cancel.

Các bạn giúp mình nhận diện khi nào người ta nhấn cancel nhé, thanks nhiều nhiều :D

(Mình dã thử thuộc tính Cancelerror nhưng ra false.)
 
Web KT
Back
Top Bottom