-
Notifications
You must be signed in to change notification settings - Fork 39
/
MRUManager.cs
471 lines (387 loc) · 14 KB
/
MRUManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
// MRI list manager.
//
// Written by: Alex Farber
//
/*******************************************************************************
Using:
1) Add menu item Recent Files (or any name you want) to main application menu.
This item is used by MRUManager as popup menu for MRU list.
2) Implement IMRUClient inteface in the form class:
public class frmMain : System.Windows.Forms.Form, IMRUClient
{
public void OpenMRUFile(string fileName)
{
// open file here
}
// ...
}
3) Add MRUManager member to the form class and initialize it:
private MRUManager mruManager;
private void frmMain_Load(object sender, System.EventArgs e)
{
mruManager = new MRUManager();
mruManager.Initialize(
this, // owner form
mnuFileMRU, // Recent Files menu item
"Software\\MyCompany\\MyProgram"); // Registry path to keep MRU list
// Optional. Call these functions to change default values:
mruManager.CurrentDir = "....."; // default is current directory
mruManager.MaxMRULength = ...; // default is 10
mruMamager.MaxDisplayNameLength = ...; // default is 40
}
NOTES:
- If Registry path is, for example, "Software\MyCompany\MyProgram",
MRU list is kept in
HKEY_CURRENT_USER\Software\MyCompany\MyProgram\MRU Registry entry.
- CurrentDir is used to show file names in the menu. If file is in
this directory, only file name is shown.
4) Call MRUManager Add and Remove functions when necessary:
mruManager.Add(fileName); // when file is successfully opened
mruManager.Remove(fileName); // when Open File operation failed
*******************************************************************************/
// Implementation details:
//
// MRUManager loads MRU list from Registry in Initialize function.
// List is saved in Registry when owner form is closed.
//
// MRU list in the menu is updated when parent menu is poped-up.
//
// Owner form OpenMRUFile function is called when user selects file
// from MRU list.
namespace MRU
{
/// <summary>
/// Interface which should be implemented by owner form
/// to use MRUManager.
/// </summary>
public interface IMRUClient
{
void OpenMRUFile(string fileName);
}
/// <summary>
/// MRU manager - manages Most Recently Used Files list
/// for Windows Form application.
/// </summary>
public class MRUManager
{
#region Members
private const string regEntryName = "file"; // entry name to keep MRU (file0, file1...)
private readonly ArrayList mruList; // MRU list (file names)
private bool bmenuUpdate;
private string currentDirectory; // current directory
private int maxDisplayLength = 40; // maximum length of file name for display
private int maxNumberOfFiles = 10; // maximum number of files in MRU list
private ToolStripMenuItem menuItemMRU; // Recent Files menu item
private ToolStripMenuItem menuItemParent; // Recent Files menu item parent
private Form ownerForm; // owner form
private string registryPath; // Registry path to keep MRU list
#endregion
#region Windows API
// BOOL PathCompactPathEx(
// LPTSTR pszOut,
// LPCTSTR pszSrc,
// UINT cchMax,
// DWORD dwFlags
// );
[DllImport("shlwapi.dll", CharSet = CharSet.Auto)]
private static extern bool PathCompactPathEx(
StringBuilder pszOut,
string pszPath,
int cchMax,
int reserved);
#endregion
#region Constructor
public MRUManager()
{
mruList = new ArrayList();
}
#endregion
#region Public Properties
/// <summary>
/// Maximum length of displayed file name in menu (default is 40).
///
/// Set this property to change default value (optional).
/// </summary>
public int MaxDisplayNameLength
{
set
{
maxDisplayLength = value;
if (maxDisplayLength < 10)
maxDisplayLength = 10;
}
get { return maxDisplayLength; }
}
/// <summary>
/// Maximum length of MRU list (default is 10).
///
/// Set this property to change default value (optional).
/// </summary>
public int MaxMRULength
{
set
{
maxNumberOfFiles = value;
if (maxNumberOfFiles < 1)
maxNumberOfFiles = 1;
if (mruList.Count > maxNumberOfFiles)
mruList.RemoveRange(maxNumberOfFiles - 1, mruList.Count - maxNumberOfFiles);
}
get { return maxNumberOfFiles; }
}
/// <summary>
/// Set current directory.
///
/// Default value is program current directory which is set when
/// Initialize function is called.
///
/// Set this property to change default value (optional)
/// after call to Initialize.
/// </summary>
public string CurrentDir
{
set { currentDirectory = value; }
get { return currentDirectory; }
}
#endregion
#region Public Functions
/// <summary>
/// Initialization. Call this function in form Load handler.
/// </summary>
/// <param name="owner">Owner form</param>
/// <param name="mruItem">Recent Files menu item</param>
/// <param name="regPath">Registry Path to keep MRU list</param>
public void Initialize(Form owner, ToolStripMenuItem mruPar, ToolStripMenuItem mruItem, string regPath)
{
// keep reference to owner form
ownerForm = owner;
// check if owner form implements IMRUClient interface
if (!(owner is IMRUClient))
{
throw new Exception(
"MRUManager: Owner form doesn't implement IMRUClient interface");
}
// keep reference to MRU menu item
menuItemMRU = mruItem;
menuItemParent = mruPar;
// keep Registry path adding MRU key to it
registryPath = regPath;
if (registryPath.EndsWith("\\"))
registryPath += "MRU";
else
registryPath += "\\MRU";
// keep current directory in the time of initialization
currentDirectory = Directory.GetCurrentDirectory();
// subscribe to MRU parent Popup event
menuItemParent.DropDownOpened += OnMRUParentPopup;
// subscribe to owner form Closing event
ownerForm.Closing += OnOwnerClosing;
// load MRU list from Registry
LoadMRU();
}
/// <summary>
/// Add file name to MRU list.
/// Call this function when file is opened successfully.
/// If file already exists in the list, it is moved to the first place.
/// </summary>
/// <param name="file">File Name</param>
public void Add(string file)
{
Remove(file);
// if array has maximum length, remove last element
if (mruList.Count == maxNumberOfFiles)
mruList.RemoveAt(maxNumberOfFiles - 1);
// add new file name to the start of array
mruList.Insert(0, file);
bmenuUpdate = true;
}
/// <summary>
/// Remove file name from MRU list.
/// Call this function when File - Open operation failed.
/// </summary>
/// <param name="file">File Name</param>
public void Remove(string file)
{
int i = 0;
IEnumerator myEnumerator = mruList.GetEnumerator();
while (myEnumerator.MoveNext())
{
if ((string) myEnumerator.Current == file)
{
mruList.RemoveAt(i);
return;
}
i++;
}
bmenuUpdate = true;
}
#endregion
#region Event Handlers
/// <summary>
/// Update MRU list when MRU menu item parent is opened
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnMRUParentPopup(object sender, EventArgs e)
{
if (!bmenuUpdate)
return;
// remove all childs
menuItemMRU.DropDownItems.Clear();
// Disable menu item if MRU list is empty
if (mruList.Count == 0)
{
menuItemMRU.Enabled = false;
return;
}
// enable menu item and add child items
menuItemMRU.Enabled = true;
IEnumerator myEnumerator = mruList.GetEnumerator();
int i = 0;
while (myEnumerator.MoveNext())
{
var item = new ToolStripMenuItem(GetDisplayName((string) myEnumerator.Current));
item.Tag = i;
// subscribe to item's Click event
item.Click += OnMRUClicked;
menuItemMRU.DropDownItems.Add(item);
i++;
}
bmenuUpdate = false;
}
/// <summary>
/// MRU menu item is clicked - call owner's OpenMRUFile function
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnMRUClicked(object sender, EventArgs e)
{
string s;
try
{
// cast sender object to MenuItem
var item = (ToolStripMenuItem) sender;
if (item != null)
{
s = (string) mruList[(int) item.Tag];
if (s.Length > 0)
{
((IMRUClient) ownerForm).OpenMRUFile(s);
}
}
}
catch (Exception ex)
{
Trace.WriteLine("Exception in OnMRUClicked: " + ex.Message);
}
}
/// <summary>
/// Save MRU list in Registry when owner form is closing
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnOwnerClosing(object sender, CancelEventArgs e)
{
int i, n;
try
{
RegistryKey key = Registry.CurrentUser.CreateSubKey(registryPath);
if (key != null)
{
n = mruList.Count;
for (i = 0; i < maxNumberOfFiles; i++)
{
key.DeleteValue(regEntryName + i.ToString(), false);
}
for (i = 0; i < n; i++)
{
key.SetValue(regEntryName + i.ToString(), mruList[i]);
}
}
}
catch (Exception ex)
{
Trace.WriteLine("Saving MRU to Registry failed: " + ex.Message);
}
}
#endregion
#region Private Functions
/// <summary>
/// Load MRU list from Registry.
/// Called from Initialize.
/// </summary>
private void LoadMRU()
{
string sKey, s;
try
{
mruList.Clear();
RegistryKey key = Registry.CurrentUser.OpenSubKey(registryPath);
if (key != null)
{
for (int i = 0; i < maxNumberOfFiles; i++)
{
sKey = regEntryName + i.ToString();
s = (string) key.GetValue(sKey, "");
if (s.Length == 0)
break;
mruList.Add(s);
}
if (mruList.Count > 0)
bmenuUpdate = true;
}
}
catch (Exception ex)
{
Trace.WriteLine("Loading MRU from Registry failed: " + ex.Message);
}
}
/// <summary>
/// Get display file name from full name.
/// </summary>
/// <param name="fullName">Full file name</param>
/// <returns>Short display name</returns>
private string GetDisplayName(string fullName)
{
// if file is in current directory, show only file name
var fileInfo = new FileInfo(fullName);
if (fileInfo.DirectoryName == currentDirectory)
return GetShortDisplayName(fileInfo.Name, maxDisplayLength);
return GetShortDisplayName(fullName, maxDisplayLength);
}
/// <summary>
/// Truncate a path to fit within a certain number of characters
/// by replacing path components with ellipses.
///
/// This solution is provided by CodeProject and GotDotNet C# expert
/// Richard Deeming.
///
/// </summary>
/// <param name="longName">Long file name</param>
/// <param name="maxLen">Maximum length</param>
/// <returns>Truncated file name</returns>
private string GetShortDisplayName(string longName, int maxLen)
{
var pszOut = new StringBuilder(maxLen + maxLen + 2); // for safety
if (PathCompactPathEx(pszOut, longName, maxLen, 0))
{
return pszOut.ToString();
}
else
{
return longName;
}
}
#endregion
}
}