Sunday, June 17, 2012

Contoh MRU - Most Recently Used

Option Explicit

Private Const MaxMRU = 4
Private Const NotFound = -1
Private Const NoMRUs = -1

Private MRUCount As Long

Private Sub Form_Load()
MRUCount = NoMRUs

GetMRUFileList
End Sub

Private Sub Form_Unload(Cancel As Integer)
SaveMRUFileList
End Sub

Private Sub mnuMRU_Click(Index As Integer)
ReorderMRUList mnuMRU(Index).Caption, CLng(Index)
End Sub

Private Sub mnuOpen_Click()
Me.CommonDialog1.ShowOpen

AddMRUItem Me.CommonDialog1.FileName
End Sub

Private Sub AddMRUItem(NewItem As String)
Dim result As Long

result = CheckForDuplicateMRU(NewItem)

If result <> NotFound Then
ReorderMRUList NewItem, result
Else
AddMenuElement NewItem
End If
End Sub

Private Function CheckForDuplicateMRU(ByVal NewItem As String) As Long
Dim i As Long

NewItem = UCase$(NewItem)

For i = 0 To MRUCount
If UCase$(Me.mnuMRU(i).Caption) = NewItem Then
CheckForDuplicateMRU = i

Exit Function
End If
Next i

CheckForDuplicateMRU = -1
End Function

Private Sub mnuQuit_Click()
Unload Me
End Sub

Private Sub AddMenuElement(NewItem As String)
Dim i As Long

If (MRUCount < (MaxMRU - 1)) Or (MaxMRU = -1) Then
MRUCount = MRUCount + 1

If MRUCount <> 0 Then
Load mnuMRU(MRUCount)
End If

mnuMRU(MRUCount).Visible = True
End If

For i = (MRUCount) To 1 Step -1
mnuMRU(i).Caption = mnuMRU(i - 1).Caption
Next i

mnuMRU(0).Caption = NewItem
End Sub

Private Sub ReorderMRUList(DuplicateMRU As String, DuplicateLocation As Long)
Dim i As Long

For i = DuplicateLocation To 1 Step -1
mnuMRU(i).Caption = mnuMRU(i - 1).Caption
Next i

mnuMRU(0).Caption = DuplicateMRU
End Sub

Private Sub GetMRUFileList()
Dim i As Long
Dim result As String

Do
result = GetSetting(App.Title, "MRUFiles", Trim$(CStr(i)), "")

If result <> "" Then
AddMRUItem result
End If

i = i + 1
Loop Until (result = "")
End Sub

Private Sub SaveMRUFileList()
Dim i As Long

For i = 0 To MRUCount
SaveSetting App.Title, "MRUFiles", Trim$(CStr(i)), mnuMRU(i).Caption
Next i
End Sub