using System;
using System.Windows.Forms;
using Microsoft.Win32;
#region FormLoad
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
try
{
using (RegistryKey userKey = Application.UserAppDataRegistry)
{
RegistryKey pathKey = userKey.CreateSubKey("FileList");
foreach (string path in pathKey.GetValueNames()) // 加载历史文件路径,并自动清除不存在的文件路径。
{
if (File.Exists(path))
fileListMenu.DropDownItems.Add(path).MouseUp += new MouseEventHandler(menuItem_MouseUp);
else
pathKey.DeleteValue(path);
}
}
}
catch (Exception se)
{
MessageBox.Show(this, se.Message, "写字板", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
#endregion
#region DragDropFile
private void richText_DragEnter(object sender, DragEventArgs e)
{
DataObject newData = e.Data as DataObject; // 获取拖放的数据对象。
if (richText.EnableAutoDragDrop = !newData.ContainsFileDropList())
return;
if (GetModified())
return;
this.LoadFile(newData.GetFileDropList()[0]);
using (RegistryKey subKey = Application.UserAppDataRegistry.CreateSubKey("FileList"))
{
foreach (string filePath in newData.GetFileDropList())
{
subKey.SetValue(filePath, "");
if (fileListMenu.DropDownItems.Count < subKey.ValueCount) // 防止记录重复文件路径。
fileListMenu.DropDownItems.Add(filePath).MouseUp += new MouseEventHandler(menuItem_MouseUp);
}
}
}
#endregion
#region AccessFile
private void recentMenu_Click(object sender, EventArgs e)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Recent);
Process.Start("explorer.exe", path).Close();
}
private void menuItem_MouseUp(object sender, MouseEventArgs e)
{
ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
string filePath = menuItem.Text;
switch (e.Button)
{
case MouseButtons.Left:
if (GetModified())
return;
if (File.Exists(filePath))
{
this.LoadFile(filePath);
foreach (ToolStripMenuItem item in fileListMenu.DropDownItems)
{
item.Checked = item.Equals(menuItem);
}
}
else
MessageBox.Show(this, string.Format("指定的文件 {0} 不存在。", filePath), "写字板", MessageBoxButtons.OK, MessageBoxIcon.Warning);
break;
case MouseButtons.Right:
fileMenu.HideDropDown();
if (MessageBox.Show(this, string.Format("确实要删除 {0} 文件路径吗?", filePath), "确认删除项", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
fileListMenu.DropDownItems.Remove(menuItem);
using (RegistryKey subKey = Application.UserAppDataRegistry.OpenSubKey("FileList", true)) // true, 读/写访问。
{
if (subKey != null)
subKey.DeleteValue(filePath, false); // false, 指定的值不存在时不引发异常。
}
}
break;
}
}
private void fileClearMenu_Click(object sender, EventArgs e)
{
if (fileListMenu.HasDropDownItems)
{
fileListMenu.DropDownItems.Clear();
using (RegistryKey subKey = Application.UserAppDataRegistry)
{
subKey.DeleteSubKey("FileList", false); // false, 指定的子项不存在时不引发异常。
}
}
}
#endregion