diff --git a/ContextMenuManager/BluePointLilac.Controls/BackupDialog.cs b/ContextMenuManager/BluePointLilac.Controls/BackupDialog.cs index 8609b2f9..abd8af1e 100644 --- a/ContextMenuManager/BluePointLilac.Controls/BackupDialog.cs +++ b/ContextMenuManager/BluePointLilac.Controls/BackupDialog.cs @@ -1,308 +1,316 @@ -using BluePointLilac.Methods; -using ContextMenuManager.Methods; -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Linq; -using System.Windows.Forms; - -namespace BluePointLilac.Controls -{ - public class BackupDialog : CommonDialog - { - public string Title { get; set; } - public string CmbTitle { get; set; } - public string[] CmbItems { get; set; } - public int CmbSelectedIndex { get; set; } - public string CmbSelectedText { get; set; } - public string TvTitle { get; set; } - public string[] TvItems { get; set; } - public List TvSelectedItems { get; set; } - - public override void Reset() { } - - protected override bool RunDialog(IntPtr hwndOwner) - { - using (SelectForm frm = new SelectForm()) - { - frm.Text = Title; - frm.CmbTitle = CmbTitle; - frm.CmbItems = CmbItems; - frm.TvTitle = TvTitle; - frm.TvItems = TvItems; - if (CmbSelectedText != null) frm.CmbSelectedText = CmbSelectedText; - else frm.CmbSelectedIndex = CmbSelectedIndex; - if (Control.FromHandle(hwndOwner) is Form owner) frm.TopMost = true; - bool flag = frm.ShowDialog() == DialogResult.OK; - if (flag) - { - CmbSelectedText = frm.CmbSelectedText; - CmbSelectedIndex = frm.CmbSelectedIndex; - TvSelectedItems = frm.TvSelectedItems; - } - return flag; - } - } - - sealed class SelectForm : RForm - { - public SelectForm() - { - SuspendLayout(); - AcceptButton = btnOK; - CancelButton = btnCancel; - Font = SystemFonts.MenuFont; - ShowIcon = ShowInTaskbar = false; - MaximizeBox = MinimizeBox = false; - FormBorderStyle = FormBorderStyle.FixedSingle; - StartPosition = FormStartPosition.CenterParent; - InitializeComponents(); - ResumeLayout(); - InitTheme(); - } - - public string CmbTitle - { - get => cmbInfo.Text; - set - { - cmbInfo.Text = value; - cmbItems.Left = cmbInfo.Right; - cmbItems.Width -= cmbInfo.Width; - } - } - public string[] CmbItems - { - get - { - string[] value = new string[cmbItems.Items.Count]; - cmbItems.Items.CopyTo(value, 0); - return value; - } - set - { - cmbItems.Items.Clear(); - cmbItems.Items.AddRange(value); - } - } - public int CmbSelectedIndex - { - get => cmbItems.SelectedIndex; - set => cmbItems.SelectedIndex = value; - } - public string CmbSelectedText - { - get => cmbItems.Text; - set => cmbItems.Text = value; - } - - public string TvTitle - { - get => tvInfo.Text; - set => tvInfo.Text = value; - } - private string[] tvValue; - public string[] TvItems - { - get => tvValue; - set { tvValue = value; ShowTreeView(); } - } - private readonly List tvSelectedItems = new List(); - public List TvSelectedItems => GetSortedTvSelectedItems(); - - readonly Label tvInfo = new Label { AutoSize = true }; - readonly TreeView treeView = new TreeView - { - ForeColor = MyMainForm.FormFore, - BackColor = MyMainForm.FormBack, - CheckBoxes = true, - Indent = 20.DpiZoom(), - ItemHeight = 25.DpiZoom(), - }; - private bool isFirst = true; - private bool changeDone = false; - - readonly CheckBox checkAll = new CheckBox - { - Name = "CheckAll", - Text = AppString.Dialog.SelectAll, - AutoSize = true, - }; - - readonly Label cmbInfo = new Label { AutoSize = true }; - readonly RComboBox cmbItems = new RComboBox - { - AutoCompleteMode = AutoCompleteMode.SuggestAppend, - AutoCompleteSource = AutoCompleteSource.ListItems, - DropDownHeight = 300.DpiZoom(), - DropDownStyle = ComboBoxStyle.DropDownList, - ImeMode = ImeMode.Disable - }; - - readonly Button btnOK = new Button - { - DialogResult = DialogResult.OK, - Text = ResourceString.OK, - AutoSize = true - }; - readonly Button btnCancel = new Button - { - DialogResult = DialogResult.Cancel, - Text = ResourceString.Cancel, - AutoSize = true - }; - - private void InitializeComponents() - { - Controls.AddRange(new Control[] { tvInfo, treeView, checkAll, cmbInfo, cmbItems, btnOK, btnCancel }); - int margin = 20.DpiZoom(); - int cmbItemsWidth = 300.DpiZoom(); - int tvHeight = 300.DpiZoom(); - tvInfo.Top = checkAll.Top = margin; - tvInfo.Left = treeView.Left = cmbInfo.Left = margin; - treeView.Top = tvInfo.Bottom + 5.DpiZoom(); - treeView.Height = tvHeight; - cmbInfo.Top = cmbItems.Top = treeView.Bottom + margin; - cmbItems.Left = cmbInfo.Right; - cmbItems.Width = cmbItemsWidth; - btnOK.Top = btnCancel.Top = cmbItems.Bottom + margin; - btnOK.Left = (cmbItems.Width + cmbInfo.Width + 2 * margin - margin) / 2 - btnOK.Width; - btnCancel.Left = btnOK.Right + margin; - ClientSize = new Size(cmbItems.Right + margin, btnCancel.Bottom + margin); - treeView.Width = ClientSize.Width - 2 * margin; - checkAll.Left = treeView.Right - checkAll.Width; - checkAll.Click += CheckAll_CheckBoxMouseClick; - cmbItems.AutosizeDropDownWidth(); - } - - private void ShowTreeView() - { - treeView.Nodes.Add(new TreeNode(AppString.ToolBar.Home)); - treeView.Nodes.Add(new TreeNode(AppString.ToolBar.Type)); - treeView.Nodes.Add(new TreeNode(AppString.ToolBar.Rule)); - - for (int i = 0; i < TvItems.Length; i++) - { - string treeNodeText = TvItems[i]; - if (BackupHelper.HomeBackupScenesText.Contains(treeNodeText)) - treeView.Nodes[0].Nodes.Add(new TreeNode(treeNodeText)); - else if (BackupHelper.TypeBackupScenesText.Contains(treeNodeText)) - treeView.Nodes[1].Nodes.Add(new TreeNode(treeNodeText)); - else if (BackupHelper.RuleBackupScenesText.Contains(treeNodeText)) - treeView.Nodes[2].Nodes.Add(new TreeNode(treeNodeText)); - } - - for (int i = 0; i < treeView.Nodes.Count; i++) - { - if (treeView.Nodes[i].Nodes.Count == 0) - { - treeView.Nodes.RemoveAt(i); - i--; - } - } - - treeView.BeforeCheck += TreeView_BeforeCheck; - treeView.AfterSelect += TreeView_AfterSelect; - treeView.AfterCheck += TreeView_AfterCheck; - } - - private void TreeView_BeforeCheck(object sender, TreeViewCancelEventArgs e) - { - if (e.Node == treeView.Nodes[0] && isFirst) - { - e.Cancel = true; - isFirst = false; - } - } - - private void TreeView_AfterCheck(object sender, TreeViewEventArgs e) - { - if (e.Node != null && !changeDone) - { - TreeNode node = e.Node; - bool isChecked = node.Checked; - string nodeText = e.Node.Text; - changeDone = true; - - if (nodeText == AppString.ToolBar.Home || nodeText == AppString.ToolBar.Type || nodeText == AppString.ToolBar.Rule) - { - for (int i = 0; i < node.Nodes.Count; i++) - { - TreeNode childNode = node.Nodes[i]; - childNode.Checked = isChecked; - if (isChecked) - { - if (!tvSelectedItems.Contains(childNode.Text)) - tvSelectedItems.Add(childNode.Text); - } - else - tvSelectedItems.Remove(childNode.Text); - } - } - else - { - int brotherNodeCheckedCount = node.Parent.Nodes.Cast().Count(tn => tn.Checked); - node.Parent.Checked = brotherNodeCheckedCount >= 1; - if (isChecked) - { - if (!tvSelectedItems.Contains(node.Text)) - tvSelectedItems.Add(node.Text); - } - else - tvSelectedItems.Remove(node.Text); - } - checkAll.Checked = tvSelectedItems.Count == tvValue.Length; - changeDone = false; - } - } - - private void TreeView_AfterSelect(object sender, TreeViewEventArgs e) - { - if (e.Node != null) - { - e.Node.Checked = !e.Node.Checked; - treeView.SelectedNode = null; - } - } - - private void CheckAll_CheckBoxMouseClick(object sender, EventArgs e) - { - // 修复:设置 changeDone 为 true 防止递归调用 - changeDone = true; - - bool isChecked = checkAll.Checked; - for (int i = 0; i < treeView.Nodes.Count; i++) - { - for (int j = 0; j < treeView.Nodes[i].Nodes.Count; j++) - { - treeView.Nodes[i].Nodes[j].Checked = isChecked; - if (isChecked) - { - if (!tvSelectedItems.Contains(treeView.Nodes[i].Nodes[j].Text)) - tvSelectedItems.Add(treeView.Nodes[i].Nodes[j].Text); - } - else - tvSelectedItems.Remove(treeView.Nodes[i].Nodes[j].Text); - } - treeView.Nodes[i].Checked = isChecked; - } - - changeDone = false; - } - - private List GetSortedTvSelectedItems() - { - // 直接从 tvSelectedItems 获取已选项,而不是重新遍历树节点 - List sortedTvSelectedItems = - [ - // 按照原始顺序排序 - .. BackupHelper.HomeBackupScenesText.Where(tvSelectedItems.Contains), - .. BackupHelper.TypeBackupScenesText.Where(tvSelectedItems.Contains), - .. BackupHelper.RuleBackupScenesText.Where(tvSelectedItems.Contains), - ]; - - return sortedTvSelectedItems; - } - } - } +using BluePointLilac.Methods; +using ContextMenuManager.Methods; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Windows.Forms; + +namespace BluePointLilac.Controls +{ + public class BackupDialog : CommonDialog + { + public string Title { get; set; } + public string CmbTitle { get; set; } + public string[] CmbItems { get; set; } + public int CmbSelectedIndex { get; set; } + public string CmbSelectedText { get; set; } + public string TvTitle { get; set; } + public string[] TvItems { get; set; } + public List TvSelectedItems { get; set; } + + public override void Reset() { } + + protected override bool RunDialog(IntPtr hwndOwner) + { + using(var frm = new SelectForm()) + { + frm.Text = Title; + frm.CmbTitle = CmbTitle; + frm.CmbItems = CmbItems; + frm.TvTitle = TvTitle; + frm.TvItems = TvItems; + frm.CmbSelectedText = CmbSelectedText ?? (CmbSelectedIndex >= 0 ? CmbItems?[CmbSelectedIndex] : null); + if (Control.FromHandle(hwndOwner) is Form owner) frm.TopMost = true; + + if (frm.ShowDialog() == DialogResult.OK) + { + CmbSelectedText = frm.CmbSelectedText; + CmbSelectedIndex = frm.CmbSelectedIndex; + TvSelectedItems = frm.TvSelectedItems; + return true; + } + return false; + } + } + + sealed class SelectForm : RForm + { + public SelectForm() + { + SuspendLayout(); + AcceptButton = btnOK; + CancelButton = btnCancel; + Font = SystemFonts.MenuFont; + ShowIcon = ShowInTaskbar = MaximizeBox = MinimizeBox = false; + FormBorderStyle = FormBorderStyle.FixedSingle; + StartPosition = FormStartPosition.CenterParent; + InitializeComponents(); + ResumeLayout(); + InitTheme(); + DarkModeHelper.ThemeChanged += OnThemeChanged; + } + + public string CmbTitle + { + get => cmbInfo.Text; + set { cmbInfo.Text = value; cmbItems.Left = cmbInfo.Right; cmbItems.Width -= cmbInfo.Width; } + } + + public string[] CmbItems + { + get + { + var items = new string[cmbItems.Items.Count]; + cmbItems.Items.CopyTo(items, 0); + return items; + } + set + { + cmbItems.Items.Clear(); + cmbItems.Items.AddRange(value); + } + } + + public int CmbSelectedIndex { get => cmbItems.SelectedIndex; set => cmbItems.SelectedIndex = value; } + public string CmbSelectedText { get => cmbItems.Text; set => cmbItems.Text = value; } + public string TvTitle { get => tvInfo.Text; set => tvInfo.Text = value; } + + public string[] TvItems + { + get => tvValue; + set { tvValue = value; ShowTreeView(); } + } + + public List TvSelectedItems => GetSortedTvSelectedItems(); + + private string[] tvValue; + private readonly List tvSelectedItems = new List(); + private bool isFirst = true; + private bool changeDone = false; + + private readonly Label tvInfo = new Label { AutoSize = true }; + private readonly TreeView treeView = new TreeView + { + ForeColor = DarkModeHelper.FormFore, + BackColor = DarkModeHelper.FormBack, + CheckBoxes = true, + Indent = 20.DpiZoom(), + ItemHeight = 25.DpiZoom(), + }; + + private readonly CheckBox checkAll = new CheckBox + { + Name = "CheckAll", + Text = AppString.Dialog.SelectAll, + AutoSize = true, + }; + + private readonly Label cmbInfo = new Label { AutoSize = true }; + private readonly RComboBox cmbItems = new RComboBox + { + AutoCompleteMode = AutoCompleteMode.None, + AutoCompleteSource = AutoCompleteSource.None, + DropDownHeight = 300.DpiZoom(), + DropDownStyle = ComboBoxStyle.DropDownList, + ImeMode = ImeMode.Disable + }; + + private readonly Button btnOK = new Button + { + DialogResult = DialogResult.OK, + Text = ResourceString.OK, + AutoSize = true + }; + + private readonly Button btnCancel = new Button + { + DialogResult = DialogResult.Cancel, + Text = ResourceString.Cancel, + AutoSize = true + }; + + private void InitializeComponents() + { + Controls.AddRange(new Control[] { tvInfo, treeView, checkAll, cmbInfo, cmbItems, btnOK, btnCancel }); + int margin = 20.DpiZoom(); + tvInfo.Top = checkAll.Top = margin; + tvInfo.Left = treeView.Left = cmbInfo.Left = margin; + treeView.Top = tvInfo.Bottom + 5.DpiZoom(); + treeView.Height = 300.DpiZoom(); + cmbInfo.Top = cmbItems.Top = treeView.Bottom + margin; + cmbItems.Left = cmbInfo.Right; + cmbItems.Width = 300.DpiZoom(); + btnOK.Top = btnCancel.Top = cmbItems.Bottom + margin; + btnOK.Left = (cmbItems.Width + cmbInfo.Width + 2 * margin - margin) / 2 - btnOK.Width; + btnCancel.Left = btnOK.Right + margin; + ClientSize = new Size(cmbItems.Right + margin, btnCancel.Bottom + margin); + treeView.Width = ClientSize.Width - 2 * margin; + checkAll.Left = treeView.Right - checkAll.Width; + checkAll.Click += CheckAll_Click; + cmbItems.AutosizeDropDownWidth(); + + treeView.BeforeCheck += TreeView_BeforeCheck; + treeView.AfterSelect += TreeView_AfterSelect; + treeView.AfterCheck += TreeView_AfterCheck; + } + + private void InitTheme() + { + BackColor = DarkModeHelper.FormBack; + ForeColor = DarkModeHelper.FormFore; + tvInfo.ForeColor = DarkModeHelper.FormFore; + checkAll.ForeColor = DarkModeHelper.FormFore; + cmbInfo.ForeColor = DarkModeHelper.FormFore; + btnOK.BackColor = btnCancel.BackColor = DarkModeHelper.ButtonMain; + btnOK.ForeColor = btnCancel.ForeColor = DarkModeHelper.FormFore; + DarkModeHelper.AdjustControlColors(this); + } + + private void OnThemeChanged(object sender, EventArgs e) + { + InitTheme(); + Invalidate(); + } + + private void ShowTreeView() + { + treeView.Nodes.AddRange(new[] + { + new TreeNode(AppString.ToolBar.Home), + new TreeNode(AppString.ToolBar.Type), + new TreeNode(AppString.ToolBar.Rule) + }); + + foreach (var item in TvItems) + { + var node = new TreeNode(item); + if (BackupHelper.HomeBackupScenesText.Contains(item)) + treeView.Nodes[0].Nodes.Add(node); + else if (BackupHelper.TypeBackupScenesText.Contains(item)) + treeView.Nodes[1].Nodes.Add(node); + else if (BackupHelper.RuleBackupScenesText.Contains(item)) + treeView.Nodes[2].Nodes.Add(node); + } + + for (int i = treeView.Nodes.Count - 1; i >= 0; i--) + { + if (treeView.Nodes[i].Nodes.Count == 0) + treeView.Nodes.RemoveAt(i); + } + } + + private void TreeView_BeforeCheck(object sender, TreeViewCancelEventArgs e) + { + if (e.Node == treeView.Nodes[0] && isFirst) + { + e.Cancel = true; + isFirst = false; + } + } + + private void TreeView_AfterCheck(object sender, TreeViewEventArgs e) + { + if (e.Node == null || changeDone) return; + + var node = e.Node; + changeDone = true; + + if (node.Parent == null) + { + foreach (TreeNode child in node.Nodes) + { + child.Checked = node.Checked; + UpdateSelectedItems(child, node.Checked); + } + } + else + { + UpdateParentNodeState(node.Parent); + UpdateSelectedItems(node, node.Checked); + } + + checkAll.Checked = tvSelectedItems.Count == tvValue.Length; + changeDone = false; + } + + private void UpdateParentNodeState(TreeNode parent) + { + bool anyChecked = parent.Nodes.Cast().Any(n => n.Checked); + parent.Checked = anyChecked; + } + + private void UpdateSelectedItems(TreeNode node, bool isChecked) + { + if (node.Parent == null) return; + + if (isChecked && !tvSelectedItems.Contains(node.Text)) + tvSelectedItems.Add(node.Text); + else if (!isChecked) + tvSelectedItems.Remove(node.Text); + } + + private void TreeView_AfterSelect(object sender, TreeViewEventArgs e) + { + if (e.Node != null) + { + e.Node.Checked = !e.Node.Checked; + treeView.SelectedNode = null; + } + } + + private void CheckAll_Click(object sender, EventArgs e) + { + bool check = checkAll.Checked; + foreach (TreeNode parent in treeView.Nodes) + { + parent.Checked = check; + foreach (TreeNode child in parent.Nodes) + { + child.Checked = check; + UpdateSelectedItems(child, check); + } + } + } + + private List GetSortedTvSelectedItems() + { + var selected = treeView.Nodes + .Cast() + .SelectMany(p => p.Nodes.Cast()) + .Where(n => n.Checked) + .Select(n => n.Text) + .ToList(); + + var sorted = new List(); + var allItems = BackupHelper.HomeBackupScenesText + .Concat(BackupHelper.TypeBackupScenesText) + .Concat(BackupHelper.RuleBackupScenesText); + + foreach (var item in allItems) + { + if (selected.Contains(item)) + sorted.Add(item); + } + + return sorted; + } + + protected override void Dispose(bool disposing) + { + if (disposing) DarkModeHelper.ThemeChanged -= OnThemeChanged; + base.Dispose(disposing); + } + } + } } \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Controls/ControlExtensions.cs b/ContextMenuManager/BluePointLilac.Controls/ControlExtensions.cs deleted file mode 100644 index a6a8f5c4..00000000 --- a/ContextMenuManager/BluePointLilac.Controls/ControlExtensions.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Reflection; -using System.Windows.Forms; - -namespace BluePointLilac.Controls -{ - // 扩展方法,用于安全地设置控件样式 - public static class ControlExtensions - { - public static void SetStyle(this Control control, ControlStyles flag, bool value) - { - try - { - // 使用反射调用 SetStyle 方法 - MethodInfo method = typeof(Control).GetMethod("SetStyle", - BindingFlags.NonPublic | BindingFlags.Instance); - - if (method != null) - { - method.Invoke(control, new object[] { flag, value }); - } - } - catch - { - // 如果反射失败,忽略错误 - } - } - } -} \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Controls/DarkModeHelper.cs b/ContextMenuManager/BluePointLilac.Controls/DarkModeHelper.cs new file mode 100644 index 00000000..86299514 --- /dev/null +++ b/ContextMenuManager/BluePointLilac.Controls/DarkModeHelper.cs @@ -0,0 +1,312 @@ +using Microsoft.Win32; +using System; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Runtime.InteropServices; +using System.Threading; +using System.Windows.Forms; + +namespace BluePointLilac.Controls +{ + public static class DarkModeHelper + { + [DllImport("UXTheme.dll", SetLastError = true, EntryPoint = "#138")] + public static extern bool CheckSystemDarkModeStatus(); + + [DllImport("DwmApi")] + private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, int[] attrValue, int attrSize); + + public static event EventHandler ThemeChanged; + private static SynchronizationContext uiContext; + public static Color MainColor = Color.FromArgb(255, 143, 31); + + // 颜色属性 + public static Color TitleArea { get; private set; } + public static Color FormBack { get; private set; } + public static Color FormFore { get; private set; } + public static Color FormBorder { get; private set; } + public static Color ButtonMain { get; private set; } + public static Color ButtonSecond { get; private set; } + public static Color SideBarBackground { get; private set; } + public static Color SideBarSeparator { get; private set; } + public static Color SideBarHovered { get; private set; } + public static Color ToolBarGradientTop { get; private set; } + public static Color ToolBarGradientMiddle { get; private set; } + public static Color ToolBarGradientBottom { get; private set; } + public static Color StatusBarGradientTop { get; private set; } + public static Color StatusBarGradientMiddle { get; private set; } + public static Color StatusBarGradientBottom { get; private set; } + public static Color SearchBoxBack { get; private set; } + public static Color SearchBoxBorder { get; private set; } + public static Color SearchBoxPlaceholder { get; private set; } + public static Color ComboBoxBack { get; private set; } + public static Color ComboBoxFore { get; private set; } + public static Color ComboBoxBorder { get; private set; } + public static Color ComboBoxArrow { get; private set; } + + private static bool _isDarkTheme = false; + public static bool IsDarkTheme => _isDarkTheme; + private static bool _listeningForThemeChanges = false; + + public static void Initialize() + { + uiContext = SynchronizationContext.Current; + if (uiContext == null && Application.MessageLoop) + { + uiContext = new WindowsFormsSynchronizationContext(); + } + + UpdateTheme(); + StartListeningForThemeChanges(); + } + + private static void StartListeningForThemeChanges() + { + if (!_listeningForThemeChanges) + { + SystemEvents.UserPreferenceChanged += OnSystemPreferencesChanged; + _listeningForThemeChanges = true; + } + } + + public static void StopListening() + { + if (_listeningForThemeChanges) + { + SystemEvents.UserPreferenceChanged -= OnSystemPreferencesChanged; + _listeningForThemeChanges = false; + } + } + + public static bool IsDarkThemeEnabled() + { + try + { + using (var key = Registry.CurrentUser.OpenSubKey( + @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize")) + { + var value = key?.GetValue("AppsUseLightTheme"); + return value != null && (int)value == 0; + } + } + catch + { + try { return CheckSystemDarkModeStatus(); } + catch { return false; } + } + } + + public static bool UpdateTheme() + { + bool newDarkTheme = IsDarkThemeEnabled(); + bool changed = _isDarkTheme != newDarkTheme; + _isDarkTheme = newDarkTheme; + + UpdateAllColors(_isDarkTheme); + + if (changed) + { + if (uiContext != null) + { + uiContext.Post(_ => SafeInvokeThemeChanged(), null); + } + else + { + SafeInvokeThemeChanged(); + } + } + + return changed; + } + + public static void ApplyDarkModeToForm(Form form) + { + if (_isDarkTheme && form.IsHandleCreated) + { + try { DwmSetWindowAttribute(form.Handle, 20, new[] { 1 }, 4); } + catch { /* 忽略API错误 */ } + } + } + + private static void UpdateAllColors(bool isDark) + { + if (isDark) SetDarkModeColors(); + else SetLightModeColors(); + } + + private static void SetDarkModeColors() + { + TitleArea = Color.FromArgb(255, 32, 32, 32); + FormBack = Color.FromArgb(255, 28, 28, 28); + FormFore = Color.FromArgb(255, 240, 240, 240); + FormBorder = Color.FromArgb(255, 50, 50, 50); + ButtonMain = Color.FromArgb(255, 55, 55, 55); + ButtonSecond = Color.FromArgb(255, 38, 38, 38); + SideBarBackground = Color.FromArgb(255, 26, 26, 26); + SideBarSeparator = Color.FromArgb(255, 64, 64, 64); + SideBarHovered = Color.FromArgb(255, 51, 51, 51); + ToolBarGradientTop = Color.FromArgb(255, 128, 128, 128); + ToolBarGradientMiddle = Color.FromArgb(255, 56, 56, 56); + ToolBarGradientBottom = Color.FromArgb(255, 128, 128, 128); + StatusBarGradientTop = Color.FromArgb(255, 128, 128, 128); + StatusBarGradientMiddle = Color.FromArgb(255, 56, 56, 56); + StatusBarGradientBottom = Color.FromArgb(255, 128, 128, 128); + SearchBoxBack = Color.FromArgb(255, 45, 45, 45); + SearchBoxBorder = Color.FromArgb(255, 80, 80, 80); + SearchBoxPlaceholder = Color.FromArgb(255, 150, 150, 150); + ComboBoxBack = Color.FromArgb(255, 45, 45, 48); + ComboBoxFore = Color.FromArgb(255, 245, 245, 245); + ComboBoxBorder = Color.FromArgb(255, 70, 70, 75); + ComboBoxArrow = Color.FromArgb(255, 200, 200, 200); + } + + private static void SetLightModeColors() + { + TitleArea = Color.FromArgb(255, 243, 243, 243); + FormBack = SystemColors.Control; + FormFore = SystemColors.ControlText; + FormBorder = Color.LightGray; + ButtonMain = SystemColors.ControlLightLight; + ButtonSecond = SystemColors.ControlLight; + SideBarBackground = SystemColors.Control; + SideBarSeparator = Color.FromArgb(255, 200, 200, 200); + SideBarHovered = Color.FromArgb(255, 230, 230, 230); + ToolBarGradientTop = Color.FromArgb(255, 255, 255, 255); + ToolBarGradientMiddle = Color.FromArgb(255, 230, 230, 230); + ToolBarGradientBottom = Color.FromArgb(255, 255, 255, 255); + StatusBarGradientTop = Color.FromArgb(255, 255, 255, 255); + StatusBarGradientMiddle = Color.FromArgb(255, 230, 230, 230); + StatusBarGradientBottom = Color.FromArgb(255, 255, 255, 255); + SearchBoxBack = Color.White; + SearchBoxBorder = Color.FromArgb(255, 200, 200, 200); + SearchBoxPlaceholder = Color.FromArgb(255, 120, 120, 120); + ComboBoxBack = Color.FromArgb(255, 250, 250, 252); + ComboBoxFore = Color.FromArgb(255, 25, 25, 25); + ComboBoxBorder = Color.FromArgb(255, 210, 210, 215); + ComboBoxArrow = Color.FromArgb(255, 100, 100, 100); + } + + public static Color GetBorderColor(bool isFocused = false) + { + return isFocused ? MainColor : (IsDarkTheme ? + Color.FromArgb(255, 80, 80, 80) : + Color.FromArgb(255, 200, 200, 200)); + } + + public static Color GetPlaceholderColor() + { + return IsDarkTheme ? + Color.FromArgb(255, 150, 150, 150) : + Color.FromArgb(255, 120, 120, 120); + } + + private static void OnSystemPreferencesChanged(object sender, UserPreferenceChangedEventArgs e) + { + if (e.Category == UserPreferenceCategory.General) + { + if (uiContext != null) + { + uiContext.Post(_ => UpdateTheme(), null); + } + else + { + UpdateTheme(); + } + } + } + + public static void AdjustControlColors(Control control) + { + if (control == null || control.IsDisposed) return; + + if (control.InvokeRequired) + { + try { control.Invoke(new Action(() => AdjustControlColors(control))); } + catch { return; } + return; + } + + if (control.IsDisposed) return; + + foreach (Control child in control.Controls) + AdjustControlColors(child); + + try + { + string typeName = control.GetType().FullName; + + if (typeName == "BluePointLilac.Controls.MyListBox" || + typeName == "BluePointLilac.Controls.MyListItem") + { + control.BackColor = FormBack; + control.ForeColor = FormFore; + } + else if (typeName == "BluePointLilac.Controls.MyToolBar") + { + control.BackColor = TitleArea; + control.ForeColor = FormFore; + } + else if (typeName == "BluePointLilac.Controls.MyToolBarButton") + { + control.ForeColor = FormFore; + } + else if (typeName == "BluePointLilac.Controls.MySideBar") + { + control.BackColor = ButtonSecond; + control.ForeColor = FormFore; + } + else if (typeName == "BluePointLilac.Controls.MyStatusBar") + { + control.BackColor = ButtonMain; + control.ForeColor = FormFore; + } + else if (control is RComboBox combo) + { + if (combo.InvokeRequired) + combo.Invoke(new Action(() => combo.UpdateColors())); + else + combo.UpdateColors(); + } + else if (control is SearchBox searchBox) + { + searchBox.Invoke(new Action(() => + { + var method = searchBox.GetType().GetMethod("UpdateThemeColors"); + method?.Invoke(searchBox, null); + })); + } + } + catch { /* 忽略错误 */ } + } + + public static GraphicsPath CreateRoundedRectanglePath(Rectangle rect, int radius) + { + var path = new GraphicsPath(); + if (radius <= 0) + { + path.AddRectangle(rect); + return path; + } + + int diameter = radius * 2; + var arc = new Rectangle(rect.Location, new Size(diameter, diameter)); + + path.AddArc(arc, 180, 90); + arc.X = rect.Right - diameter; + path.AddArc(arc, 270, 90); + arc.Y = rect.Bottom - diameter; + path.AddArc(arc, 0, 90); + arc.X = rect.Left; + path.AddArc(arc, 90, 90); + + path.CloseFigure(); + return path; + } + + private static void SafeInvokeThemeChanged() + { + try { ThemeChanged?.Invoke(null, EventArgs.Empty); } + catch { /* 忽略异常 */ } + } + } +} \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Controls/DownloadDialog.cs b/ContextMenuManager/BluePointLilac.Controls/DownloadDialog.cs index 8d9272a8..51fdb6e5 100644 --- a/ContextMenuManager/BluePointLilac.Controls/DownloadDialog.cs +++ b/ContextMenuManager/BluePointLilac.Controls/DownloadDialog.cs @@ -16,8 +16,8 @@ public override void Reset() { } protected override bool RunDialog(IntPtr hwndOwner) { - using (Process process = Process.GetCurrentProcess()) - using (DownloadForm frm = new DownloadForm()) + using(Process process = Process.GetCurrentProcess()) + using(DownloadForm frm = new DownloadForm()) { frm.Url = Url; frm.Text = Text; @@ -40,6 +40,9 @@ public DownloadForm() InitializeComponents(); ResumeLayout(); InitTheme(); + + // 监听主题变化 + DarkModeHelper.ThemeChanged += OnThemeChanged; } readonly ProgressBar pgbDownload = new ProgressBar @@ -65,19 +68,35 @@ private void InitializeComponents() btnCancel.Left = pgbDownload.Right + a; ClientSize = new Size(btnCancel.Right + a, btnCancel.Bottom + a); } + + private void InitTheme() + { + BackColor = DarkModeHelper.FormBack; + ForeColor = DarkModeHelper.FormFore; + + btnCancel.BackColor = DarkModeHelper.ButtonMain; + btnCancel.ForeColor = DarkModeHelper.FormFore; + } + + // 主题变化事件处理 + private void OnThemeChanged(object sender, EventArgs e) + { + InitTheme(); + Invalidate(); + } private void DownloadFile(string url, string filePath) { try { - using (UAWebClient client = new UAWebClient()) + using(UAWebClient client = new UAWebClient()) { client.DownloadProgressChanged += (sender, e) => { int value = e.ProgressPercentage; Text = $"Downloading: {value}%"; pgbDownload.Value = value; - if (DialogResult == DialogResult.Cancel) + if(DialogResult == DialogResult.Cancel) { client.CancelAsync(); File.Delete(FilePath); @@ -90,7 +109,7 @@ private void DownloadFile(string url, string filePath) client.DownloadFileAsync(new Uri(url), filePath); } } - catch (Exception e) + catch(Exception e) { MessageBox.Show(e.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); DialogResult = DialogResult.Cancel; @@ -99,8 +118,8 @@ private void DownloadFile(string url, string filePath) protected override void OnLoad(EventArgs e) { - if (Owner == null && Form.ActiveForm != this) Owner = Form.ActiveForm; - if (Owner == null) StartPosition = FormStartPosition.CenterScreen; + if(Owner == null && Form.ActiveForm != this) Owner = Form.ActiveForm; + if(Owner == null) StartPosition = FormStartPosition.CenterScreen; else { TopMost = true; @@ -108,6 +127,15 @@ protected override void OnLoad(EventArgs e) } base.OnLoad(e); } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + DarkModeHelper.ThemeChanged -= OnThemeChanged; + } + base.Dispose(disposing); + } } } } \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Controls/InputDialog.cs b/ContextMenuManager/BluePointLilac.Controls/InputDialog.cs index fe5480c3..1ab666fe 100644 --- a/ContextMenuManager/BluePointLilac.Controls/InputDialog.cs +++ b/ContextMenuManager/BluePointLilac.Controls/InputDialog.cs @@ -17,7 +17,7 @@ public override void Reset() { } protected override bool RunDialog(IntPtr hwndOwner) { - using (InputBox frm = new InputBox()) + using(InputBox frm = new InputBox()) { frm.Text = Title; frm.InputedText = Text; @@ -44,6 +44,9 @@ public InputBox() txtInput.CanResizeFont(); InitializeComponents(); InitTheme(); + + // 监听主题变化 + DarkModeHelper.ThemeChanged += OnThemeChanged; } public string InputedText @@ -91,6 +94,36 @@ private void InitializeComponents() txtInput.Height = btnCancel.Top - 2 * a; }; } + + private void InitTheme() + { + BackColor = DarkModeHelper.FormBack; + ForeColor = DarkModeHelper.FormFore; + + txtInput.BackColor = DarkModeHelper.FormBack; + txtInput.ForeColor = DarkModeHelper.FormFore; + + btnOK.BackColor = DarkModeHelper.ButtonMain; + btnOK.ForeColor = DarkModeHelper.FormFore; + btnCancel.BackColor = DarkModeHelper.ButtonMain; + btnCancel.ForeColor = DarkModeHelper.FormFore; + } + + // 主题变化事件处理 + private void OnThemeChanged(object sender, EventArgs e) + { + InitTheme(); + Invalidate(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + DarkModeHelper.ThemeChanged -= OnThemeChanged; + } + base.Dispose(disposing); + } } } } \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Controls/LoadingDialog.Designer.cs b/ContextMenuManager/BluePointLilac.Controls/LoadingDialog.Designer.cs deleted file mode 100644 index ba691cb1..00000000 --- a/ContextMenuManager/BluePointLilac.Controls/LoadingDialog.Designer.cs +++ /dev/null @@ -1,140 +0,0 @@ -using Microsoft.AspNetCore.Http.HttpResults; -using System; -using System.ComponentModel; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Windows.Forms; - -namespace BluePointLilac.Controls -{ - sealed partial class LoadingDialog - { - /// - /// Required designer variable. - /// - private IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - progressBar = new NewProgressBar(); - panel1 = new Panel(); - panel1.SuspendLayout(); - SuspendLayout(); - // - // progressBar - // - progressBar.Dock = DockStyle.Top; - progressBar.Location = new System.Drawing.Point(10, 12); - progressBar.Margin = new Padding(5, 6, 5, 6); - progressBar.Name = "progressBar"; - progressBar.Size = new System.Drawing.Size(560, 40); - progressBar.Style = ProgressBarStyle.Blocks; - progressBar.TabIndex = 0; - progressBar.Value = 0; - progressBar.Maximum = 100; - progressBar.Minimum = 0; - // - // panel1 - // - panel1.AutoSize = true; - panel1.AutoSizeMode = AutoSizeMode.GrowAndShrink; - panel1.BorderStyle = BorderStyle.FixedSingle; - panel1.Controls.Add(progressBar); - panel1.Location = new System.Drawing.Point(0, 0); - panel1.Margin = new Padding(0); - panel1.MinimumSize = new System.Drawing.Size(582, 19); - panel1.Name = "panel1"; - panel1.Padding = new Padding(10, 12, 10, 12); - panel1.Size = new System.Drawing.Size(582, 66); - panel1.TabIndex = 2; - panel1.Resize += panel1_Resize; - // - // LoadingDialog - // - AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F); - AutoScaleMode = AutoScaleMode.Font; - AutoSizeMode = AutoSizeMode.GrowAndShrink; - BackColor = System.Drawing.SystemColors.Control; - ClientSize = new System.Drawing.Size(581, 64); - ControlBox = false; - Controls.Add(panel1); - FormBorderStyle = FormBorderStyle.None; - Margin = new Padding(5, 6, 5, 6); - MaximizeBox = false; - MinimizeBox = false; - Name = "LoadingDialog"; - ShowIcon = false; - ShowInTaskbar = false; - SizeGripStyle = SizeGripStyle.Hide; - StartPosition = FormStartPosition.CenterParent; - panel1.ResumeLayout(false); - ResumeLayout(false); - PerformLayout(); - - } - - #endregion - private Panel panel1; - private NewProgressBar progressBar; - } - - public class NewProgressBar : ProgressBar - { - private Color foreColor = MyMainForm.MainColor; - private Color backColor = MyMainForm.ButtonMain; - - public NewProgressBar() - { - this.SetStyle(ControlStyles.UserPaint, true); - } - - protected override void OnPaintBackground(PaintEventArgs pevent) - { - // None... Helps control the flicker. - } - protected override void OnPaint(PaintEventArgs e) - { - const int inset = 2; // A single inset value to control teh sizing of the inner rect. - - using (Image offscreenImage = new Bitmap(this.Width, this.Height)) - { - using (Graphics offscreen = Graphics.FromImage(offscreenImage)) - { - Rectangle rect = new Rectangle(0, 0, this.Width, this.Height); - - if (ProgressBarRenderer.IsSupported) - ProgressBarRenderer.DrawHorizontalBar(offscreen, rect); - - rect.Inflate(new Size(-inset, -inset)); // Deflate inner rect. - rect.Width = (int)(rect.Width * ((double)this.Value / this.Maximum)); - if (rect.Width == 0) rect.Width = 1; // Can't draw rec with width of 0. - - /*LinearGradientBrush brush = new LinearGradientBrush(rect, backColor, foreColor, LinearGradientMode.Vertical);*/ - using (SolidBrush brush = new SolidBrush(foreColor)) - offscreen.FillRectangle(brush, inset, inset, rect.Width, rect.Height); - - e.Graphics.DrawImage(offscreenImage, 0, 0); - } - } - } - } -} \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Controls/LoadingDialog.cs b/ContextMenuManager/BluePointLilac.Controls/LoadingDialog.cs index bfa1447d..cef4d4e5 100644 --- a/ContextMenuManager/BluePointLilac.Controls/LoadingDialog.cs +++ b/ContextMenuManager/BluePointLilac.Controls/LoadingDialog.cs @@ -1,413 +1,407 @@ -/* - Copyright (c) 2017 Marcin Szeniak (https://github.com/Klocman/) - Apache License Version 2.0 -*/ - -using System; -using System.ComponentModel; -using System.Drawing; -using System.Threading; -using System.Timers; -using System.Windows.Forms; -using Timer = System.Timers.Timer; - -namespace BluePointLilac.Controls -{ - public sealed partial class LoadingDialog : Form - { - private readonly Thread _workThread; - private readonly LoadingDialogInterface _controller; - private Point _offset; - private ContentAlignment _ownerAlignment; - private bool _startAutomatically; - - internal LoadingDialog(string title, Action action) - { - InitializeComponent(); - - Text = title; - - ForeColor = MyMainForm.FormFore; - BackColor = MyMainForm.FormBack; - - UseWaitCursor = true; - - _controller = new LoadingDialogInterface(this); - - _workThread = new Thread(() => - { - _controller.WaitTillDialogIsReady(); - try - { - action(_controller); - } - catch (Exception ex) - { - Error = ex; - } - - _controller.CloseDialog(); - }) - { Name = "LoadingDialogThread - " + title }; - } - - protected override CreateParams CreateParams - { - get - { - const int csDropshadow = 0x20000; - var cp = base.CreateParams; - cp.ClassStyle |= csDropshadow; - return cp; - } - } - - public static Form DefaultOwner { get; set; } - - public Exception Error { get; private set; } - - internal ProgressBar ProgressBar => progressBar; - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - if (Owner?.Icon != null) - Icon = Owner.Icon; - } - - protected override void OnShown(EventArgs e) - { - base.OnShown(e); - - if (Owner != null) - { - Owner.Move += OwnerOnMove; - Owner.Resize += OwnerOnMove; - - OwnerOnMove(this, e); - } - - if (_startAutomatically) - StartWork(); - } - - protected override void OnClosing(CancelEventArgs e) - { - if (Owner != null) - { - Owner.Move -= OwnerOnMove; - Owner.Resize -= OwnerOnMove; - } - - base.OnClosing(e); - } - - protected override void OnFormClosed(FormClosedEventArgs e) - { - _controller.Abort = true; - base.OnFormClosed(e); - } - - protected override void OnResize(EventArgs e) - { - base.OnResize(e); - - OwnerOnMove(this, e); - } - - private void OwnerOnMove(object sender, EventArgs eventArgs) - { - if (Owner == null) return; - - var newPos = new Point(); - - switch (_ownerAlignment) - { - case ContentAlignment.MiddleLeft: - case ContentAlignment.MiddleCenter: - case ContentAlignment.MiddleRight: - newPos.Y = Owner.Location.Y + Owner.Size.Height / 2 - Size.Height / 2; - break; - - case ContentAlignment.BottomLeft: - case ContentAlignment.BottomCenter: - case ContentAlignment.BottomRight: - newPos.Y = Owner.Location.Y + Owner.Size.Height - Size.Height; - break; - - default: - break; - } - switch (_ownerAlignment) - { - case ContentAlignment.TopCenter: - case ContentAlignment.MiddleCenter: - case ContentAlignment.BottomCenter: - newPos.X = Owner.Location.X + Owner.Size.Width / 2 - Size.Width / 2; - break; - case ContentAlignment.TopRight: - case ContentAlignment.MiddleRight: - case ContentAlignment.BottomRight: - newPos.X = Owner.Location.X + Owner.Size.Width - Size.Width; - break; - - default: - break; - } - - newPos.X += _offset.X; - newPos.Y += _offset.Y; - Location = newPos; - } - - /// - /// Start the action on a separate thread and show a progress bar. When action completes the dialog is closed. - /// - /// Parent form - /// Title of the window - /// Action to perform while displaying the dialog - /// Offset from the alignment point - /// Alignment point to the parent - public static LoadingDialog Show(Form owner, string title, Action action, - Point offset = default(Point), ContentAlignment ownerAlignment = ContentAlignment.MiddleCenter) - { - if (owner == null) owner = DefaultOwner; - // Find the topmost form so clicking on forms above owner doesn't bring the loading form under the others - while (owner != null && owner.OwnedForms.Length > 0) owner = owner.OwnedForms[0]; - - var loadBar = new LoadingDialog(title, action) - { - _offset = offset, - _ownerAlignment = ownerAlignment, - Owner = owner, - StartPosition = FormStartPosition.Manual, - _startAutomatically = false, - }; - - loadBar.Show(loadBar.Owner); - return loadBar; - } - - /// - /// Start the action on a separate thread and show a progress bar. - /// - /// Parent form - /// Title of the window - /// Action to perform while displaying the dialog - /// Offset from the alignment point - /// Alignment point to the parent - public static Exception ShowDialog(Form owner, string title, Action action, - Point offset = default(Point), ContentAlignment ownerAlignment = ContentAlignment.MiddleCenter) - { - using (var loadBar = new LoadingDialog(title, action) - { - _offset = offset, - _ownerAlignment = ownerAlignment, - Owner = owner ?? DefaultOwner, - StartPosition = FormStartPosition.Manual, - _startAutomatically = true - }) - { - loadBar.ShowDialog(loadBar.Owner); - return loadBar.Error; - } - } - - public void StartWork() - { - _workThread.Start(); - } - - private void panel1_Resize(object sender, EventArgs e) - { - Size = panel1.Size; - } - } - - public sealed class LoadingDialogInterface - { - private readonly Timer _updateTimer; - - private Action _lastProgressUpdate; - private Action _lastSubProgressUpdate; - - internal LoadingDialogInterface(LoadingDialog dialog) - { - Dialog = dialog; - _updateTimer = new Timer - { - AutoReset = true, - Interval = 35, - SynchronizingObject = Dialog - }; - _updateTimer.Elapsed += UpdateTimerOnElapsed; - _updateTimer.Start(); - dialog.Disposed += (sender, args) => _updateTimer.Dispose(); - } - - private void UpdateTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs) - { - var p = Interlocked.Exchange(ref _lastProgressUpdate, null); - p?.Invoke(); - p = Interlocked.Exchange(ref _lastSubProgressUpdate, null); - p?.Invoke(); - } - - public bool Abort { get; internal set; } - - private LoadingDialog Dialog { get; } - - public void CloseDialog() - { - _updateTimer.Dispose(); - SafeInvoke(() => { if (!Dialog.IsDisposed) Dialog.Close(); }); - } - - public void SetMaximum(int value) - { - SetMaximumInt(value, Dialog.ProgressBar); - } - - private void SetMaximumInt(int value, ProgressBar targetBar) - { - SafeInvoke(() => - { - if (targetBar.Maximum == value) return; - - if (value < targetBar.Minimum) - targetBar.Style = ProgressBarStyle.Marquee; - else - { - try - { - targetBar.Maximum = value; - } - catch - { - targetBar.Style = ProgressBarStyle.Marquee; - } - } - }); - } - - public void SetMinimum(int value) - { - SetMinimumInt(value, Dialog.ProgressBar); - } - - private void SetMinimumInt(int value, ProgressBar targetBar) - { - SafeInvoke(() => - { - try - { - targetBar.Minimum = value; - } - catch - { - targetBar.Style = ProgressBarStyle.Marquee; - } - }); - } - - /// - /// Setting progress automatically changes the style from "Unknown time" (Marquee) to a normal progressbar. - /// If the value is invalid the style goes back to Marquee - /// - public void SetProgress(int value, string description = null, bool forceNoAnimation = false) - { - _lastProgressUpdate = () => SetProgressInt(value, description, Dialog.ProgressBar, forceNoAnimation); - } - - private void SetProgressInt(int value, string description, ProgressBar targetBar, bool forceNoAnimation) - { - try - { - if (targetBar.Value == value) - return; - - var min = targetBar.Minimum; - var max = targetBar.Maximum; - if (min >= max || min > value || value > max) - { - targetBar.Style = ProgressBarStyle.Marquee; - } - else - { - targetBar.Style = ProgressBarStyle.Blocks; - - if (value < min) value = min; - else if (value > max) value = max; - - if (forceNoAnimation) - { - // Moving progress forward then back skips the animation - if (value == max) - { - targetBar.Maximum = value + 1; - targetBar.Value = value + 1; - targetBar.Maximum = value; - } - else - { - targetBar.Value = value + 1; - } - } - - targetBar.Value = value; - } - } - catch - { - targetBar.Style = ProgressBarStyle.Marquee; - } - } - - public void SetTitle(string newTitle) - { - SafeInvoke(() => { Dialog.Text = newTitle; }); - } - - /// - /// Block current thread until dialog is visible - /// - internal void WaitTillDialogIsReady() - { - var notReady = true; - while (notReady) - { - SafeInvoke(() => notReady = !Dialog.Visible); - Thread.Sleep(10); - } - } - - private void SafeInvoke(Action action) - { - Control obj = Dialog; - - if (action == null) - throw new ArgumentNullException(nameof(action)); - if (obj == null) - throw new ArgumentNullException(nameof(obj)); - - if (!obj.IsDisposed && !obj.Disposing) - { - if (obj.InvokeRequired) - { - try - { - obj.Invoke(action); - } - catch (ObjectDisposedException) { } - catch (InvalidOperationException) { } - catch (InvalidAsynchronousStateException) { } - } - else - { - action(); - } - } - } - } +/* + Copyright (c) 2017 Marcin Szeniak (https://github.com/Klocman/) + Apache License Version 2.0 +*/ + +using System; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Threading; +using System.Timers; +using System.Windows.Forms; +using Timer = System.Timers.Timer; + +namespace BluePointLilac.Controls +{ + public sealed partial class LoadingDialog : Form + { + private readonly Thread _workThread; + private readonly LoadingDialogInterface _controller; + private Point _offset; + private ContentAlignment _ownerAlignment; + private bool _startAutomatically; + private NewProgressBar progressBar; + private Panel panel1; + + internal LoadingDialog(string title, Action action) + { + InitializeComponent(); + Text = title; + ForeColor = DarkModeHelper.FormFore; + BackColor = DarkModeHelper.FormBack; + UseWaitCursor = true; + + _controller = new LoadingDialogInterface(this); + _workThread = new Thread(() => ExecuteAction(action)) { Name = "LoadingDialogThread - " + title }; + + DarkModeHelper.ThemeChanged += OnThemeChanged; + } + + protected override CreateParams CreateParams + { + get + { + var cp = base.CreateParams; + cp.ClassStyle |= 0x20000; // csDropshadow + return cp; + } + } + + public static Form DefaultOwner { get; set; } + public Exception Error { get; private set; } + internal ProgressBar ProgressBar => progressBar; + + protected override void OnShown(EventArgs e) + { + base.OnShown(e); + if (Owner != null) + { + Owner.Move += OwnerOnMove; + Owner.Resize += OwnerOnMove; + OwnerOnMove(this, e); + } + if (_startAutomatically) StartWork(); + } + + protected override void OnClosing(CancelEventArgs e) + { + if (Owner != null) + { + Owner.Move -= OwnerOnMove; + Owner.Resize -= OwnerOnMove; + } + base.OnClosing(e); + } + + protected override void OnFormClosed(FormClosedEventArgs e) + { + _controller.Abort = true; + base.OnFormClosed(e); + } + + private void OwnerOnMove(object sender, EventArgs e) + { + if (Owner == null) return; + var newPos = CalculatePosition(); + newPos.X += _offset.X; + newPos.Y += _offset.Y; + Location = newPos; + } + + private Point CalculatePosition() + { + var pos = Point.Empty; + var ownerAlignment = _ownerAlignment.ToString(); + + if (ownerAlignment.Contains("Middle")) + pos.Y = Owner.Location.Y + Owner.Size.Height / 2 - Size.Height / 2; + else if (ownerAlignment.Contains("Bottom")) + pos.Y = Owner.Location.Y + Owner.Size.Height - Size.Height; + + if (ownerAlignment.Contains("Center")) + pos.X = Owner.Location.X + Owner.Size.Width / 2 - Size.Width / 2; + else if (ownerAlignment.Contains("Right")) + pos.X = Owner.Location.X + Owner.Size.Width - Size.Width; + + return pos; + } + + public static LoadingDialog Show(Form owner, string title, Action action, + Point offset = default, ContentAlignment ownerAlignment = ContentAlignment.MiddleCenter) + { + owner = GetTopmostOwner(owner); + var loadBar = CreateLoadingDialog(owner, title, action, offset, ownerAlignment); + loadBar.Show(loadBar.Owner); + return loadBar; + } + + public static Exception ShowDialog(Form owner, string title, Action action, + Point offset = default, ContentAlignment ownerAlignment = ContentAlignment.MiddleCenter) + { + using (var loadBar = CreateLoadingDialog(owner, title, action, offset, ownerAlignment)) + { + loadBar._startAutomatically = true; + loadBar.ShowDialog(loadBar.Owner); + return loadBar.Error; + } + } + + private static LoadingDialog CreateLoadingDialog(Form owner, string title, + Action action, Point offset, ContentAlignment alignment) + { + return new LoadingDialog(title, action) + { + _offset = offset, + _ownerAlignment = alignment, + Owner = owner, + StartPosition = FormStartPosition.Manual + }; + } + + private static Form GetTopmostOwner(Form owner) + { + if (owner == null) owner = DefaultOwner; + while (owner != null && owner.OwnedForms.Length > 0) + owner = owner.OwnedForms[0]; + return owner; + } + + public void StartWork() => _workThread.Start(); + private void panel1_Resize(object sender, EventArgs e) => Size = panel1.Size; + + private void ExecuteAction(Action action) + { + _controller.WaitTillDialogIsReady(); + try { action(_controller); } + catch (Exception ex) { Error = ex; } + _controller.CloseDialog(); + } + + private void OnThemeChanged(object sender, EventArgs e) + { + if (IsDisposed || Disposing) return; + ForeColor = DarkModeHelper.FormFore; + BackColor = DarkModeHelper.FormBack; + panel1.BackColor = DarkModeHelper.FormBack; + Invalidate(); + } + + private void InitializeComponent() + { + progressBar = new NewProgressBar(); + panel1 = new Panel(); + panel1.SuspendLayout(); + SuspendLayout(); + + progressBar.Location = new Point(8, 10); + progressBar.Size = new Size(391, 25); + progressBar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + + panel1.AutoSize = true; + panel1.AutoSizeMode = AutoSizeMode.GrowAndShrink; + panel1.BorderStyle = BorderStyle.FixedSingle; + panel1.Controls.Add(progressBar); + panel1.Dock = DockStyle.Fill; + panel1.MinimumSize = new Size(408, 45); + panel1.Padding = new Padding(8, 10, 8, 10); + panel1.Size = new Size(408, 45); + panel1.Resize += panel1_Resize; + + AutoScaleDimensions = new SizeF(7F, 17F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(408, 45); + Controls.Add(panel1); + FormBorderStyle = FormBorderStyle.None; + ShowInTaskbar = false; + StartPosition = FormStartPosition.CenterParent; + + panel1.ResumeLayout(false); + ResumeLayout(false); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + DarkModeHelper.ThemeChanged -= OnThemeChanged; + progressBar?.Dispose(); + panel1?.Dispose(); + } + base.Dispose(disposing); + } + } + + public sealed class LoadingDialogInterface + { + private readonly Timer _updateTimer = new Timer { Interval = 35 }; + private Action _lastProgressUpdate; + + internal LoadingDialogInterface(LoadingDialog dialog) + { + Dialog = dialog; + _updateTimer.SynchronizingObject = Dialog; + _updateTimer.Elapsed += (s, e) => + Interlocked.Exchange(ref _lastProgressUpdate, null)?.Invoke(); + _updateTimer.Start(); + dialog.Disposed += (s, e) => _updateTimer.Dispose(); + } + + public bool Abort { get; internal set; } + private LoadingDialog Dialog { get; } + + public void CloseDialog() + { + _updateTimer.Dispose(); + SafeInvoke(() => { if (!Dialog.IsDisposed) Dialog.Close(); }); + } + + public void SetMaximum(int value) => SafeInvoke(() => UpdateProgressBar(pb => pb.Maximum = value)); + public void SetMinimum(int value) => SafeInvoke(() => UpdateProgressBar(pb => pb.Minimum = value)); + + public void SetProgress(int value, string description = null, bool forceNoAnimation = false) + { + _lastProgressUpdate = () => UpdateProgressBar(pb => ApplyProgressValue(pb, value, forceNoAnimation)); + } + + public void SetTitle(string newTitle) => SafeInvoke(() => Dialog.Text = newTitle); + + internal void WaitTillDialogIsReady() + { + var notReady = true; + while (notReady) + { + SafeInvoke(() => notReady = !Dialog.Visible); + Thread.Sleep(10); + } + } + + private void ApplyProgressValue(ProgressBar pb, int value, bool forceNoAnimation) + { + try + { + if (pb.Value == value) return; + if (value < pb.Minimum || value > pb.Maximum) + pb.Style = ProgressBarStyle.Marquee; + else + { + pb.Style = ProgressBarStyle.Blocks; + if (forceNoAnimation && value < pb.Maximum) + pb.Value = value + 1; + pb.Value = value; + } + } + catch { pb.Style = ProgressBarStyle.Marquee; } + } + + private void UpdateProgressBar(Action action) + { + var pb = Dialog.ProgressBar; + if (pb != null && !pb.IsDisposed) action(pb); + } + + private void SafeInvoke(Action action) + { + if (Dialog.IsDisposed || Dialog.Disposing) return; + if (Dialog.InvokeRequired) + { + try { Dialog.Invoke(action); } + catch { /* 忽略调用异常 */ } + } + else action(); + } + } + + public class NewProgressBar : ProgressBar + { + public NewProgressBar() + { + SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | + ControlStyles.OptimizedDoubleBuffer, true); + + DarkModeHelper.ThemeChanged += OnThemeChanged; + } + + protected override void OnPaintBackground(PaintEventArgs pevent) + { + using (var brush = new SolidBrush(DarkModeHelper.FormBack)) + pevent.Graphics.FillRectangle(brush, pevent.ClipRectangle); + } + + protected override void OnPaint(PaintEventArgs e) + { + const int inset = 1; + const int cornerRadius = 6; + e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; + e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; + + using (var bgClearBrush = new SolidBrush(DarkModeHelper.FormBack)) + e.Graphics.FillRectangle(bgClearBrush, ClientRectangle); + + Rectangle rect = new Rectangle(0, 0, Width, Height); + + using (GraphicsPath bgPath = CreateRoundedRectanglePath(rect, cornerRadius)) + { + Color bgColor1, bgColor2, bgColor3; + + if (DarkModeHelper.IsDarkTheme) + { + bgColor1 = Color.FromArgb(80, 80, 80); + bgColor2 = Color.FromArgb(60, 60, 60); + bgColor3 = Color.FromArgb(80, 80, 80); + } + else + { + bgColor1 = Color.FromArgb(220, 220, 220); + bgColor2 = Color.FromArgb(180, 180, 180); + bgColor3 = Color.FromArgb(220, 220, 220); + } + + using (LinearGradientBrush bgBrush = new LinearGradientBrush( + new Point(0, rect.Top), new Point(0, rect.Bottom), bgColor1, bgColor3)) + { + bgBrush.InterpolationColors = new ColorBlend + { + Colors = new[] { bgColor1, bgColor2, bgColor3 }, + Positions = new[] { 0f, 0.5f, 1f } + }; + e.Graphics.FillPath(bgBrush, bgPath); + } + } + + int progressWidth = (int)((Width - 2 * inset) * ((double)Value / Maximum)); + + if (progressWidth > 0) + { + Rectangle progressRect = new Rectangle(inset, inset, progressWidth, Height - 2 * inset); + if (progressWidth < cornerRadius * 2) + progressRect.Width = Math.Max(progressWidth, cornerRadius); + + Color fgColor1 = Color.FromArgb(255, 195, 0); + Color fgColor2 = Color.FromArgb(255, 140, 26); + Color fgColor3 = Color.FromArgb(255, 195, 0); + + using (LinearGradientBrush fgBrush = new LinearGradientBrush( + new Point(0, progressRect.Top), new Point(0, progressRect.Bottom), fgColor1, fgColor3)) + { + fgBrush.InterpolationColors = new ColorBlend + { + Colors = new[] { fgColor1, fgColor2, fgColor3 }, + Positions = new[] { 0f, 0.5f, 1f } + }; + + using (GraphicsPath progressPath = CreateRoundedRectanglePath(progressRect, cornerRadius - 1)) + e.Graphics.FillPath(fgBrush, progressPath); + } + } + } + + private GraphicsPath CreateRoundedRectanglePath(Rectangle rect, int radius) + { + var path = new GraphicsPath(); + if (radius <= 0) + { + path.AddRectangle(rect); + return path; + } + + radius = Math.Min(radius, Math.Min(rect.Width, rect.Height) / 2); + int diameter = radius * 2; + + path.AddArc(rect.X, rect.Y, diameter, diameter, 180, 90); + path.AddArc(rect.Right - diameter, rect.Y, diameter, diameter, 270, 90); + path.AddArc(rect.Right - diameter, rect.Bottom - diameter, diameter, diameter, 0, 90); + path.AddArc(rect.X, rect.Bottom - diameter, diameter, diameter, 90, 90); + path.CloseFigure(); + return path; + } + + private void OnThemeChanged(object sender, EventArgs e) => Invalidate(); + + protected override void Dispose(bool disposing) + { + if (disposing) DarkModeHelper.ThemeChanged -= OnThemeChanged; + base.Dispose(disposing); + } + } } \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Controls/LoadingDialog.resx b/ContextMenuManager/BluePointLilac.Controls/LoadingDialog.resx deleted file mode 100644 index 6392ed1a..00000000 --- a/ContextMenuManager/BluePointLilac.Controls/LoadingDialog.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Controls/MyCheckBox.cs b/ContextMenuManager/BluePointLilac.Controls/MyCheckBox.cs index 895cc84e..e777a449 100644 --- a/ContextMenuManager/BluePointLilac.Controls/MyCheckBox.cs +++ b/ContextMenuManager/BluePointLilac.Controls/MyCheckBox.cs @@ -10,7 +10,7 @@ namespace BluePointLilac.Controls [DefaultProperty("Checked")] public class MyCheckBox : Control { - private Timer animationTimer; + private Timer animationTimer = new Timer { Interval = 16 }; private double animationProgress = 0; private bool isAnimating = false; private bool targetCheckedState; @@ -20,10 +20,10 @@ public class MyCheckBox : Control public MyCheckBox() { - this.SetStyle(ControlStyles.AllPaintingInWmPaint | - ControlStyles.UserPaint | - ControlStyles.OptimizedDoubleBuffer | - ControlStyles.ResizeRedraw, true); + SetStyle(ControlStyles.AllPaintingInWmPaint | + ControlStyles.UserPaint | + ControlStyles.OptimizedDoubleBuffer | + ControlStyles.ResizeRedraw, true); HeightPx = 40.DpiZoom(); WidthPx = 80.DpiZoom(); @@ -31,12 +31,11 @@ public MyCheckBox() PaddingPx = 4.DpiZoom(); ButtonSizePx = HeightPx - PaddingPx * 2; - this.Size = new Size(WidthPx, HeightPx); + Size = new Size(WidthPx, HeightPx); Cursor = Cursors.Hand; - - animationTimer = new Timer(); - animationTimer.Interval = 16; + animationTimer.Tick += AnimationTimer_Tick; + DarkModeHelper.ThemeChanged += OnThemeChanged; } private bool? _Checked = null; @@ -46,6 +45,7 @@ public bool Checked set { if (_Checked == value) return; + if (_Checked == null) { _Checked = value; @@ -53,12 +53,14 @@ public bool Checked Invalidate(); return; } + if (PreCheckChanging != null && !PreCheckChanging.Invoke()) return; CheckChanging?.Invoke(); if (PreCheckChanged != null && !PreCheckChanged.Invoke()) return; targetCheckedState = value; - if (isAnimating) animationProgress = 1 - animationProgress; + if (isAnimating) + animationProgress = 1 - animationProgress; else { animationProgress = 0; @@ -81,7 +83,7 @@ protected override void OnMouseDown(MouseEventArgs e) private void AnimationTimer_Tick(object sender, EventArgs e) { - if (this.IsDisposed || !this.Visible) + if (IsDisposed || !Visible) { animationTimer.Stop(); isAnimating = false; @@ -112,87 +114,116 @@ private void AnimationTimer_Tick(object sender, EventArgs e) protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); - if (this.IsDisposed) return; + if (IsDisposed) return; try { Graphics g = e.Graphics; g.SmoothingMode = SmoothingMode.AntiAlias; double easedProgress = EaseInOutCubic(animationProgress); - bool visualState = isAnimating ? (animationProgress > 0.5 ? targetCheckedState : currentCheckedState) : currentCheckedState; + bool visualState = isAnimating ? + (animationProgress > 0.5 ? targetCheckedState : currentCheckedState) : + currentCheckedState; - using (var bgPath = CreateRoundedRect(0, 0, WidthPx, HeightPx, RadiusPx)) - { - Color topColor, middleColor, bottomColor; - if (visualState) - { - topColor = Color.FromArgb(255, 195, 0); - middleColor = Color.FromArgb(255, 141, 26); - bottomColor = Color.FromArgb(255, 195, 0); - } - else - { - topColor = Color.FromArgb(200, 200, 200); - middleColor = Color.FromArgb(150, 150, 150); - bottomColor = Color.FromArgb(200, 200, 200); - } + DrawBackground(g, visualState, easedProgress); + DrawButton(g, easedProgress); + } + catch { /* 忽略绘制异常 */ } + } - if (isAnimating) - { - Color targetTopColor = targetCheckedState ? Color.FromArgb(255, 195, 0) : Color.FromArgb(200, 200, 200); - Color targetMiddleColor = targetCheckedState ? Color.FromArgb(255, 141, 26) : Color.FromArgb(150, 150, 150); - Color targetBottomColor = targetCheckedState ? Color.FromArgb(255, 195, 0) : Color.FromArgb(200, 200, 200); + private void DrawBackground(Graphics g, bool visualState, double easedProgress) + { + using (var bgPath = CreateRoundedRect(0, 0, WidthPx, HeightPx, RadiusPx)) + { + Color topColor, middleColor, bottomColor; + + if (visualState) + { + topColor = Color.FromArgb(255, 195, 0); + middleColor = Color.FromArgb(255, 141, 26); + bottomColor = Color.FromArgb(255, 195, 0); + } + else + { + topColor = Color.FromArgb(200, 200, 200); + middleColor = Color.FromArgb(150, 150, 150); + bottomColor = Color.FromArgb(200, 200, 200); + } - topColor = InterpolateColor(topColor, targetTopColor, easedProgress); - middleColor = InterpolateColor(middleColor, targetMiddleColor, easedProgress); - bottomColor = InterpolateColor(bottomColor, targetBottomColor, easedProgress); - } + if (isAnimating) + { + var targetColors = GetTargetColors(targetCheckedState); + topColor = InterpolateColor(topColor, targetColors.Top, easedProgress); + middleColor = InterpolateColor(middleColor, targetColors.Middle, easedProgress); + bottomColor = InterpolateColor(bottomColor, targetColors.Bottom, easedProgress); + } - using (var bgBrush = new LinearGradientBrush(new Rectangle(0, 0, WidthPx, HeightPx), Color.Empty, Color.Empty, 90f)) + using (var bgBrush = new LinearGradientBrush(new Rectangle(0, 0, WidthPx, HeightPx), + Color.Empty, Color.Empty, 90f)) + { + bgBrush.InterpolationColors = new ColorBlend { - var colorBlend = new ColorBlend(3); - colorBlend.Colors = new Color[] { topColor, middleColor, bottomColor }; - colorBlend.Positions = new float[] { 0f, 0.5f, 1f }; - bgBrush.InterpolationColors = colorBlend; - g.FillPath(bgBrush, bgPath); - } + Colors = new[] { topColor, middleColor, bottomColor }, + Positions = new[] { 0f, 0.5f, 1f } + }; + g.FillPath(bgBrush, bgPath); } + } + } - int startX = currentCheckedState ? (WidthPx - HeightPx + PaddingPx) : PaddingPx; - int endX = targetCheckedState ? (WidthPx - HeightPx + PaddingPx) : PaddingPx; - int buttonX = (int)(startX + (endX - startX) * easedProgress); - int buttonY = PaddingPx; + private void DrawButton(Graphics g, double easedProgress) + { + int startX = currentCheckedState ? (WidthPx - HeightPx + PaddingPx) : PaddingPx; + int endX = targetCheckedState ? (WidthPx - HeightPx + PaddingPx) : PaddingPx; + int buttonX = (int)(startX + (endX - startX) * easedProgress); + int buttonY = PaddingPx; - for (int i = 3; i > 0; i--) + for (int i = 3; i > 0; i--) + { + int shadowSize = i * 2; + int shadowOffset = i; + using (var shadowPath = CreateRoundedRect( + buttonX - shadowSize / 2 + shadowOffset / 2, + buttonY - shadowSize / 2 + shadowOffset, + ButtonSizePx + shadowSize, + ButtonSizePx + shadowSize, + (ButtonSizePx + shadowSize) / 2)) + using (var shadowBrush = new SolidBrush(Color.FromArgb(20 / i, 0, 0, 0))) { - int shadowSize = i * 2; - int shadowOffset = i; - using (var shadowPath = CreateRoundedRect(buttonX - shadowSize / 2 + shadowOffset / 2, buttonY - shadowSize / 2 + shadowOffset, ButtonSizePx + shadowSize, ButtonSizePx + shadowSize, (ButtonSizePx + shadowSize) / 2)) - using (var shadowBrush = new SolidBrush(Color.FromArgb(20 / i, 0, 0, 0))) - g.FillPath(shadowBrush, shadowPath); + g.FillPath(shadowBrush, shadowPath); } + } - using (var buttonPath = CreateRoundedRect(buttonX, buttonY, ButtonSizePx, ButtonSizePx, ButtonSizePx / 2)) - using (var buttonBrush = new SolidBrush(Color.White)) - g.FillPath(buttonBrush, buttonPath); + using (var buttonPath = CreateRoundedRect(buttonX, buttonY, ButtonSizePx, ButtonSizePx, ButtonSizePx / 2)) + using (var buttonBrush = new SolidBrush(Color.White)) + { + g.FillPath(buttonBrush, buttonPath); + } - using (var highlightPath = CreateRoundedRect(buttonX + 2, buttonY + 2, ButtonSizePx / 2, ButtonSizePx / 2, ButtonSizePx / 4)) - using (var highlightBrush = new SolidBrush(Color.FromArgb(100, 255, 255, 255))) - g.FillPath(highlightBrush, highlightPath); + using (var highlightPath = CreateRoundedRect(buttonX + 2, buttonY + 2, ButtonSizePx / 2, ButtonSizePx / 2, ButtonSizePx / 4)) + using (var highlightBrush = new SolidBrush(Color.FromArgb(100, 255, 255, 255))) + { + g.FillPath(highlightBrush, highlightPath); } - catch { } } - private static double EaseInOutCubic(double t) => t < 0.5 ? 4 * t * t * t : 1 - Math.Pow(-2 * t + 2, 3) / 2; - - private static Color InterpolateColor(Color start, Color end, double progress) + private (Color Top, Color Middle, Color Bottom) GetTargetColors(bool targetState) { - int r = (int)(start.R + (end.R - start.R) * progress); - int g = (int)(start.G + (end.G - start.G) * progress); - int b = (int)(start.B + (end.B - start.B) * progress); - return Color.FromArgb(r, g, b); + if (targetState) + return (Color.FromArgb(255, 195, 0), Color.FromArgb(255, 141, 26), Color.FromArgb(255, 195, 0)); + else + return (Color.FromArgb(200, 200, 200), Color.FromArgb(150, 150, 150), Color.FromArgb(200, 200, 200)); } + private static double EaseInOutCubic(double t) => + t < 0.5 ? 4 * t * t * t : 1 - Math.Pow(-2 * t + 2, 3) / 2; + + private static Color InterpolateColor(Color start, Color end, double progress) => + Color.FromArgb( + (int)(start.R + (end.R - start.R) * progress), + (int)(start.G + (end.G - start.G) * progress), + (int)(start.B + (end.B - start.B) * progress)); + private static GraphicsPath CreateRoundedRect(float x, float y, float width, float height, float radius) { var path = new GraphicsPath(); @@ -204,13 +235,15 @@ private static GraphicsPath CreateRoundedRect(float x, float y, float width, flo return path; } + private void OnThemeChanged(object sender, EventArgs e) => Invalidate(); + protected override void Dispose(bool disposing) { - if (disposing && animationTimer != null) + if (disposing) { - animationTimer.Stop(); - animationTimer.Dispose(); - animationTimer = null; + DarkModeHelper.ThemeChanged -= OnThemeChanged; + animationTimer?.Stop(); + animationTimer?.Dispose(); } base.Dispose(disposing); } diff --git a/ContextMenuManager/BluePointLilac.Controls/MyListBox.cs b/ContextMenuManager/BluePointLilac.Controls/MyListBox.cs index ea85d66e..0c172080 100644 --- a/ContextMenuManager/BluePointLilac.Controls/MyListBox.cs +++ b/ContextMenuManager/BluePointLilac.Controls/MyListBox.cs @@ -1,719 +1,416 @@ -using BluePointLilac.Methods; -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Windows.Forms; - -namespace BluePointLilac.Controls -{ - public class MyListBox : Panel - { - public MyListBox() - { - AutoScroll = true; - BackColor = MyMainForm.FormBack; - ForeColor = MyMainForm.FormFore; - } - - protected override void OnMouseWheel(MouseEventArgs e) - { - //使滚动幅度与MyListItem的高度相配合,防止滚动过快导致来不及重绘界面变花 - base.OnMouseWheel(new MouseEventArgs(e.Button, e.Clicks, e.X, e.Y, Math.Sign(e.Delta) * 50.DpiZoom())); - } - - // 搜索功能 - public virtual void SearchItems(string searchText) - { - if (string.IsNullOrWhiteSpace(searchText)) - { - // 清空搜索,显示所有项 - foreach (Control control in Controls) - { - if (control is MyList list) - { - foreach (Control item in list.Controls) - { - if (item is MyListItem listItem && !listItem.IsDisposed) - { - listItem.Visible = true; - listItem.HighlightText = null; - } - } - } - } - return; - } - - // 搜索所有列表项 - foreach (Control control in Controls) - { - if (control is MyList list) - { - foreach (Control item in list.Controls) - { - if (item is MyListItem listItem && !listItem.IsDisposed) - { - bool matches = listItem.Text.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0; - listItem.Visible = matches; - if (matches) - { - listItem.HighlightText = searchText; - } - else - { - listItem.HighlightText = null; - } - } - } - } - } - } - - // 获取所有可见的列表项 - public virtual IEnumerable GetAllItems() - { - foreach (Control control in Controls) - { - if (control is MyList list) - { - foreach (Control item in list.Controls) - { - if (item is MyListItem listItem && !listItem.IsDisposed) - { - yield return listItem; - } - } - } - } - } - - // 清除搜索高亮 - public virtual void ClearSearchHighlight() - { - foreach (var item in GetAllItems()) - { - if (!item.IsDisposed) - { - item.HighlightText = null; - } - } - } - } - - public class MyList : FlowLayoutPanel - { - public MyListBox Owner - { - get => (MyListBox)Parent; - set => Parent = value; - } - - public MyList(MyListBox owner) : this() - { - Owner = owner; - } - - public MyList() - { - AutoSize = true; - WrapContents = true; - Dock = DockStyle.Top; - DoubleBuffered = true; - AutoSizeMode = AutoSizeMode.GrowAndShrink; - } - - // 恢复悬停项相关代码 - private MyListItem hoveredItem; - public MyListItem HoveredItem - { - get => hoveredItem; - set - { - if (hoveredItem == value) return; - - // 移除旧悬停效果 - 检查是否已释放 - if (hoveredItem != null && !hoveredItem.IsDisposed) - { - hoveredItem.ForeColor = MyMainForm.FormFore; - hoveredItem.Font = new Font(hoveredItem.Font, FontStyle.Regular); - } - - hoveredItem = value; - - // 应用新悬停效果 - 检查是否已释放 - if (hoveredItem != null && !hoveredItem.IsDisposed) - { - hoveredItem.ForeColor = MyMainForm.MainColor; - hoveredItem.Font = new Font(hoveredItem.Font, FontStyle.Bold); - hoveredItem.Focus(); - } - - HoveredItemChanged?.Invoke(this, null); - } - } - - public event EventHandler HoveredItemChanged; - - public void AddItem(MyListItem item) - { - if (item == null || item.IsDisposed) return; - - SuspendLayout(); - item.Parent = this; - - // 恢复悬停事件 - 添加释放检查 - item.MouseEnter += (sender, e) => - { - if (!item.IsDisposed) - HoveredItem = item; - }; - - // 添加鼠标离开事件,清除悬停 - item.MouseLeave += (sender, e) => - { - if (HoveredItem == item && !item.IsDisposed) - HoveredItem = null; - }; - - MouseWheel += (sender, e) => - { - if (!item.IsDisposed) - item.ContextMenuStrip?.Close(); - }; - - void ResizeItem() - { - if (!item.IsDisposed) - item.Width = Owner.Width - item.Margin.Horizontal; - } - - Owner.Resize += (sender, e) => ResizeItem(); - ResizeItem(); - ResumeLayout(); - } - - public void AddItems(MyListItem[] items) - { - if (items == null) return; - Array.ForEach(items, item => - { - if (!item.IsDisposed) - AddItem(item); - }); - } - - public void AddItems(List items) - { - if (items == null) return; - items.ForEach(item => - { - if (!item.IsDisposed) - AddItem(item); - }); - } - - public void SetItemIndex(MyListItem item, int newIndex) - { - if (item == null || item.IsDisposed) return; - Controls.SetChildIndex(item, newIndex); - } - - public int GetItemIndex(MyListItem item) - { - if (item == null || item.IsDisposed) return -1; - return Controls.GetChildIndex(item); - } - - public void InsertItem(MyListItem item, int index) - { - if (item == null || item.IsDisposed) return; - AddItem(item); - SetItemIndex(item, index); - } - - public virtual void ClearItems() - { - if (Controls.Count == 0) return; - - // 清除悬停项引用 - HoveredItem = null; - - SuspendLayout(); - for (int i = Controls.Count - 1; i >= 0; i--) - { - Control ctr = Controls[i]; - Controls.Remove(ctr); - if (!ctr.IsDisposed) - ctr.Dispose(); - } - ResumeLayout(); - } - - public void SortItemByText() - { - List items = new List(); - foreach (MyListItem item in Controls) - { - if (!item.IsDisposed) - items.Add(item); - } - Controls.Clear(); - items.Sort(new TextComparer()); - items.ForEach(item => - { - if (!item.IsDisposed) - AddItem(item); - }); - } - - public class TextComparer : IComparer - { - public int Compare(MyListItem x, MyListItem y) - { - if (x == null || y == null) return 0; - if (x.Equals(y)) return 0; - string[] strs = { x.Text, y.Text }; - Array.Sort(strs); - if (strs[0] == x.Text) return -1; - else return 1; - } - } - - // 搜索功能 - public virtual void SearchItems(string searchText) - { - if (string.IsNullOrWhiteSpace(searchText)) - { - // 清空搜索,显示所有项 - foreach (Control control in Controls) - { - if (control is MyListItem item && !item.IsDisposed) - { - item.Visible = true; - item.HighlightText = null; - } - } - return; - } - - // 搜索所有列表项 - foreach (Control control in Controls) - { - if (control is MyListItem item && !item.IsDisposed) - { - bool matches = item.Text.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0; - item.Visible = matches; - if (matches) - { - item.HighlightText = searchText; - } - else - { - item.HighlightText = null; - } - } - } - } - - // 获取所有列表项 - public virtual IEnumerable GetAllItems() - { - foreach (Control control in Controls) - { - if (control is MyListItem item && !item.IsDisposed) - { - yield return item; - } - } - } - } - - public class MyListItem : Panel - { - private string highlightText; - private string displayText; - private readonly RichTextBox rtbText; - - public MyListItem() - { - SuspendLayout(); - DoubleBuffered = true; - Height = 50.DpiZoom(); - Margin = new Padding(0); - BackColor = MyMainForm.FormBack; - - // 使用RichTextBox - rtbText = new RichTextBox - { - BorderStyle = BorderStyle.None, - BackColor = MyMainForm.FormBack, - ForeColor = MyMainForm.FormFore, - ReadOnly = true, - ScrollBars = RichTextBoxScrollBars.None, - Multiline = false, - DetectUrls = false, - Name = "Text", - TabStop = false, // 禁用Tab键焦点 - HideSelection = true // 隐藏选择 - }; - - // 添加控件到面板 - Controls.AddRange(new Control[] { lblSeparator, flpControls, rtbText, picImage }); - - // 设置初始位置 - picImage.Left = 20.DpiZoom(); - rtbText.Left = 60.DpiZoom(); // 默认有图片的位置 - - // 设置RichTextBox的位置和大小 - UpdateRichTextBoxPosition(); - - Resize += (Sender, e) => - { - if (!IsDisposed) - { - pnlScrollbar.Height = ClientSize.Height; - UpdateRichTextBoxPosition(); - } - }; - - // 禁用RichTextBox的鼠标和键盘事件 - rtbText.MouseDown += (sender, e) => - { - if (!IsDisposed) - { - OnMouseDown(e); - // 防止RichTextBox获得焦点 - ((RichTextBox)sender).Parent.Focus(); - } - }; - - rtbText.MouseMove += (sender, e) => { if (!IsDisposed) OnMouseMove(e); }; - rtbText.MouseUp += (sender, e) => { if (!IsDisposed) OnMouseUp(e); }; - rtbText.MouseClick += (sender, e) => { if (!IsDisposed) OnMouseClick(e); }; - rtbText.MouseDoubleClick += (sender, e) => { if (!IsDisposed) OnDoubleClick(e); }; - - rtbText.KeyDown += (sender, e) => - { - if (!IsDisposed) - { - OnKeyDown(e); - e.Handled = true; // 阻止键盘事件 - } - }; - - rtbText.KeyPress += (sender, e) => - { - if (!IsDisposed) - { - OnKeyPress(e); - e.Handled = true; // 阻止键盘事件 - } - }; - - rtbText.KeyUp += (sender, e) => - { - if (!IsDisposed) - { - OnKeyUp(e); - e.Handled = true; // 阻止键盘事件 - } - }; - - flpControls.MouseClick += (sender, e) => { if (!IsDisposed) OnMouseClick(e); }; - flpControls.MouseDown += (sender, e) => { if (!IsDisposed) OnMouseDown(e); }; - - // 为子控件添加悬停事件 - foreach (Control control in Controls) - { - control.MouseEnter += (sender, e) => { if (!IsDisposed) OnMouseEnter(e); }; - control.MouseLeave += (sender, e) => { if (!IsDisposed) OnMouseLeave(e); }; - } - - lblSeparator.SetEnabled(false); - - CenterControl(picImage); - AddCtr(pnlScrollbar, 0); - - // 最后设置HasImage,确保所有控件已初始化 - hasImage = true; - picImage.Visible = true; - - ResumeLayout(); - } - - // 更新RichTextBox的位置以实现垂直居中 - private void UpdateRichTextBoxPosition() - { - if (rtbText == null || rtbText.IsDisposed || IsDisposed) return; - - // 计算文本高度 - int textHeight = TextRenderer.MeasureText("A", rtbText.Font).Height; - - // 计算垂直居中位置 - int top = (Height - textHeight) / 2; - - // 设置RichTextBox的位置和大小 - rtbText.Top = top; - rtbText.Height = textHeight + 2; // 添加一点额外高度确保文本完全显示 - rtbText.Width = Width - rtbText.Left - flpControls.Width - 10.DpiZoom(); - } - - public Image Image - { - get => picImage?.Image; - set - { - if (picImage != null && !picImage.IsDisposed && !IsDisposed) - picImage.Image = value; - } - } - - public new string Text - { - get => displayText ?? string.Empty; - set - { - displayText = value; - if (rtbText != null && !rtbText.IsDisposed && !IsDisposed) - { - rtbText.Text = value; - UpdateHighlight(); - UpdateRichTextBoxPosition(); // 文本改变时更新位置 - } - } - } - - public new Font Font - { - get => rtbText?.Font ?? SystemFonts.IconTitleFont; - set - { - if (rtbText != null && !rtbText.IsDisposed && !IsDisposed) - { - rtbText.Font = value; - UpdateHighlight(); - UpdateRichTextBoxPosition(); // 字体改变时更新位置 - } - } - } - - public new Color ForeColor - { - get => rtbText?.ForeColor ?? MyMainForm.FormFore; - set - { - if (rtbText != null && !rtbText.IsDisposed && !IsDisposed) - { - rtbText.ForeColor = value; - UpdateHighlight(); - } - } - } - - // 高亮文本属性 - public string HighlightText - { - get => highlightText; - set - { - if (highlightText != value && !IsDisposed) - { - highlightText = value; - UpdateHighlight(); - } - } - } - - // 自动适配的高亮颜色 - public Color HighlightColor - { - get - { - if (IsDisposed) return Color.Yellow; - - // 根据背景色亮度自动选择合适的高亮颜色 - bool isDarkMode = IsDarkColor(BackColor); - return isDarkMode ? - Color.FromArgb(255, 100, 70, 0) : // 暗色模式:暗橙色 - Color.FromArgb(255, 255, 220, 100); // 浅色模式:浅黄色 - } - } - - // 判断颜色是否为暗色 - private bool IsDarkColor(Color color) - { - // 计算颜色的相对亮度 (ITU-R BT.709 标准) - double luminance = (0.2126 * color.R + 0.7152 * color.G + 0.0722 * color.B) / 255; - return luminance < 0.5; - } - - private bool hasImage; - public bool HasImage - { - get => hasImage; - set - { - hasImage = value; - if (picImage != null && !picImage.IsDisposed && !IsDisposed) - picImage.Visible = value; - if (rtbText != null && !rtbText.IsDisposed && !IsDisposed) - { - rtbText.Left = (value ? 60 : 20).DpiZoom(); - UpdateRichTextBoxPosition(); // 位置改变时更新位置 - } - } - } - - // 更新高亮显示 - private void UpdateHighlight() - { - if (rtbText == null || rtbText.IsDisposed || IsDisposed || string.IsNullOrEmpty(Text)) return; - - try - { - // 保存当前选择位置 - int originalSelectionStart = rtbText.SelectionStart; - int originalSelectionLength = rtbText.SelectionLength; - - // 清除所有格式 - rtbText.SelectAll(); - rtbText.SelectionBackColor = rtbText.BackColor; - rtbText.DeselectAll(); - - // 如果有高亮文本,应用高亮 - if (!string.IsNullOrEmpty(highlightText)) - { - var text = Text; - var searchText = highlightText; - var index = text.IndexOf(searchText, StringComparison.OrdinalIgnoreCase); - - if (index >= 0) - { - rtbText.Select(index, searchText.Length); - rtbText.SelectionBackColor = HighlightColor; - rtbText.DeselectAll(); - } - } - - // 恢复原始选择位置 - rtbText.Select(originalSelectionStart, originalSelectionLength); - - // 确保没有文本被选中 - rtbText.SelectionStart = 0; - rtbText.SelectionLength = 0; - } - catch (ObjectDisposedException) - { - // 忽略已释放对象的异常 - return; - } - } - - protected override void OnMouseDown(MouseEventArgs e) - { - if (IsDisposed) return; - - base.OnMouseDown(e); - OnMouseEnter(e); // 鼠标按下时也触发悬停效果 - - // 确保RichTextBox没有焦点 - if (rtbText != null && !rtbText.IsDisposed && rtbText.Focused) - { - // 将焦点转移到父控件 - this.Focus(); - } - } - - private readonly PictureBox picImage = new PictureBox - { - SizeMode = PictureBoxSizeMode.AutoSize, - Enabled = false, - Name = "Image" - }; - private readonly FlowLayoutPanel flpControls = new FlowLayoutPanel - { - AutoSizeMode = AutoSizeMode.GrowAndShrink, - FlowDirection = FlowDirection.RightToLeft, - Anchor = AnchorStyles.Right, - AutoSize = true, - Name = "Controls" - }; - private readonly Label lblSeparator = new Label - { - BackColor = MyMainForm.FormFore, - Dock = DockStyle.Bottom, - Name = "Separator", - Height = 1 - };//分割线 - private readonly Panel pnlScrollbar = new Panel - { - Width = SystemInformation.VerticalScrollBarWidth, - Enabled = false - };//预留滚动条宽度 - - private void CenterControl(Control ctr) - { - if (ctr == null || IsDisposed) return; - - void reSize() - { - if (ctr.Parent == null || ctr.IsDisposed || IsDisposed) return; - int top = (ClientSize.Height - ctr.Height) / 2; - ctr.Top = top; - if (ctr.Parent == flpControls) - { - ctr.Margin = new Padding(0, top, ctr.Margin.Right, top); - } - } - ctr.Parent.Resize += (sender, e) => reSize(); - ctr.Resize += (sender, e) => reSize(); - reSize(); - } - - public void AddCtr(Control ctr) - { - AddCtr(ctr, 20.DpiZoom()); - } - - public void AddCtr(Control ctr, int space) - { - if (ctr == null || flpControls == null || IsDisposed) return; - - SuspendLayout(); - ctr.Parent = flpControls; - ctr.Margin = new Padding(0, 0, space, 0); - - ctr.MouseDown += (sender, e) => { if (!IsDisposed) OnMouseDown(e); }; - ctr.MouseEnter += (sender, e) => { if (!IsDisposed) OnMouseEnter(e); }; - ctr.MouseLeave += (sender, e) => { if (!IsDisposed) OnMouseLeave(e); }; - CenterControl(ctr); - ResumeLayout(); - } - - public void AddCtrs(Control[] ctrs) - { - if (ctrs == null) return; - Array.ForEach(ctrs, ctr => - { - if (!ctr.IsDisposed) - AddCtr(ctr); - }); - } - - public void RemoveCtrAt(int index) - { - if (flpControls?.Controls != null && flpControls.Controls.Count > index && !IsDisposed) - flpControls.Controls.RemoveAt(index + 1); - } - - public int GetCtrIndex(Control ctr) - { - return flpControls?.Controls?.GetChildIndex(ctr, true) - 1 ?? -1; - } - - public void SetCtrIndex(Control ctr, int newIndex) - { - flpControls?.Controls?.SetChildIndex(ctr, newIndex + 1); - } - } +using BluePointLilac.Methods; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Windows.Forms; + +namespace BluePointLilac.Controls +{ + public class MyListBox : Panel + { + public MyListBox() + { + AutoScroll = true; + UpdateColors(); + + // 订阅主题变化事件 + DarkModeHelper.ThemeChanged += OnThemeChanged; + } + + protected override void OnMouseWheel(MouseEventArgs e) + { + // 使滚动幅度与MyListItem的高度相配合,防止滚动过快导致来不及重绘界面变花 + base.OnMouseWheel(new MouseEventArgs(e.Button, e.Clicks, e.X, e.Y, Math.Sign(e.Delta) * 50.DpiZoom())); + } + + /// + /// 主题变化事件处理 + /// + private void OnThemeChanged(object sender, EventArgs e) + { + if (IsHandleCreated && !IsDisposed) + { + UpdateColors(); + Invalidate(true); + } + } + + /// + /// 更新控件颜色 + /// + public void UpdateColors() + { + BackColor = DarkModeHelper.FormBack; + ForeColor = DarkModeHelper.FormFore; + } + + /// + /// 清理资源 + /// + protected override void Dispose(bool disposing) + { + if (disposing) + { + DarkModeHelper.ThemeChanged -= OnThemeChanged; + } + base.Dispose(disposing); + } + } + + public class MyList : FlowLayoutPanel + { + public MyListBox Owner + { + get => (MyListBox)Parent; + set => Parent = value; + } + + public MyList(MyListBox owner) : this() + { + Owner = owner; + } + + public MyList() + { + AutoSize = true; + WrapContents = true; + Dock = DockStyle.Top; + DoubleBuffered = true; + AutoSizeMode = AutoSizeMode.GrowAndShrink; + + // 订阅主题变化事件 + DarkModeHelper.ThemeChanged += OnThemeChanged; + } + + private MyListItem hoveredItem; + public MyListItem HoveredItem + { + get => hoveredItem; + set + { + if(hoveredItem == value) return; + if(hoveredItem != null) + { + hoveredItem.ForeColor = DarkModeHelper.FormFore; + hoveredItem.Font = new Font(hoveredItem.Font, FontStyle.Regular); + } + hoveredItem = value; + if (hoveredItem != null) + { + value.ForeColor = DarkModeHelper.MainColor; + value.Font = new Font(hoveredItem.Font, FontStyle.Bold); + value.Focus(); + } + HoveredItemChanged?.Invoke(this, null); + } + } + + public event EventHandler HoveredItemChanged; + + public void AddItem(MyListItem item) + { + SuspendLayout(); + item.Parent = this; + item.MouseEnter += (sender, e) => HoveredItem = item; + MouseWheel += (sender, e) => item.ContextMenuStrip?.Close(); + void ResizeItem() => item.Width = Owner.Width - item.Margin.Horizontal; + Owner.Resize += (sender, e) => ResizeItem(); + ResizeItem(); + ResumeLayout(); + } + + public void AddItems(MyListItem[] items) + { + Array.ForEach(items, item => AddItem(item)); + } + + public void AddItems(List items) + { + items.ForEach(item => AddItem(item)); + } + + public void SetItemIndex(MyListItem item, int newIndex) + { + Controls.SetChildIndex(item, newIndex); + } + + public int GetItemIndex(MyListItem item) + { + return Controls.GetChildIndex(item); + } + + public void InsertItem(MyListItem item, int index) + { + if(item == null) return; + AddItem(item); + SetItemIndex(item, index); + } + + public virtual void ClearItems() + { + if(Controls.Count == 0) return; + SuspendLayout(); + for(int i = Controls.Count - 1; i >= 0; i--) + { + Control ctr = Controls[i]; + Controls.Remove(ctr); + ctr.Dispose(); + } + ResumeLayout(); + } + + public void SortItemByText() + { + List items = new List(); + foreach(MyListItem item in Controls) items.Add(item); + Controls.Clear(); + items.Sort(new TextComparer()); + items.ForEach(item => AddItem(item)); + } + + public class TextComparer : IComparer + { + public int Compare(MyListItem x, MyListItem y) + { + if(x.Equals(y)) return 0; + string[] strs = { x.Text, y.Text }; + Array.Sort(strs); + if(strs[0] == x.Text) return -1; + else return 1; + } + } + + /// + /// 主题变化事件处理 + /// + private void OnThemeChanged(object sender, EventArgs e) + { + if (IsHandleCreated && !IsDisposed) + { + // 更新悬停项的颜色 + if (hoveredItem != null && hoveredItem.IsHandleCreated && !hoveredItem.IsDisposed) + { + hoveredItem.ForeColor = DarkModeHelper.MainColor; + } + } + } + + /// + /// 清理资源 + /// + protected override void Dispose(bool disposing) + { + if (disposing) + { + DarkModeHelper.ThemeChanged -= OnThemeChanged; + } + base.Dispose(disposing); + } + } + + public class MyListItem : Panel + { + private string subText; // 添加SubText字段 + + public MyListItem() + { + SuspendLayout(); + HasImage = true; + DoubleBuffered = true; + Height = 50.DpiZoom(); + Margin = new Padding(0); + Font = SystemFonts.IconTitleFont; + + // 初始化颜色 + UpdateColors(); + + Controls.AddRange(new Control[] { lblSeparator, flpControls, lblText, picImage }); + Resize += (Sender, e) => pnlScrollbar.Height = ClientSize.Height; + flpControls.MouseClick += (sender, e) => OnMouseClick(e); + flpControls.MouseEnter += (sender, e) => OnMouseEnter(e); + flpControls.MouseDown += (sender, e) => OnMouseDown(e); + lblSeparator.SetEnabled(false); + lblText.SetEnabled(false); + CenterControl(lblText); + CenterControl(picImage); + AddCtr(pnlScrollbar, 0); + + // 订阅主题变化事件 + DarkModeHelper.ThemeChanged += OnThemeChanged; + + ResumeLayout(); + } + + public Image Image + { + get => picImage.Image; + set => picImage.Image = value; + } + public new string Text + { + get => lblText.Text; + set => lblText.Text = value; + } + public new Font Font + { + get => lblText.Font; + set => lblText.Font = value; + } + public new Color ForeColor + { + get => lblText.ForeColor; + set => lblText.ForeColor = value; + } + + // 添加SubText属性 + public string SubText + { + get => subText; + set + { + subText = value; + // 如果需要显示副文本,可以在这里添加UI更新逻辑 + } + } + + private bool hasImage; + public bool HasImage + { + get => hasImage; + set + { + hasImage = value; + picImage.Visible = value; + lblText.Left = (value ? 60 : 20).DpiZoom(); + } + } + + private readonly Label lblText = new Label + { + AutoSize = true, + Name = "Text" + }; + private readonly PictureBox picImage = new PictureBox + { + SizeMode = PictureBoxSizeMode.AutoSize, + Left = 20.DpiZoom(), + Enabled = false, + Name = "Image" + }; + private readonly FlowLayoutPanel flpControls = new FlowLayoutPanel + { + AutoSizeMode = AutoSizeMode.GrowAndShrink, + FlowDirection = FlowDirection.RightToLeft, + Anchor = AnchorStyles.Right, + AutoSize = true, + Name = "Controls" + }; + private readonly Label lblSeparator = new Label + { + BackColor = DarkModeHelper.FormFore, + Dock = DockStyle.Bottom, + Name = "Separator", + Height = 1 + };//分割线 + private readonly Panel pnlScrollbar = new Panel + { + Width = SystemInformation.VerticalScrollBarWidth, + Enabled = false + };//预留滚动条宽度 + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); OnMouseEnter(null); + } + + private void CenterControl(Control ctr) + { + void reSize() + { + if(ctr.Parent == null) return; + int top = (ClientSize.Height - ctr.Height) / 2; + ctr.Top = top; + if(ctr.Parent == flpControls) + { + ctr.Margin = new Padding(0, top, ctr.Margin.Right, top); + } + } + ctr.Parent.Resize += (sender, e) => reSize(); + ctr.Resize += (sender, e) => reSize(); + reSize(); + } + + public void AddCtr(Control ctr) + { + AddCtr(ctr, 20.DpiZoom()); + } + + public void AddCtr(Control ctr, int space) + { + SuspendLayout(); + ctr.Parent = flpControls; + ctr.Margin = new Padding(0, 0, space, 0); + ctr.MouseEnter += (sender, e) => OnMouseEnter(e); + ctr.MouseDown += (sender, e) => OnMouseEnter(e); + CenterControl(ctr); + ResumeLayout(); + } + + public void AddCtrs(Control[] ctrs) + { + Array.ForEach(ctrs, ctr => AddCtr(ctr)); + } + + public void RemoveCtrAt(int index) + { + if(flpControls.Controls.Count > index) flpControls.Controls.RemoveAt(index + 1); + } + + public int GetCtrIndex(Control ctr) + { + return flpControls.Controls.GetChildIndex(ctr, true) - 1; + } + + public void SetCtrIndex(Control ctr, int newIndex) + { + flpControls.Controls.SetChildIndex(ctr, newIndex + 1); + } + + /// + /// 主题变化事件处理 + /// + private void OnThemeChanged(object sender, EventArgs e) + { + if (IsHandleCreated && !IsDisposed) + { + UpdateColors(); + Invalidate(true); + } + } + + /// + /// 更新控件颜色 + /// + public void UpdateColors() + { + BackColor = DarkModeHelper.FormBack; + ForeColor = DarkModeHelper.FormFore; + + // 更新子控件颜色 + lblSeparator.BackColor = DarkModeHelper.FormFore; + lblText.ForeColor = DarkModeHelper.FormFore; + } + + /// + /// 清理资源 + /// + protected override void Dispose(bool disposing) + { + if (disposing) + { + DarkModeHelper.ThemeChanged -= OnThemeChanged; + } + base.Dispose(disposing); + } + } } \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Controls/MyMainForm.cs b/ContextMenuManager/BluePointLilac.Controls/MyMainForm.cs index b6f097ea..1b7499df 100644 --- a/ContextMenuManager/BluePointLilac.Controls/MyMainForm.cs +++ b/ContextMenuManager/BluePointLilac.Controls/MyMainForm.cs @@ -1,5 +1,4 @@ using BluePointLilac.Methods; -using Microsoft.Win32; using System; using System.Drawing; using System.Runtime.InteropServices; @@ -9,15 +8,12 @@ namespace BluePointLilac.Controls { public class MyMainForm : Form { - // 程序主题色 - public static Color MainColor = Color.FromArgb(255, 143, 31); - public MyMainForm() { SuspendLayout(); Text = Application.ProductName; - ForeColor = FormFore; - BackColor = FormBack; + ForeColor = DarkModeHelper.FormFore; + BackColor = DarkModeHelper.FormBack; StartPosition = FormStartPosition.CenterScreen; Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); Controls.AddRange(new Control[] { MainBody, SideBar, StatusBar, ToolBar }); @@ -27,6 +23,13 @@ public MyMainForm() MainBody.Dock = DockStyle.Left; StatusBar.CanMoveForm(); ToolBar.CanMoveForm(); + + // 初始化主题 + DarkModeHelper.Initialize(); + DarkModeHelper.ThemeChanged += OnThemeChanged; + DarkModeHelper.ApplyDarkModeToForm(this); + Adjust(); + ResumeLayout(); } @@ -58,10 +61,10 @@ protected override void WndProc(ref Message m) const int SC_SIZE = 0xF000; const int HT_CAPTION = 0x2; bool suspend = false;//临时挂起MainBody - switch (m.Msg) + switch(m.Msg) { case WM_SYSCOMMAND: - switch (m.WParam.ToInt32()) + switch(m.WParam.ToInt32()) { //解决控件过多移动窗体时延迟问题 case SC_MOVE: @@ -76,7 +79,7 @@ protected override void WndProc(ref Message m) } break; case WM_NCLBUTTONDBLCLK: - switch (m.WParam.ToInt32()) + switch(m.WParam.ToInt32()) { //双击标题栏最大化和还原窗口 case HT_CAPTION: @@ -84,7 +87,7 @@ protected override void WndProc(ref Message m) } break; } - if (suspend) + if(suspend) { SuspendLayout(); MainBody.SuspendLayout(); @@ -98,27 +101,6 @@ protected override void WndProc(ref Message m) else base.WndProc(ref m); } - #region Dark Theme - - /* - * Edited from: https://github.com/seerge/g-helper - */ - - public static Color ButtonMain; - public static Color ButtonSecond; - public static Color titleArea; - - public static Color FormBack; - public static Color FormFore; - public static Color FormBorder; - - [DllImport("UXTheme.dll", SetLastError = true, EntryPoint = "#138")] - public static extern bool CheckSystemDarkModeStatus(); - - [DllImport("DwmApi")] //System.Runtime.InteropServices - private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, int[] attrValue, int attrSize); - - public bool darkTheme = false; protected override CreateParams CreateParams { get @@ -130,126 +112,28 @@ protected override CreateParams CreateParams } } - public static void InitColors() - { - InitColors(IsDarkTheme()); - } - - private static void InitColors(bool darkTheme) - { - if (darkTheme) - { - titleArea = Color.FromArgb(255, 32, 32, 32); - - ButtonMain = Color.FromArgb(255, 55, 55, 55); - ButtonSecond = Color.FromArgb(255, 38, 38, 38); - - FormBack = Color.FromArgb(255, 28, 28, 28); - FormFore = Color.FromArgb(255, 240, 240, 240); - FormBorder = Color.FromArgb(255, 50, 50, 50); - } - else - { - titleArea = Color.FromArgb(255, 243, 243, 243); - - ButtonMain = SystemColors.ControlLightLight; - ButtonSecond = SystemColors.ControlLight; - - FormBack = SystemColors.Control; - FormFore = SystemColors.ControlText; - FormBorder = Color.LightGray; - } - } - - public static bool IsDarkTheme() - { - using (var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize")) - { - var registryValueObject = key?.GetValue("AppsUseLightTheme"); - - if (registryValueObject == null) return false; - return (int)registryValueObject <= 0; - } - } - - public bool InitTheme(bool firstTime = false) + private void OnThemeChanged(object sender, EventArgs e) { - bool newDarkTheme = IsDarkTheme(); - bool changed = darkTheme != newDarkTheme; - darkTheme = newDarkTheme; - - InitColors(darkTheme); - - if (firstTime || changed) - { - DwmSetWindowAttribute(Handle, 20, new[] { darkTheme ? 1 : 0 }, 4); - Adjust(); - Invalidate(); - } - - return changed; + DarkModeHelper.ApplyDarkModeToForm(this); + Adjust(); + Invalidate(); } private void Adjust() { - BackColor = FormBack; - ForeColor = FormFore; + BackColor = DarkModeHelper.FormBack; + ForeColor = DarkModeHelper.FormFore; - AdjustControls(Controls); + DarkModeHelper.AdjustControlColors(this); } - private void AdjustControls(Control.ControlCollection controls) + protected override void Dispose(bool disposing) { - foreach (Control control in controls) + if (disposing) { - AdjustControls(control.Controls); - - if (control is MyListBox listBox) - { - listBox.BackColor = FormBack; - listBox.ForeColor = FormFore; - } - - if (control is MyListItem listItem) - { - listItem.BackColor = FormBack; - listItem.ForeColor = FormFore; - } - - if (control is MyToolBar toolBar) - { - toolBar.BackColor = titleArea; - toolBar.ForeColor = FormFore; - } - - if (control is MyToolBarButton toolBarButton) - { - toolBarButton.ForeColor = FormFore; - } - - if (control is MySideBar sideBar) - { - sideBar.BackColor = ButtonSecond;// More darker than buttonMain - sideBar.ForeColor = FormFore; - } - - if (control is MyStatusBar statusBar) - { - statusBar.BackColor = ButtonMain; - statusBar.ForeColor = FormFore; - } - - if (control is RComboBox combo) - { - combo.BackColor = ButtonMain; - combo.ForeColor = FormFore; - combo.BorderColor = ButtonMain; - combo.ButtonColor = ButtonMain; - combo.ArrowColor = FormFore; - } + DarkModeHelper.StopListening(); } + base.Dispose(disposing); } - - #endregion } -} +} \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Controls/MySideBar.cs b/ContextMenuManager/BluePointLilac.Controls/MySideBar.cs index 73f1b889..623df1d4 100644 --- a/ContextMenuManager/BluePointLilac.Controls/MySideBar.cs +++ b/ContextMenuManager/BluePointLilac.Controls/MySideBar.cs @@ -3,6 +3,7 @@ using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; +using System.ComponentModel; namespace BluePointLilac.Controls { @@ -11,11 +12,18 @@ public sealed class MySideBar : Panel private readonly Panel PnlSelected = new Panel { Enabled = false, BackColor = Color.Transparent }; private readonly Panel PnlHovered = new Panel { Enabled = false, BackColor = Color.Transparent }; private readonly Label LblSeparator = new Label { Dock = DockStyle.Right, Width = 1 }; - + private readonly Timer animationTimer = new Timer { Interval = 16 }; + private string[] itemNames; private int itemHeight = 36; private int selectIndex = -1; private int hoverIndex = -1; + + private int animationTargetIndex = -1; + private int animationCurrentIndex = -1; + private float animationProgress = 0f; + private const float ANIMATION_SPEED = 0.25f; + private bool isAnimating = false; public Color SelectedGradientColor1 { get; set; } = Color.FromArgb(255, 195, 0); public Color SelectedGradientColor2 { get; set; } = Color.FromArgb(255, 141, 26); @@ -23,7 +31,9 @@ public sealed class MySideBar : Panel public Color BackgroundGradientColor1 { get; set; } = Color.FromArgb(240, 240, 240); public Color BackgroundGradientColor2 { get; set; } = Color.FromArgb(220, 220, 220); public Color BackgroundGradientColor3 { get; set; } = Color.FromArgb(200, 200, 200); - + + [Browsable(false)] public bool EnableAnimation { get; set; } = true; + public string[] ItemNames { get => itemNames; @@ -33,7 +43,8 @@ public string[] ItemNames if (value != null && !IsFixedWidth) { int maxWidth = 0; - Array.ForEach(value, str => maxWidth = Math.Max(maxWidth, GetItemWidth(str))); + foreach (string str in value) + maxWidth = Math.Max(maxWidth, GetItemWidth(str)); Width = maxWidth + 2 * HorizontalSpace; } PnlHovered.Width = PnlSelected.Width = Width; @@ -41,38 +52,36 @@ public string[] ItemNames SelectedIndex = -1; } } - + public int ItemHeight { get => itemHeight; set => itemHeight = Math.Max(1, value); } public int TopSpace { get; set; } = 4.DpiZoom(); public int HorizontalSpace { get; set; } = 20.DpiZoom(); public bool IsFixedWidth { get; set; } = true; - + public Color SeparatorColor { get => LblSeparator.BackColor; set => LblSeparator.BackColor = value; } public Color SelectedBackColor { get => PnlSelected.BackColor; set => PnlSelected.BackColor = value; } public Color HoveredBackColor { get => PnlHovered.BackColor; set => PnlHovered.BackColor = value; } public Color SelectedForeColor { get; set; } = Color.Black; public Color HoveredForeColor { get; set; } - - private float VerticalSpace => (itemHeight - TextHeight) * 0.5F; - private int TextHeight => TextRenderer.MeasureText(" ", Font).Height; - private bool IsDarkTheme => ControlPaint.Light(BackColor).GetBrightness() < 0.5f; - + + private float VerticalSpace => (itemHeight - TextRenderer.MeasureText(" ", Font).Height) * 0.5F; + public event EventHandler SelectIndexChanged; public event EventHandler HoverIndexChanged; - + public int SelectedIndex { get => selectIndex; set { if (selectIndex == value) return; - selectIndex = value; - RefreshItem(PnlSelected, value); - HoveredIndex = value; - SelectIndexChanged?.Invoke(this, EventArgs.Empty); + if (EnableAnimation && value >= 0 && value < ItemNames?.Length && selectIndex >= 0 && !isAnimating) + StartAnimation(selectIndex, value); + else + SetSelectedIndexDirectly(value); } } - + public int HoveredIndex { get => hoverIndex; @@ -84,7 +93,7 @@ public int HoveredIndex HoverIndexChanged?.Invoke(this, EventArgs.Empty); } } - + public MySideBar() { Dock = DockStyle.Left; @@ -92,60 +101,151 @@ public MySideBar() BackgroundImageLayout = ImageLayout.None; DoubleBuffered = true; Font = new Font(SystemFonts.MenuFont.FontFamily, SystemFonts.MenuFont.Size + 1F); - + InitializeColors(); Controls.AddRange(new Control[] { LblSeparator, PnlSelected, PnlHovered }); - + SizeChanged += (sender, e) => UpdateBackground(); PnlHovered.Paint += PaintHoveredItem; PnlSelected.Paint += PaintSelectedItem; + animationTimer.Tick += AnimationTimer_Tick; + + DarkModeHelper.ThemeChanged += OnThemeChanged; SelectedIndex = -1; } - + + private void StartAnimation(int fromIndex, int toIndex) + { + animationCurrentIndex = fromIndex; + animationTargetIndex = toIndex; + animationProgress = 0f; + isAnimating = true; + + if (!animationTimer.Enabled) + animationTimer.Start(); + } + + private void AnimationTimer_Tick(object sender, EventArgs e) + { + animationProgress += ANIMATION_SPEED; + + if (animationProgress >= 1f) + CompleteAnimation(); + else + UpdateAnimationFrame(); + } + + private void UpdateAnimationFrame() + { + if (animationCurrentIndex < 0 || animationTargetIndex < 0) return; + + float easedProgress = EaseOutCubic(animationProgress); + int startTop = GetItemTop(animationCurrentIndex); + int targetTop = GetItemTop(animationTargetIndex); + int currentTop = Math.Max(0, Math.Min( + (int)(startTop + (targetTop - startTop) * easedProgress), Height - ItemHeight)); + + PnlSelected.Top = currentTop; + PnlSelected.Height = ItemHeight; + + if (hoverIndex == selectIndex) + { + PnlHovered.Top = PnlSelected.Top; + PnlHovered.Height = ItemHeight; + } + + Invalidate(); + Update(); + } + + private void CompleteAnimation() + { + animationProgress = 1f; + isAnimating = false; + animationTimer.Stop(); + + SetSelectedIndexDirectly(animationTargetIndex); + PnlSelected.Top = GetItemTop(selectIndex); + + if (hoverIndex == selectIndex) + PnlHovered.Top = PnlSelected.Top; + + Refresh(); + } + + private void SetSelectedIndexDirectly(int value) + { + selectIndex = value; + RefreshItem(PnlSelected, value); + HoveredIndex = value; + SelectIndexChanged?.Invoke(this, EventArgs.Empty); + } + + private int GetItemTop(int index) => TopSpace + index * ItemHeight; + + private float EaseOutCubic(float t) => 1 - (float)Math.Pow(1 - t, 3); + public void BeginUpdate() => SuspendLayout(); public void EndUpdate() { ResumeLayout(true); UpdateBackground(); } public int GetItemWidth(string str) => TextRenderer.MeasureText(str, Font).Width + 2 * HorizontalSpace; - - private void InitializeColors() + + public void StopAnimation() { - Color baseColor = IsDarkTheme ? Color.FromArgb(26, 26, 26) : SystemColors.Control; - BackColor = baseColor; - ForeColor = IsDarkTheme ? Color.WhiteSmoke : SystemColors.ControlText; - HoveredBackColor = IsDarkTheme ? Color.FromArgb(51, 51, 51) : Color.FromArgb(230, 230, 230); - SeparatorColor = IsDarkTheme ? Color.FromArgb(64, 64, 64) : Color.FromArgb(200, 200, 200); - PnlSelected.BackColor = Color.Transparent; - - if (IsDarkTheme) + if (isAnimating) { - BackgroundGradientColor1 = Color.FromArgb(128, 128, 128); - BackgroundGradientColor2 = Color.FromArgb(56, 56, 56); - BackgroundGradientColor3 = Color.FromArgb(128, 128, 128); + animationTimer.Stop(); + isAnimating = false; + SetSelectedIndexDirectly(animationTargetIndex); } - else + } + + public void SmoothScrollTo(int index) + { + if (index >= 0 && index < ItemNames?.Length) + SelectedIndex = index; + } + + protected override void Dispose(bool disposing) + { + if (disposing) { - BackgroundGradientColor1 = Color.FromArgb(255, 255, 255); - BackgroundGradientColor2 = Color.FromArgb(230, 230, 230); - BackgroundGradientColor3 = Color.FromArgb(255, 255, 255); + DarkModeHelper.ThemeChanged -= OnThemeChanged; + animationTimer?.Stop(); + animationTimer?.Dispose(); } + base.Dispose(disposing); } - + + private void InitializeColors() + { + BackColor = DarkModeHelper.SideBarBackground; + ForeColor = DarkModeHelper.FormFore; + HoveredBackColor = DarkModeHelper.SideBarHovered; + SeparatorColor = DarkModeHelper.SideBarSeparator; + PnlSelected.BackColor = Color.Transparent; + + BackgroundGradientColor1 = DarkModeHelper.ToolBarGradientTop; + BackgroundGradientColor2 = DarkModeHelper.ToolBarGradientMiddle; + BackgroundGradientColor3 = DarkModeHelper.ToolBarGradientBottom; + } + private void UpdateBackground() { if (ItemNames == null) return; int bgWidth = Math.Max(1, Width); - int bgHeight = CalculateValidBackgroundHeight(); - if (bgWidth <= 0 || bgHeight <= 0) return; - + int bgHeight = ItemNames.Length == 0 ? Math.Max(1, Height) : + Math.Max(Height, Math.Max(0, ItemHeight) * ItemNames.Length); + try { var oldBackground = BackgroundImage; BackgroundImage = new Bitmap(bgWidth, bgHeight); oldBackground?.Dispose(); - + using (var g = Graphics.FromImage(BackgroundImage)) { DrawBackgroundGradient(g, bgWidth, bgHeight); - if (ShouldDrawItems()) + if (ItemNames.Length > 0 && ItemHeight > 0 && Width > 0 && Height > 0) { DrawTextItems(g); DrawSeparators(g); @@ -158,26 +258,20 @@ private void UpdateBackground() BackgroundImage = null; } } - - private int CalculateValidBackgroundHeight() => ItemNames == null || ItemNames.Length == 0 ? - Math.Max(1, Height) : Math.Max(Height, Math.Max(0, ItemHeight) * ItemNames.Length); - - private bool ShouldDrawItems() => ItemNames != null && ItemNames.Length > 0 && ItemHeight > 0 && Width > 0 && Height > 0; - + private void DrawBackgroundGradient(Graphics g, int width, int height) { using (var brush = new LinearGradientBrush(new Rectangle(0, 0, width, height), Color.Empty, Color.Empty, 0f)) { - var blend = new ColorBlend + brush.InterpolationColors = new ColorBlend { Colors = new[] { BackgroundGradientColor1, BackgroundGradientColor2, BackgroundGradientColor3 }, Positions = new[] { 0f, 0.5f, 1f } }; - brush.InterpolationColors = blend; g.FillRectangle(brush, new Rectangle(0, 0, width, height)); } } - + private void DrawTextItems(Graphics g) { if (ItemNames == null || ItemNames.Length == 0) return; @@ -192,7 +286,7 @@ private void DrawTextItems(Graphics g) } } } - + private void DrawSeparators(Graphics g) { using (var pen = new Pen(SeparatorColor)) @@ -205,17 +299,16 @@ private void DrawSeparators(Graphics g) } } } - + private int CalculateItemIndex(int yPos) { if (ItemNames == null || ItemHeight <= 0) return -1; - int relativeY = yPos - TopSpace; - int index = relativeY / ItemHeight; + int index = (yPos - TopSpace) / ItemHeight; if (index < 0 || index >= ItemNames.Length) return -1; if (string.IsNullOrEmpty(ItemNames[index])) return -1; return index; } - + private void RefreshItem(Panel panel, int index) { if (index < 0 || index >= ItemNames?.Length) @@ -225,15 +318,14 @@ private void RefreshItem(Panel panel, int index) } else { - int actualTop = TopSpace + index * ItemHeight; - actualTop = Math.Max(0, Math.Min(actualTop, Height - ItemHeight)); + int actualTop = Math.Max(0, Math.Min(TopSpace + index * ItemHeight, Height - ItemHeight)); panel.Top = actualTop; panel.Text = ItemNames[index]; } panel.Height = ItemHeight; panel.Refresh(); } - + private void PaintHoveredItem(object sender, PaintEventArgs e) { var ctr = (Control)sender; @@ -241,53 +333,62 @@ private void PaintHoveredItem(object sender, PaintEventArgs e) e.Graphics.FillRectangle(new SolidBrush(HoveredBackColor), new Rectangle(0, 0, ctr.Width, ctr.Height)); DrawItemText(e, ctr, HoveredForeColor); } - + private void PaintSelectedItem(object sender, PaintEventArgs e) { var ctr = (Control)sender; if (string.IsNullOrEmpty(ctr.Text)) return; - + using (var brush = new LinearGradientBrush(new Rectangle(0, 0, ctr.Width, ctr.Height), Color.Empty, Color.Empty, 0f)) { - var blend = new ColorBlend + brush.InterpolationColors = new ColorBlend { Colors = new[] { SelectedGradientColor1, SelectedGradientColor2, SelectedGradientColor3 }, Positions = new[] { 0f, 0.5f, 1f } }; - brush.InterpolationColors = blend; e.Graphics.FillRectangle(brush, new Rectangle(0, 0, ctr.Width, ctr.Height)); } DrawItemText(e, ctr, SelectedForeColor); } - + private void DrawItemText(PaintEventArgs e, Control ctr, Color textColor) { e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; - Color useColor = textColor == Color.Empty ? ForeColor : textColor; - using (var brush = new SolidBrush(useColor)) + using (var brush = new SolidBrush(textColor == Color.Empty ? ForeColor : textColor)) e.Graphics.DrawString(ctr.Text, Font, brush, new PointF(HorizontalSpace, VerticalSpace)); } - + private void ShowItem(Panel panel, MouseEventArgs e) { if (ItemNames == null) return; int index = CalculateItemIndex(e.Y); bool isValid = index != -1 && index != SelectedIndex; Cursor = isValid ? Cursors.Hand : Cursors.Default; + if (isValid) { - if (panel == PnlSelected) SelectedIndex = index; + if (panel == PnlSelected) + { + if (isAnimating) StopAnimation(); + SelectedIndex = index; + } else HoveredIndex = index; } else HoveredIndex = SelectedIndex; } - + protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); ShowItem(PnlHovered, e); } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button == MouseButtons.Left) ShowItem(PnlSelected, e); } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); HoveredIndex = SelectedIndex; } protected override void OnBackColorChanged(EventArgs e) { base.OnBackColorChanged(e); InitializeColors(); UpdateBackground(); } protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) => base.SetBoundsCore(x, y, Math.Max(1, width), Math.Max(1, height), specified); + + private void OnThemeChanged(object sender, EventArgs e) + { + InitializeColors(); + UpdateBackground(); + } } } \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Controls/MyStatusBar.cs b/ContextMenuManager/BluePointLilac.Controls/MyStatusBar.cs index b5b177af..d91fb06c 100644 --- a/ContextMenuManager/BluePointLilac.Controls/MyStatusBar.cs +++ b/ContextMenuManager/BluePointLilac.Controls/MyStatusBar.cs @@ -11,12 +11,12 @@ public sealed class MyStatusBar : Panel { public static readonly string DefaultText = $"Ver: {Application.ProductVersion} {Application.CompanyName}"; - // ɫ + // 渐变色定义 private Color topColor = Color.Empty; private Color middleColor = Color.Empty; private Color bottomColor = Color.Empty; - // ɫģʽ־ + // 主题模式标识 private bool isDarkMode = false; public MyStatusBar() @@ -26,101 +26,69 @@ public MyStatusBar() Dock = DockStyle.Bottom; Font = SystemFonts.StatusFont; - // ϵͳⲢɫ + // 初始化系统主题 CheckSystemTheme(); - // ϵͳ¼ - Microsoft.Win32.SystemEvents.UserPreferenceChanged += SystemEvents_UserPreferenceChanged; - this.Disposed += (s, e) => Microsoft.Win32.SystemEvents.UserPreferenceChanged -= SystemEvents_UserPreferenceChanged; + // 监听主题变化事件 + DarkModeHelper.ThemeChanged += OnThemeChanged; } - // ϵͳ¼ - private void SystemEvents_UserPreferenceChanged(object sender, Microsoft.Win32.UserPreferenceChangedEventArgs e) + // 主题变化事件处理 + private void OnThemeChanged(object sender, EventArgs e) { - if (e.Category == Microsoft.Win32.UserPreferenceCategory.General) - { - CheckSystemTheme(); - Refresh(); - } + CheckSystemTheme(); + Refresh(); } - // ϵͳ + // 检查系统主题 private void CheckSystemTheme() { - // Ƿɫģʽ (Windows 10/11) - isDarkMode = IsDarkThemeEnabled(); + // 使用DarkModeHelper统一管理主题 + isDarkMode = DarkModeHelper.IsDarkTheme; if (isDarkMode) { - // ɫģʽɫ - ʹɫ - BackColor = Color.FromArgb(40, 40, 40); // мɫΪɫ + // 深色模式颜色方案 - 使用渐变色 + BackColor = Color.FromArgb(40, 40, 40); // 备用背景色 ForeColor = Color.LightGray; - // ɫģʽɫ - ɫ - topColor = Color.FromArgb(128, 128, 128); - middleColor = Color.FromArgb(56, 56, 56); - bottomColor = Color.FromArgb(128, 128, 128); + // 使用DarkModeHelper中的颜色 + topColor = DarkModeHelper.StatusBarGradientTop; + middleColor = DarkModeHelper.StatusBarGradientMiddle; + bottomColor = DarkModeHelper.StatusBarGradientBottom; } else { - // dzɫģʽɫ - BackColor = MyMainForm.ButtonMain; - ForeColor = MyMainForm.FormFore; - - // dzɫģʽɫ - ɫ - topColor = Color.FromArgb(255, 255, 255); - middleColor = Color.FromArgb(230, 230, 230); - bottomColor = Color.FromArgb(255, 255, 255); + // 浅色模式颜色方案 + BackColor = DarkModeHelper.ButtonMain; + ForeColor = DarkModeHelper.FormFore; + + // 使用DarkModeHelper中的颜色 + topColor = DarkModeHelper.StatusBarGradientTop; + middleColor = DarkModeHelper.StatusBarGradientMiddle; + bottomColor = DarkModeHelper.StatusBarGradientBottom; } } - // ϵͳǷʹɫ - private bool IsDarkThemeEnabled() - { - try - { - // ͨעWindows - using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey( - @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize")) - { - if (key != null) - { - var value = key.GetValue("AppsUseLightTheme"); - if (value != null && value is int) - { - return (int)value == 0; - } - } - } - } - catch - { - // ޷⣬ʹĬֵ - } - - // Ĭʹdzɫģʽ - return false; - } - [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] public override string Text { get => base.Text; set => base.Text = value; } - // ɫ - [Browsable(true), Category("Appearance"), Description("䶥ɫ")] + // 渐变色属性 + [Browsable(true), Category("Appearance"), Description("渐变顶部颜色")] public Color TopColor { get => topColor; set { topColor = value; Refresh(); } } - [Browsable(true), Category("Appearance"), Description("мɫ")] + [Browsable(true), Category("Appearance"), Description("渐变中间颜色")] public Color MiddleColor { get => middleColor; set { middleColor = value; Refresh(); } } - [Browsable(true), Category("Appearance"), Description("ײɫ")] + [Browsable(true), Category("Appearance"), Description("渐变底部颜色")] public Color BottomColor { get => bottomColor; @@ -129,14 +97,14 @@ public Color BottomColor protected override void OnPaint(PaintEventArgs e) { - // ɫ䱳 + // 绘制渐变色背景 using (LinearGradientBrush brush = new LinearGradientBrush( ClientRectangle, Color.Empty, Color.Empty, LinearGradientMode.Vertical)) { - // ɫ + // 设置渐变色 ColorBlend colorBlend = new ColorBlend(3); colorBlend.Colors = new Color[] { TopColor, MiddleColor, BottomColor }; colorBlend.Positions = new float[] { 0f, 0.5f, 1f }; @@ -145,7 +113,7 @@ protected override void OnPaint(PaintEventArgs e) e.Graphics.FillRectangle(brush, ClientRectangle); } - // ıԭ߼ + // 绘制文本(带有省略号处理) string txt = Text; int left = Height / 3; for (int i = Text.Length - 1; i >= 0; i--) @@ -184,5 +152,14 @@ protected override void OnBackColorChanged(EventArgs e) { base.OnBackColorChanged(e); Refresh(); } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + DarkModeHelper.ThemeChanged -= OnThemeChanged; + } + base.Dispose(disposing); + } } } \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Controls/MyToolBar.cs b/ContextMenuManager/BluePointLilac.Controls/MyToolBar.cs index f74efa69..4f1e3102 100644 --- a/ContextMenuManager/BluePointLilac.Controls/MyToolBar.cs +++ b/ContextMenuManager/BluePointLilac.Controls/MyToolBar.cs @@ -1,4 +1,4 @@ -using BluePointLilac.Methods; +using BluePointLilac.Methods; using System; using System.Drawing; using System.Drawing.Drawing2D; @@ -13,41 +13,43 @@ public sealed class MyToolBar : Panel public const float SelctedOpacity = 0.8F; public const float HoveredOpacity = 0.4F; public const float UnSelctedOpacity = 0; - - private FlowLayoutPanel buttonPanel; + + private FlowLayoutPanel buttonContainer; + private Panel searchBoxContainer; public MyToolBar() { Height = 80.DpiZoom(); Dock = DockStyle.Top; DoubleBuffered = true; - BackColor = MyMainForm.titleArea; - ForeColor = MyMainForm.FormFore; - - // 启用透明背景支持 - SetStyle(ControlStyles.SupportsTransparentBackColor, true); - SetStyle(ControlStyles.Opaque, false); - - // 创建按钮面板 - InitializeButtonPanel(); - - // 添加搜索框 - InitializeSearchBox(); - } - - private void InitializeButtonPanel() - { - buttonPanel = new FlowLayoutPanel + BackColor = DarkModeHelper.TitleArea; + ForeColor = DarkModeHelper.FormFore; + + // 创建按钮容器(左侧) + buttonContainer = new FlowLayoutPanel { Dock = DockStyle.Left, + Height = Height, AutoSize = true, - AutoSizeMode = AutoSizeMode.GrowAndShrink, - BackColor = Color.Transparent, FlowDirection = FlowDirection.LeftToRight, - WrapContents = false + WrapContents = false, + BackColor = Color.Transparent }; - - Controls.Add(buttonPanel); + + // 创建搜索框容器(右侧) + searchBoxContainer = new Panel + { + Dock = DockStyle.Right, + Width = 240.DpiZoom(), + Height = Height, + BackColor = Color.Transparent + }; + + Controls.Add(buttonContainer); + Controls.Add(searchBoxContainer); + + // 监听主题变化 + DarkModeHelper.ThemeChanged += OnThemeChanged; } private MyToolBarButton selectedButton; @@ -74,133 +76,22 @@ public MyToolBarButton SelectedButton } } - // 搜索框相关属性 - private ModernSearchBox searchBox; - private Panel searchPanel; - public string SearchText => searchBox?.SearchText ?? string.Empty; - public event EventHandler SearchTextChanged; - public event EventHandler SearchPerformed; - public event EventHandler SelectedButtonChanged; public int SelectedIndex { - get - { - if (SelectedButton == null) return -1; - // 从 buttonPanel 中查找按钮索引 - var buttons = buttonPanel.Controls.OfType().ToList(); - return buttons.IndexOf(SelectedButton); - } - set - { - // 从 buttonPanel 中获取按钮 - var buttons = buttonPanel.Controls.OfType().ToList(); - SelectedButton = value < 0 || value >= buttons.Count ? null : buttons[value]; - } - } - - // 获取所有工具栏按钮(不包括搜索框) - public MyToolBarButton[] ToolBarButtons => buttonPanel.Controls.OfType().ToArray(); - - private void InitializeSearchBox() - { - // 创建搜索面板 - 固定在右侧 - searchPanel = new Panel - { - Height = 40.DpiZoom(), - Width = 220.DpiZoom(), - Anchor = AnchorStyles.Right | AnchorStyles.Top, - BackColor = Color.Transparent - }; - - // 启用透明背景支持 - searchPanel.SetStyle(ControlStyles.SupportsTransparentBackColor, true); - searchPanel.SetStyle(ControlStyles.Opaque, false); - - // 创建现代化搜索框 - searchBox = new ModernSearchBox - { - Size = new Size(200.DpiZoom(), 32.DpiZoom()), - Location = new Point(10, 4) - }; - - // 搜索事件 - searchBox.SearchPerformed += (sender, e) => - { - SearchPerformed?.Invoke(this, e); - }; - - // 文本改变事件 - searchBox.GetTextBox().TextChanged += (sender, e) => - { - SearchTextChanged?.Invoke(this, e); - }; - - // 将搜索框添加到搜索面板 - searchPanel.Controls.Add(searchBox); - - // 将搜索面板添加到工具栏 - Controls.Add(searchPanel); - - // 设置搜索面板在最前面 - searchPanel.BringToFront(); - - // 初始定位 - AdjustSearchBoxPosition(); - } - - // 公开获取内部文本框的方法 - public TextBox GetSearchTextBox() - { - return searchBox?.GetTextBox(); - } - - protected override void OnParentChanged(EventArgs e) - { - base.OnParentChanged(e); - AdjustSearchBoxPosition(); - } - - protected override void OnVisibleChanged(EventArgs e) - { - base.OnVisibleChanged(e); - if (searchPanel != null) - { - searchPanel.Visible = this.Visible; - if (this.Visible) - { - AdjustSearchBoxPosition(); - } - } - } - - private void AdjustSearchBoxPosition() - { - if (searchPanel != null) - { - // 定位到工具栏的右侧 - searchPanel.Location = new Point( - this.ClientSize.Width - searchPanel.Width - 20.DpiZoom(), - (this.Height - searchPanel.Height) / 2 - ); - } - } - - public void ClearSearch() - { - searchBox?.ClearSearch(); + get => SelectedButton == null ? -1 : buttonContainer.Controls.GetChildIndex(SelectedButton); + set => SelectedButton = value < 0 || value >= buttonContainer.Controls.Count ? + null : (MyToolBarButton)buttonContainer.Controls[value]; } - public void FocusSearchBox() - { - searchBox?.FocusSearch(); - } + // 添加一个方法来获取所有按钮(用于兼容旧代码) + public Control.ControlCollection ButtonControls => buttonContainer.Controls; public void AddButton(MyToolBarButton button) { - buttonPanel.SuspendLayout(); - button.Parent = buttonPanel; + buttonContainer.SuspendLayout(); + button.Parent = buttonContainer; button.Margin = new Padding(12, 4, 0, 0).DpiZoom(); button.MouseDown += (sender, e) => @@ -227,7 +118,7 @@ public void AddButton(MyToolBarButton button) } }; - buttonPanel.ResumeLayout(true); + buttonContainer.ResumeLayout(); } public void AddButtons(MyToolBarButton[] buttons) @@ -237,34 +128,57 @@ public void AddButtons(MyToolBarButton[] buttons) Array.ForEach(buttons, button => { button.Width = maxWidth; AddButton(button); }); } + // 添加搜索框到工具栏右侧 + public void AddSearchBox(SearchBox searchBox) + { + // 清除现有搜索框 + searchBoxContainer.Controls.Clear(); + + // 设置搜索框 + searchBox.Parent = searchBoxContainer; + searchBox.Width = searchBoxContainer.Width - 40.DpiZoom(); + searchBox.Height = 36.DpiZoom(); + searchBox.Left = 20.DpiZoom(); + searchBox.Top = (searchBoxContainer.Height - searchBox.Height) / 2; + } + + protected override void OnResize(EventArgs e) + { + base.OnResize(e); + + // 调整搜索框容器的宽度 + if (searchBoxContainer != null) + { + searchBoxContainer.Width = 240.DpiZoom(); + searchBoxContainer.Height = Height; + + // 确保搜索框在容器中垂直居中 + var searchBox = searchBoxContainer.Controls.OfType().FirstOrDefault(); + if (searchBox != null) + { + searchBox.Width = searchBoxContainer.Width - 40.DpiZoom(); + searchBox.Top = (searchBoxContainer.Height - searchBox.Height) / 2; + } + } + } + protected override void OnPaintBackground(PaintEventArgs e) { base.OnPaintBackground(e); var rect = ClientRectangle; - Color color1, color2, color3; - if (MyMainForm.IsDarkTheme()) - { - // 深色模式三色渐变 - color1 = Color.FromArgb(128, 128, 128); // 顶部颜色 - color2 = Color.FromArgb(56, 56, 56); // 中间颜色 - color3 = Color.FromArgb(128, 128, 128); // 底部颜色 - } - else - { - // 浅色模式三色渐变 - color1 = Color.FromArgb(255, 255, 255); // 顶部颜色 - color2 = Color.FromArgb(230, 230, 230); // 中间颜色 - color3 = Color.FromArgb(255, 255, 255); // 底部颜色 - } + // 使用DarkModeHelper中的颜色 + Color color1 = DarkModeHelper.ToolBarGradientTop; + Color color2 = DarkModeHelper.ToolBarGradientMiddle; + Color color3 = DarkModeHelper.ToolBarGradientBottom; // 创建三色渐变 - using (var brush = new System.Drawing.Drawing2D.LinearGradientBrush( - rect, Color.Empty, Color.Empty, System.Drawing.Drawing2D.LinearGradientMode.Vertical)) + using (var brush = new LinearGradientBrush( + rect, Color.Empty, Color.Empty, LinearGradientMode.Vertical)) { // 使用ColorBlend创建三色渐变 - var colorBlend = new System.Drawing.Drawing2D.ColorBlend(3); + var colorBlend = new ColorBlend(3); colorBlend.Colors = new Color[] { color1, color2, color3 }; colorBlend.Positions = new float[] { 0f, 0.5f, 1f }; brush.InterpolationColors = colorBlend; @@ -272,12 +186,32 @@ protected override void OnPaintBackground(PaintEventArgs e) e.Graphics.FillRectangle(brush, rect); } } - - protected override void OnResize(EventArgs e) + + // 重写Controls属性以保持向后兼容(注意:这可能会影响一些代码) + public new Control.ControlCollection Controls { - base.OnResize(e); - // 调整搜索面板位置到右侧 - AdjustSearchBoxPosition(); + get + { + // 返回包含所有子控件的集合 + return base.Controls; + } + } + + // 主题变化事件处理 + private void OnThemeChanged(object sender, EventArgs e) + { + BackColor = DarkModeHelper.TitleArea; + ForeColor = DarkModeHelper.FormFore; + Invalidate(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + DarkModeHelper.ThemeChanged -= OnThemeChanged; + } + base.Dispose(disposing); } } @@ -293,7 +227,7 @@ public MyToolBarButton(Image image, string text) { SuspendLayout(); DoubleBuffered = true; - ForeColor = MyMainForm.FormFore; + ForeColor = DarkModeHelper.FormFore; BackColor = Color.Transparent; Cursor = Cursors.Hand; Size = new Size(72, 72).DpiZoom(); @@ -324,10 +258,11 @@ public MyToolBarButton(Image image, string text) readonly Label lblText = new Label { - ForeColor = MyMainForm.FormFore, + ForeColor = DarkModeHelper.FormFore, BackColor = Color.Transparent, Font = SystemFonts.MenuFont, AutoSize = true, + Anchor = AnchorStyles.Left | AnchorStyles.Right }; public Image Image @@ -342,6 +277,8 @@ public Image Image set => lblText.Text = value; } + public bool CanBeSelected = true; + private float opacity; public float Opacity { get => currentOpacity; @@ -361,14 +298,10 @@ protected override void OnPaint(PaintEventArgs e) base.OnPaint(e); // 创建圆角矩形路径 - using (var path = CreateRoundedRectanglePath(ClientRectangle, borderRadius)) + using (var path = DarkModeHelper.CreateRoundedRectanglePath(ClientRectangle, borderRadius)) { // 根据当前模式选择颜色 - bool isDarkMode = false; - if (Parent?.Parent is MyToolBar toolbar) - { - isDarkMode = MyMainForm.IsDarkTheme(); - } + bool isDarkMode = DarkModeHelper.IsDarkTheme; // 深色模式使用白色,浅色模式使用黑色 Color baseColor = isDarkMode ? Color.White : Color.Black; @@ -392,11 +325,7 @@ protected override void OnPaint(PaintEventArgs e) // 更新文字颜色的方法 public void UpdateTextColor() { - bool isDarkMode = false; - if (Parent?.Parent is MyToolBar toolbar) - { - isDarkMode = MyMainForm.IsDarkTheme(); - } + bool isDarkMode = DarkModeHelper.IsDarkTheme; // 浅色模式下,当按钮被选中或悬停时,文字颜色改为白色 if (!isDarkMode && currentOpacity > 0.1f) @@ -405,22 +334,10 @@ public void UpdateTextColor() } else { - lblText.ForeColor = MyMainForm.FormFore; + lblText.ForeColor = DarkModeHelper.FormFore; } } - // 创建圆角矩形路径的辅助方法 - private GraphicsPath CreateRoundedRectanglePath(Rectangle rect, int radius) - { - var path = new GraphicsPath(); - path.AddArc(rect.X, rect.Y, radius * 2, radius * 2, 180, 90); - path.AddArc(rect.Right - radius * 2, rect.Y, radius * 2, radius * 2, 270, 90); - path.AddArc(rect.Right - radius * 2, rect.Bottom - radius * 2, radius * 2, radius * 2, 0, 90); - path.AddArc(rect.X, rect.Bottom - radius * 2, radius * 2, radius * 2, 90, 90); - path.CloseFigure(); - return path; - } - private void UpdateAnimation() { currentOpacity += (targetOpacity - currentOpacity) * AnimationSpeed; @@ -440,8 +357,6 @@ private void UpdateAnimation() this.Update(); } - public bool CanBeSelected { get; set; } = true; - protected override void OnResize(EventArgs e) { base.OnResize(e); @@ -460,5 +375,15 @@ protected override CreateParams CreateParams return cp; } } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + animationTimer?.Stop(); + animationTimer?.Dispose(); + } + base.Dispose(disposing); + } } } \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Controls/PictureButton.cs b/ContextMenuManager/BluePointLilac.Controls/PictureButton.cs index db8670a4..4ef0a984 100644 --- a/ContextMenuManager/BluePointLilac.Controls/PictureButton.cs +++ b/ContextMenuManager/BluePointLilac.Controls/PictureButton.cs @@ -1,4 +1,5 @@ using System; +using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; @@ -10,15 +11,18 @@ public class PictureButton : PictureBox private Timer animationTimer; private float currentOpacity = 0f; private float targetOpacity = 0f; - private const float ANIMATION_SPEED = 0.1f; - + private const float ANIMATION_SPEED = 0.1f; + public PictureButton(Image image) { BaseImage = image; SizeMode = PictureBoxSizeMode.AutoSize; - Cursor = Cursors.Hand; - - // 初始化动画计时器 + Cursor = Cursors.Hand; + + // 监听主题变化 + DarkModeHelper.ThemeChanged += OnThemeChanged; + + // 初始化动画计时器 animationTimer = new Timer(); animationTimer.Interval = 16; // ~60 FPS animationTimer.Tick += AnimationTimer_Tick; @@ -53,8 +57,8 @@ protected override void OnMouseLeave(EventArgs e) protected override void OnMouseDown(MouseEventArgs e) { if (e.Button == MouseButtons.Left) base.OnMouseDown(e); - } - + } + private void AnimationTimer_Tick(object sender, EventArgs e) { // 逐步接近目标不透明度 @@ -72,55 +76,67 @@ private void AnimationTimer_Tick(object sender, EventArgs e) { animationTimer.Stop(); return; - } - - // 创建混合图像 + } + + // 创建混合图像 Image normalImage = BaseImage; - Image disabledImage = CreateDisabledImage(BaseImage); - - // 创建一个临时位图来绘制混合效果 + Image disabledImage = CreateDisabledImage(BaseImage); + + // 创建一个临时位图来绘制混合效果 Bitmap mixedImage = new Bitmap(normalImage.Width, normalImage.Height); using (Graphics g = Graphics.FromImage(mixedImage)) { // 先绘制禁用效果的图像 - g.DrawImage(disabledImage, 0, 0); - - // 然后根据当前不透明度绘制正常图像 + g.DrawImage(disabledImage, 0, 0); + + // 然后根据当前不透明度绘制正常图像 float opacity = Math.Max(0, Math.Min(1, currentOpacity)); ColorMatrix matrix = new ColorMatrix(); matrix.Matrix33 = opacity; // 设置透明度 ImageAttributes attributes = new ImageAttributes(); - attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); - + attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); + g.DrawImage( - normalImage, + normalImage, new Rectangle(0, 0, normalImage.Width, normalImage.Height), 0, 0, normalImage.Width, normalImage.Height, - GraphicsUnit.Pixel, + GraphicsUnit.Pixel, attributes ); - } - - // 更新显示的图像 + } + + // 更新显示的图像 if (Image != null && Image != disabledImage && Image != baseImage) - Image.Dispose(); - - Image = mixedImage; - - // 清理资源 + Image.Dispose(); + + Image = mixedImage; + + // 清理资源 disabledImage.Dispose(); - } - + } + private Image CreateDisabledImage(Image image) { return ToolStripRenderer.CreateDisabledImage(image); - } - - // 添加资源清理 + } + + // 主题变化事件处理 + private void OnThemeChanged(object sender, EventArgs e) + { + // 重新创建禁用效果的图像以适应主题变化 + if (baseImage != null) + { + Image = CreateDisabledImage(baseImage); + } + } + + // 添加资源清理 protected override void Dispose(bool disposing) { if (disposing) { + DarkModeHelper.ThemeChanged -= OnThemeChanged; + animationTimer?.Stop(); animationTimer?.Dispose(); } diff --git a/ContextMenuManager/BluePointLilac.Controls/RComboBox.cs b/ContextMenuManager/BluePointLilac.Controls/RComboBox.cs new file mode 100644 index 00000000..9d5c04aa --- /dev/null +++ b/ContextMenuManager/BluePointLilac.Controls/RComboBox.cs @@ -0,0 +1,341 @@ +using BluePointLilac.Methods; +using System; +using System.ComponentModel; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Windows.Forms; + +namespace BluePointLilac.Controls +{ + public class RComboBox : ComboBox + { + private bool mouseOverDropDown = false; + private bool focused = false; + private Timer animTimer; + private float borderWidth = 1.2f, targetWidth = 1.2f; + private Color currentBorder, targetBorder; + private readonly int borderRadius = 14; + + [DefaultValue(typeof(Color), "255, 145, 60")] + public Color HoverColor { get; set; } = Color.FromArgb(255, 145, 60); + + [DefaultValue(typeof(Color), "255, 107, 0")] + public Color FocusColor { get; set; } = Color.FromArgb(255, 107, 0); + + [DefaultValue(typeof(Color), "100, 100, 100")] + public Color ArrowColor { get; set; } = Color.FromArgb(100, 100, 100); + + [DefaultValue(true)] + public bool AutoSize { get; set; } = true; + + [DefaultValue(120)] + public int MinWidth { get; set; } = 120; + + [DefaultValue(400)] + public int MaxWidth { get; set; } = 400; + + [DefaultValue(50)] + public int Padding { get; set; } = 50; + + public RComboBox() + { + SetStyle(ControlStyles.AllPaintingInWmPaint | + ControlStyles.UserPaint | + ControlStyles.ResizeRedraw | + ControlStyles.OptimizedDoubleBuffer, true); + + DrawMode = DrawMode.OwnerDrawFixed; + DropDownStyle = ComboBoxStyle.DropDownList; + FlatStyle = FlatStyle.Flat; + Height = 32.DpiZoom(); + + InitAnimation(); + UpdateColors(); + + DarkModeHelper.ThemeChanged += OnThemeChanged; + + GotFocus += (s, e) => { focused = true; UpdateState(); }; + LostFocus += (s, e) => { focused = false; UpdateState(); }; + MouseEnter += (s, e) => UpdateState(); + MouseLeave += (s, e) => { mouseOverDropDown = false; UpdateState(); }; + MouseMove += (s, e) => UpdateDropDownHoverState(e.Location); + + SelectedIndexChanged += (s, e) => { if (AutoSize) AdjustWidth(); }; + TextChanged += (s, e) => { if (AutoSize) AdjustWidth(); }; + } + + private void InitAnimation() + { + animTimer = new Timer { Interval = 16 }; + animTimer.Tick += (s, e) => { + bool update = false; + if (Math.Abs(borderWidth - targetWidth) > 0.01f) + { + borderWidth += (targetWidth - borderWidth) * 0.3f; + update = true; + } + if (currentBorder != targetBorder) + { + currentBorder = ColorLerp(currentBorder, targetBorder, 0.25f); + update = true; + } + if (update) Invalidate(); + }; + animTimer.Start(); + currentBorder = targetBorder = DarkModeHelper.ComboBoxBorder; + } + + private Color ColorLerp(Color c1, Color c2, float t) => + Color.FromArgb( + (int)(c1.A + (c2.A - c1.A) * t), + (int)(c1.R + (c2.R - c1.R) * t), + (int)(c1.G + (c2.G - c1.G) * t), + (int)(c1.B + (c2.B - c1.B) * t) + ); + + public void UpdateColors() + { + if (IsDisposed) return; + + SafeInvoke(() => + { + BackColor = DarkModeHelper.ComboBoxBack; + ForeColor = DarkModeHelper.ComboBoxFore; + currentBorder = targetBorder = DarkModeHelper.ComboBoxBorder; + ArrowColor = DarkModeHelper.ComboBoxArrow; + }); + } + + private void UpdateState() + { + if (focused) + { + targetWidth = 2.2f; + targetBorder = FocusColor; + } + else if (mouseOverDropDown || ClientRectangle.Contains(PointToClient(MousePosition))) + { + targetWidth = 1.8f; + targetBorder = HoverColor; + } + else + { + targetWidth = 1.2f; + targetBorder = DarkModeHelper.ComboBoxBorder; + } + Invalidate(); + } + + private void UpdateDropDownHoverState(Point location) + { + var dropDownRect = GetDropDownButtonRect(); + bool wasHovered = mouseOverDropDown; + mouseOverDropDown = dropDownRect.Contains(location); + if (wasHovered != mouseOverDropDown) + { + Cursor = mouseOverDropDown ? Cursors.Hand : Cursors.Default; + UpdateState(); + } + } + + private Rectangle GetDropDownButtonRect() + { + var clientRect = ClientRectangle; + var dropDownButtonWidth = SystemInformation.HorizontalScrollBarArrowWidth + 8; + var dropDownRect = new Rectangle( + clientRect.Right - dropDownButtonWidth, + clientRect.Top, + dropDownButtonWidth, + clientRect.Height + ); + + if (RightToLeft == RightToLeft.Yes) + { + dropDownRect.X = clientRect.Left; + } + + return dropDownRect; + } + + private void AdjustWidth() + { + if (!AutoSize || DesignMode) return; + + string text = SelectedItem?.ToString() ?? Text; + if (string.IsNullOrEmpty(text)) return; + + using (var g = CreateGraphics()) + { + SizeF textSize = g.MeasureString(text, Font); + int requiredWidth = (int)textSize.Width + Padding.DpiZoom(); + int newWidth = Math.Max(MinWidth.DpiZoom(), Math.Min(MaxWidth.DpiZoom(), requiredWidth)); + + if (Width != newWidth) + { + Width = newWidth; + Invalidate(); + } + } + } + + protected override void OnPaint(PaintEventArgs e) + { + var g = e.Graphics; + g.SmoothingMode = SmoothingMode.AntiAlias; + g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; + + if (!DarkModeHelper.IsDarkTheme) + { + using (var p = DarkModeHelper.CreateRoundedRectanglePath(new Rectangle(1, 2, Width - 2, Height - 2), borderRadius.DpiZoom())) + using (var b = new SolidBrush(Color.FromArgb(15, 0, 0, 0))) + g.FillPath(b, p); + } + + var rect = new Rectangle(0, 0, Width - 1, Height - 1); + using (var path = DarkModeHelper.CreateRoundedRectanglePath(rect, borderRadius.DpiZoom())) + { + FillGradient(g, path); + DrawBorder(g, path, currentBorder, borderWidth); + } + + DrawTextAndArrow(g); + } + + private void FillGradient(Graphics g, GraphicsPath path) + { + var r = path.GetBounds(); + Color c1, c2; + if (DarkModeHelper.IsDarkTheme) + { + c1 = Color.FromArgb(50, 50, 53); + c2 = Color.FromArgb(40, 40, 43); + } + else + { + c1 = Color.FromArgb(253, 253, 255); + c2 = Color.FromArgb(247, 247, 249); + } + + using (var brush = new LinearGradientBrush(new PointF(r.X, r.Y), new PointF(r.X, r.Bottom), c1, c2)) + { + brush.InterpolationColors = new ColorBlend + { + Positions = new[] { 0f, 0.5f, 1f }, + Colors = new[] { c1, Color.FromArgb((c1.R + c2.R) / 2, (c1.G + c2.G) / 2, (c1.B + c2.B) / 2), c2 } + }; + g.FillPath(brush, path); + } + } + + private void DrawBorder(Graphics g, GraphicsPath path, Color color, float width) + { + using (var pen = new Pen(color, width) { Alignment = PenAlignment.Center, LineJoin = LineJoin.Round }) + g.DrawPath(pen, path); + } + + private void DrawTextAndArrow(Graphics g) + { + if (SelectedItem != null || !string.IsNullOrEmpty(Text)) + { + string text = SelectedItem?.ToString() ?? Text; + using (var brush = new SolidBrush(ForeColor)) + { + var textRect = new Rectangle( + 16.DpiZoom(), + 4.DpiZoom(), + Width - GetDropDownButtonRect().Width - 20.DpiZoom(), + Height - 8.DpiZoom() + ); + var format = new StringFormat + { + LineAlignment = StringAlignment.Center, + Alignment = StringAlignment.Near, + Trimming = StringTrimming.EllipsisCharacter + }; + g.DrawString(text, Font, brush, textRect, format); + } + } + + DrawDropdownArrow(g); + } + + private void DrawDropdownArrow(Graphics g) + { + var dropDownRect = GetDropDownButtonRect(); + var currentArrowColor = mouseOverDropDown ? FocusColor : + focused ? FocusColor : + ArrowColor; + + var middle = new Point( + dropDownRect.Left + dropDownRect.Width / 2, + dropDownRect.Top + dropDownRect.Height / 2 + ); + + int arrowSize = 6.DpiZoom(); + var arrowPoints = new Point[] + { + new Point(middle.X - arrowSize, middle.Y - arrowSize / 2), + new Point(middle.X + arrowSize, middle.Y - arrowSize / 2), + new Point(middle.X, middle.Y + arrowSize / 2) + }; + + using (var brush = new SolidBrush(currentArrowColor)) + g.FillPolygon(brush, arrowPoints); + } + + protected override void OnDrawItem(DrawItemEventArgs e) + { + if (e.Index < 0) return; + + if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) + e.Graphics.FillRectangle(new SolidBrush(SystemColors.Highlight), e.Bounds); + else + e.Graphics.FillRectangle(new SolidBrush(BackColor), e.Bounds); + + string text = GetItemText(Items[e.Index]); + using (var brush = new SolidBrush((e.State & DrawItemState.Selected) == DrawItemState.Selected ? SystemColors.HighlightText : ForeColor)) + { + var rect = e.Bounds; + rect.X += 4; + e.Graphics.DrawString(text, Font, brush, rect, new StringFormat { LineAlignment = StringAlignment.Center }); + } + + if ((e.State & DrawItemState.Focus) == DrawItemState.Focus) + e.DrawFocusRectangle(); + } + + private void SafeInvoke(Action action) + { + if (IsDisposed || !IsHandleCreated) return; + if (InvokeRequired) + { + try { Invoke(action); } + catch { /* 忽略调用异常 */ } + } + else action(); + } + + private void OnThemeChanged(object sender, EventArgs e) => SafeInvoke(() => { UpdateColors(); Invalidate(); }); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + DarkModeHelper.ThemeChanged -= OnThemeChanged; + animTimer?.Stop(); + animTimer?.Dispose(); + } + base.Dispose(disposing); + } + + protected override void OnResize(EventArgs e) { base.OnResize(e); Invalidate(); } + + protected override void OnHandleCreated(EventArgs e) + { + base.OnHandleCreated(e); + if (!DesignMode && AutoSize) AdjustWidth(); + } + + protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); if (AutoSize) AdjustWidth(); } + } +} \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Controls/ReadOnlyTextBox.cs b/ContextMenuManager/BluePointLilac.Controls/ReadOnlyTextBox.cs index 35fc8fda..9eb6791d 100644 --- a/ContextMenuManager/BluePointLilac.Controls/ReadOnlyTextBox.cs +++ b/ContextMenuManager/BluePointLilac.Controls/ReadOnlyTextBox.cs @@ -1,4 +1,4 @@ -using BluePointLilac.Methods; +using BluePointLilac.Methods; using System; using System.Drawing; using System.Windows.Forms; @@ -12,17 +12,20 @@ public ReadOnlyTextBox() ReadOnly = true; Multiline = true; ShortcutsEnabled = false; - ForeColor = MyMainForm.FormFore; - BackColor = MyMainForm.FormBack; + ForeColor = DarkModeHelper.FormFore; + BackColor = DarkModeHelper.FormBack; Font = SystemFonts.MenuFont; Font = new Font(Font.FontFamily, Font.Size + 1F); + + // 监听主题变化 + DarkModeHelper.ThemeChanged += OnThemeChanged; } const int WM_SETFOCUS = 0x0007; const int WM_KILLFOCUS = 0x0008; protected override void WndProc(ref Message m) { - switch (m.Msg) + switch(m.Msg) { case WM_SETFOCUS: m.Msg = WM_KILLFOCUS; break; @@ -35,9 +38,25 @@ protected override void WndProc(ref Message m) protected override void OnMouseEnter(EventArgs e) { base.OnMouseEnter(e); - if (firstEnter) Focus(); + if(firstEnter) Focus(); firstEnter = false; } + + // 主题变化事件处理 + private void OnThemeChanged(object sender, EventArgs e) + { + ForeColor = DarkModeHelper.FormFore; + BackColor = DarkModeHelper.FormBack; + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + DarkModeHelper.ThemeChanged -= OnThemeChanged; + } + base.Dispose(disposing); + } } public sealed class ReadOnlyRichTextBox : RichTextBox @@ -47,10 +66,13 @@ public ReadOnlyRichTextBox() ReadOnly = true; Dock = DockStyle.Fill; BorderStyle = BorderStyle.None; - ForeColor = MyMainForm.FormFore; - BackColor = MyMainForm.FormBack; + ForeColor = DarkModeHelper.FormFore; + BackColor = DarkModeHelper.FormBack; Font = SystemFonts.MenuFont; Font = new Font(Font.FontFamily, Font.Size + 1F); + + // 监听主题变化 + DarkModeHelper.ThemeChanged += OnThemeChanged; } const int WM_SETFOCUS = 0x0007; @@ -58,7 +80,7 @@ public ReadOnlyRichTextBox() protected override void WndProc(ref Message m) { - switch (m.Msg) + switch(m.Msg) { case WM_SETFOCUS: m.Msg = WM_KILLFOCUS; break; @@ -71,7 +93,7 @@ protected override void WndProc(ref Message m) protected override void OnMouseEnter(EventArgs e) { base.OnMouseEnter(e); - if (firstEnter) Focus(); + if(firstEnter) Focus(); firstEnter = false; } @@ -80,5 +102,21 @@ protected override void OnLinkClicked(LinkClickedEventArgs e) base.OnLinkClicked(e); ExternalProgram.OpenWebUrl(e.LinkText); } + + // 主题变化事件处理 + private void OnThemeChanged(object sender, EventArgs e) + { + ForeColor = DarkModeHelper.FormFore; + BackColor = DarkModeHelper.FormBack; + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + DarkModeHelper.ThemeChanged -= OnThemeChanged; + } + base.Dispose(disposing); + } } } \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Controls/ResizeLimitedForm.cs b/ContextMenuManager/BluePointLilac.Controls/ResizeLimitedForm.cs index eacb7e74..7eceb170 100644 --- a/ContextMenuManager/BluePointLilac.Controls/ResizeLimitedForm.cs +++ b/ContextMenuManager/BluePointLilac.Controls/ResizeLimitedForm.cs @@ -1,4 +1,5 @@ -using System; +using BluePointLilac.Methods; +using System; using System.Windows.Forms; namespace BluePointLilac.Controls @@ -15,33 +16,61 @@ public class ResizeLimitedForm : RForm public ResizeLimitedForm() { InitTheme(); + + // 监听主题变化 + DarkModeHelper.ThemeChanged += OnThemeChanged; } protected override void WndProc(ref Message m) { base.WndProc(ref m); - if (m.Msg == WM_NCHITTEST && WindowState == FormWindowState.Normal) + if(m.Msg == WM_NCHITTEST && WindowState == FormWindowState.Normal) { IntPtr hNowhere = new IntPtr((int)HitTest.Nowhere); - switch ((HitTest)m.Result) + switch((HitTest)m.Result) { case HitTest.Top: case HitTest.Bottom: - if (!VerticalResizable) m.Result = hNowhere; + if(!VerticalResizable) m.Result = hNowhere; break; case HitTest.Left: case HitTest.Right: - if (!HorizontalResizable) m.Result = hNowhere; + if(!HorizontalResizable) m.Result = hNowhere; break; case HitTest.TopLeft: case HitTest.TopRight: case HitTest.BottomLeft: case HitTest.BottomRight: - if (!VerticalResizable || !HorizontalResizable) m.Result = hNowhere; + if(!VerticalResizable || !HorizontalResizable) m.Result = hNowhere; break; } } } + + private void InitTheme() + { + BackColor = DarkModeHelper.FormBack; + ForeColor = DarkModeHelper.FormFore; + + // 应用深色模式标题栏 + DarkModeHelper.ApplyDarkModeToForm(this); + } + + // 主题变化事件处理 + private void OnThemeChanged(object sender, EventArgs e) + { + InitTheme(); + Invalidate(); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + DarkModeHelper.ThemeChanged -= OnThemeChanged; + } + base.Dispose(disposing); + } const int WM_NCHITTEST = 0x84;//光标移动或鼠标按下、释放时的消息 /// 鼠标击中位置 diff --git a/ContextMenuManager/BluePointLilac.Controls/SearchBox.cs b/ContextMenuManager/BluePointLilac.Controls/SearchBox.cs index 7118d16f..29dc90e1 100644 --- a/ContextMenuManager/BluePointLilac.Controls/SearchBox.cs +++ b/ContextMenuManager/BluePointLilac.Controls/SearchBox.cs @@ -1,562 +1,201 @@ -using BluePointLilac.Methods; -using ContextMenuManager.Methods; -using Svg; -using System; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Drawing.Imaging; -using System.Windows.Forms; - -namespace BluePointLilac.Controls -{ - public class ModernSearchBox : Panel - { - private TextBox searchTextBox; - private bool isFocused = false; - private bool isMouseOverIcon = false; - private int borderRadius = 14; - private Color borderColor, hoverBorderColor, focusBorderColor, backgroundColor, textColor; - private Rectangle iconRect; - private Bitmap cachedIconBitmap; - private Color lastIconColor = Color.Empty; - - // 动画相关变量 - private Timer animationTimer; - private float currentBorderWidth = 1.2f; - private float targetBorderWidth = 1.2f; - private Color currentBorderColor; - private Color targetBorderColor; - private float iconScale = 1.0f; - private float targetIconScale = 1.0f; - private float focusGlowAlpha = 0f; - private float targetFocusGlowAlpha = 0f; - - private readonly Color orangePrimary = Color.FromArgb(255, 107, 0); - private readonly Color orangeLight = Color.FromArgb(255, 145, 60); - private readonly Color orangeDark = Color.FromArgb(220, 85, 0); - private readonly Color subtleShadow = Color.FromArgb(15, 0, 0, 0); - private readonly Color focusGlowColor = Color.FromArgb(80, 255, 145, 60); - - public event EventHandler SearchPerformed; - - public ModernSearchBox() - { - DoubleBuffered = true; - SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.ResizeRedraw | - ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | - ControlStyles.OptimizedDoubleBuffer, true); - - InitializeComponent(); - InitializeAnimation(); - UpdateIconRect(); - Application.AddMessageFilter(new GlobalMouseMessageFilter(this)); - } - - public string SearchText - { - get => searchTextBox.Text; - set => searchTextBox.Text = value; - } - - private void InitializeAnimation() - { - animationTimer = new Timer - { - Interval = 16 // ~60 FPS - }; - animationTimer.Tick += (s, e) => UpdateAnimation(); - animationTimer.Start(); - - // 初始化动画状态 - currentBorderColor = borderColor; - targetBorderColor = borderColor; - } - - private void UpdateAnimation() - { - bool needsInvalidate = false; - - // 边框宽度动画 - if (Math.Abs(currentBorderWidth - targetBorderWidth) > 0.01f) - { - currentBorderWidth = Lerp(currentBorderWidth, targetBorderWidth, 0.3f); - needsInvalidate = true; - } - - // 边框颜色动画 - if (currentBorderColor != targetBorderColor) - { - currentBorderColor = ColorLerp(currentBorderColor, targetBorderColor, 0.25f); - needsInvalidate = true; - } - - // 图标缩放动画 - if (Math.Abs(iconScale - targetIconScale) > 0.01f) - { - iconScale = Lerp(iconScale, targetIconScale, 0.4f); - needsInvalidate = true; - } - - // 焦点光晕动画 - if (Math.Abs(focusGlowAlpha - targetFocusGlowAlpha) > 0.01f) - { - focusGlowAlpha = Lerp(focusGlowAlpha, targetFocusGlowAlpha, 0.2f); - needsInvalidate = true; - } - - if (needsInvalidate) - { - Invalidate(); - } - } - - private float Lerp(float a, float b, float t) - { - return a + (b - a) * t; - } - - private Color ColorLerp(Color color1, Color color2, float t) - { - var r = (int)(color1.R + (color2.R - color1.R) * t); - var g = (int)(color1.G + (color2.G - color1.G) * t); - var b = (int)(color1.B + (color2.B - color1.B) * t); - var a = (int)(color1.A + (color2.A - color1.A) * t); - return Color.FromArgb(a, r, g, b); - } - - private void InitializeComponent() - { - Size = new Size(260.DpiZoom(), 40.DpiZoom()); - - searchTextBox = new TextBox - { - Location = new Point(16.DpiZoom(), 10.DpiZoom()), - Size = new Size(200.DpiZoom(), 22.DpiZoom()), - Font = new Font("Segoe UI", 9.5F, FontStyle.Regular), - PlaceholderText = AppString.Other.SearchContent, - BorderStyle = BorderStyle.None - }; - - searchTextBox.SetStyle(ControlStyles.SupportsTransparentBackColor | - ControlStyles.OptimizedDoubleBuffer | - ControlStyles.AllPaintingInWmPaint, true); - - searchTextBox.GotFocus += (s, e) => - { - isFocused = true; - UpdateAnimationTargets(); - Invalidate(); - }; - searchTextBox.LostFocus += (s, e) => - { - isFocused = false; - UpdateAnimationTargets(); - Invalidate(); - }; - searchTextBox.TextChanged += (s, e) => Invalidate(); - searchTextBox.KeyDown += (s, e) => - { - if (e.KeyCode == Keys.Enter) - { - PerformSearchWithAnimation(); - e.Handled = e.SuppressKeyPress = true; - } - }; - - Controls.Add(searchTextBox); - - MouseEnter += (s, e) => - { - UpdateAnimationTargets(); - Invalidate(); - }; - MouseLeave += (s, e) => - { - isMouseOverIcon = false; - UpdateAnimationTargets(); - Invalidate(); - }; - MouseMove += (s, e) => - { - bool wasOverIcon = isMouseOverIcon; - isMouseOverIcon = iconRect.Contains(e.Location); - if (wasOverIcon != isMouseOverIcon) - { - Cursor = isMouseOverIcon ? Cursors.Hand : Cursors.Default; - UpdateAnimationTargets(); - Invalidate(); - } - }; - MouseClick += (s, e) => - { - if (iconRect.Contains(e.Location) && e.Button == MouseButtons.Left) - PerformSearchWithAnimation(); - }; - - searchTextBox.MouseEnter += (s, e) => - { - UpdateAnimationTargets(); - Invalidate(); - }; - searchTextBox.MouseLeave += (s, e) => - { - UpdateAnimationTargets(); - Invalidate(); - }; - - InitializeColors(); - } - - private void UpdateAnimationTargets() - { - // 更新边框宽度目标值 - if (isFocused) - { - targetBorderWidth = 2.2f; - targetFocusGlowAlpha = 1.0f; - } - else if (ClientRectangle.Contains(PointToClient(MousePosition)) || isMouseOverIcon) - { - targetBorderWidth = 1.8f; - targetFocusGlowAlpha = 0f; - } - else - { - targetBorderWidth = 1.2f; - targetFocusGlowAlpha = 0f; - } - - // 更新边框颜色目标值 - if (isFocused) - { - targetBorderColor = focusBorderColor; - } - else if (ClientRectangle.Contains(PointToClient(MousePosition)) || isMouseOverIcon) - { - targetBorderColor = hoverBorderColor; - } - else - { - targetBorderColor = borderColor; - } - - // 更新图标缩放目标值 - if (isMouseOverIcon) - { - targetIconScale = 1.1f; - } - else - { - targetIconScale = 1.0f; - } - } - - private void InitializeColors() - { - if (MyMainForm.IsDarkTheme()) - { - backgroundColor = Color.FromArgb(45, 45, 48); - textColor = Color.FromArgb(245, 245, 245); - borderColor = Color.FromArgb(70, 70, 75); - hoverBorderColor = orangeLight; - focusBorderColor = orangePrimary; - } - else - { - backgroundColor = Color.FromArgb(250, 250, 252); - textColor = Color.FromArgb(25, 25, 25); - borderColor = Color.FromArgb(210, 210, 215); - hoverBorderColor = orangeLight; - focusBorderColor = orangePrimary; - } - - if (searchTextBox != null) - { - searchTextBox.ForeColor = textColor; - searchTextBox.BackColor = backgroundColor; - } - - // 初始化动画颜色 - currentBorderColor = borderColor; - targetBorderColor = borderColor; - } - - private void UpdateIconRect() - { - int iconSize = (int)(18.DpiZoom() * iconScale); - int margin = 12.DpiZoom(); - int y = (Height - iconSize) / 2; - int x = Math.Max(margin, Width - iconSize - margin); - iconRect = new Rectangle(x, y, iconSize, iconSize); - } - - private void PerformSearch() => SearchPerformed?.Invoke(this, EventArgs.Empty); - - private async void PerformSearchWithAnimation() - { - // 图标点击动画 - targetIconScale = 0.8f; - await System.Threading.Tasks.Task.Delay(100); - targetIconScale = 1.0f; - - PerformSearch(); - } - - protected override void OnPaint(PaintEventArgs e) - { - var g = e.Graphics; - g.SmoothingMode = SmoothingMode.AntiAlias; - g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; - - if (!MyMainForm.IsDarkTheme()) - { - using (var shadowPath = CreateRoundedRectanglePath(new Rectangle(1, 2, Width - 2, Height - 2), borderRadius.DpiZoom())) - using (var shadowBrush = new SolidBrush(subtleShadow)) - g.FillPath(shadowBrush, shadowPath); - } - - // 绘制焦点光晕效果 - if (focusGlowAlpha > 0.01f) - { - using (var glowPath = CreateRoundedRectanglePath(new Rectangle(-2, -2, Width + 3, Height + 3), (borderRadius + 2).DpiZoom())) - using (var glowBrush = new SolidBrush(Color.FromArgb((int)(focusGlowAlpha * 80), focusGlowColor))) - { - g.FillPath(glowBrush, glowPath); - } - } - - var drawRect = new Rectangle(0, 0, Width - 1, Height - 1); - using (var path = CreateRoundedRectanglePath(drawRect, borderRadius.DpiZoom())) - { - FillGradientBackground(g, path); - DrawRefinedBorder(g, path, currentBorderColor, currentBorderWidth); - } - - DrawSearchIcon(g, iconRect); - } - - private void FillGradientBackground(Graphics g, GraphicsPath path) - { - var rect = path.GetBounds(); - Color color1, color2; - - if (MyMainForm.IsDarkTheme()) - { - color1 = Color.FromArgb(50, 50, 53); - color2 = Color.FromArgb(40, 40, 43); - } - else - { - color1 = Color.FromArgb(253, 253, 255); - color2 = Color.FromArgb(247, 247, 249); - } - - using (var brush = new LinearGradientBrush(new PointF(rect.X, rect.Y), new PointF(rect.X, rect.Bottom), color1, color2)) - { - var blend = new ColorBlend - { - Positions = new[] { 0f, 0.5f, 1f }, - Colors = new[] { color1, Color.FromArgb((color1.R + color2.R) / 2, (color1.G + color2.G) / 2, (color1.B + color2.B) / 2), color2 } - }; - brush.InterpolationColors = blend; - g.FillPath(brush, path); - } - } - - private void DrawRefinedBorder(Graphics g, GraphicsPath path, Color borderColor, float borderWidth) - { - using (var pen = new Pen(borderColor, borderWidth)) - { - pen.Alignment = PenAlignment.Center; - pen.LineJoin = LineJoin.Round; - g.DrawPath(pen, path); - } - } - - private void DrawSearchIcon(Graphics g, Rectangle iconRect) - { - if (iconRect.Right > Width || iconRect.Bottom > Height || iconRect.Width <= 0 || iconRect.Height <= 0) - UpdateIconRect(); - - var iconColor = isMouseOverIcon ? orangeDark : - isFocused ? focusBorderColor : - ClientRectangle.Contains(PointToClient(MousePosition)) ? hoverBorderColor : - borderColor; - - if (cachedIconBitmap == null || lastIconColor != iconColor || - cachedIconBitmap?.Width != iconRect.Width || cachedIconBitmap?.Height != iconRect.Height) - { - cachedIconBitmap?.Dispose(); - cachedIconBitmap = GenerateModernSearchIcon(iconRect.Size, iconColor); - lastIconColor = iconColor; - } - - if (cachedIconBitmap != null) - { - // 应用图标缩放变换 - var scaledRect = new Rectangle( - iconRect.X + (int)(iconRect.Width * (1 - iconScale) / 2), - iconRect.Y + (int)(iconRect.Height * (1 - iconScale) / 2), - (int)(iconRect.Width * iconScale), - (int)(iconRect.Height * iconScale) - ); - g.DrawImage(cachedIconBitmap, scaledRect); - } - } - - private Bitmap GenerateModernSearchIcon(Size size, Color color) - { - try - { - if (size.Width <= 0 || size.Height <= 0) - size = new Size(18.DpiZoom(), 18.DpiZoom()); - - var svgDocument = new SvgDocument - { - Width = size.Width, - Height = size.Height, - ViewBox = new SvgViewBox(0, 0, 24, 24) - }; - - var searchPath = new SvgPath - { - PathData = SvgPathBuilder.Parse("M15.5 14h-.79l-.28-.27A6.471 6.471 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"), - Fill = new SvgColourServer(Color.Transparent), - Stroke = new SvgColourServer(color), - StrokeWidth = 1.8f, - StrokeLineCap = SvgStrokeLineCap.Round, - StrokeLineJoin = SvgStrokeLineJoin.Round - }; - - svgDocument.Children.Add(searchPath); - return svgDocument.Draw(size.Width, size.Height); - } - catch - { - return GenerateModernFallbackIcon(size, color); - } - } - - private Bitmap GenerateModernFallbackIcon(Size size, Color color) - { - if (size.Width < 16) size = new Size(16, size.Height); - if (size.Height < 16) size = new Size(size.Width, 16); - - var bitmap = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb); - using (var g = Graphics.FromImage(bitmap)) - { - g.SmoothingMode = SmoothingMode.AntiAlias; - int margin = Math.Max(2, size.Width / 8); - int drawSize = Math.Min(size.Width, size.Height) - margin * 2; - if (drawSize < 8) drawSize = 8; - - int x = (size.Width - drawSize) / 2; - int y = (size.Height - drawSize) / 2; - - using (var pen = new Pen(color, Math.Max(1.6f, drawSize / 10f))) - { - pen.StartCap = LineCap.Round; - int circleDiameter = (int)(drawSize * 0.65f); - if (circleDiameter < 6) circleDiameter = 6; - - int circleX = x + (drawSize - circleDiameter) / 2; - int circleY = y + (drawSize - circleDiameter) / 2; - - RectangleF circleRect = new RectangleF(circleX + pen.Width / 2, circleY + pen.Width / 2, - circleDiameter - pen.Width, circleDiameter - pen.Width); - g.DrawEllipse(pen, circleRect); - - float angle = 45f; - float handleLength = drawSize * 0.35f; - if (handleLength < 4) handleLength = 4; - - double radian = angle * Math.PI / 180; - float centerX = circleX + circleDiameter / 2f; - float centerY = circleY + circleDiameter / 2f; - float radius = circleDiameter / 2f; - - float startX = centerX + (float)(radius * Math.Cos(radian)); - float startY = centerY + (float)(radius * Math.Sin(radian)); - float endX = startX + (float)(handleLength * Math.Cos(radian)); - float endY = startY + (float)(handleLength * Math.Sin(radian)); - - g.DrawLine(pen, startX, startY, endX, endY); - } - } - return bitmap; - } - - private GraphicsPath CreateRoundedRectanglePath(Rectangle rect, int radius) - { - var path = new GraphicsPath(); - float diameter = radius * 2f; - - path.AddArc(rect.X, rect.Y, diameter, diameter, 180, 90); - path.AddArc(rect.Right - diameter, rect.Y, diameter, diameter, 270, 90); - path.AddArc(rect.Right - diameter, rect.Bottom - diameter, diameter, diameter, 0, 90); - path.AddArc(rect.X, rect.Bottom - diameter, diameter, diameter, 90, 90); - - path.CloseFigure(); - return path; - } - - protected override void Dispose(bool disposing) - { - if (disposing) - { - animationTimer?.Stop(); - animationTimer?.Dispose(); - cachedIconBitmap?.Dispose(); - } - base.Dispose(disposing); - } - - public void FocusSearch() { searchTextBox?.Focus(); searchTextBox?.SelectAll(); } - public void ClearSearch() { searchTextBox.Text = string.Empty; } - public void LoseFocus() { Parent?.Focus(); } - public TextBox GetTextBox() { return searchTextBox; } - - protected override void OnResize(EventArgs e) - { - base.OnResize(e); - if (searchTextBox != null && !searchTextBox.IsDisposed) - { - int iconAreaWidth = 50.DpiZoom(); - searchTextBox.Width = Width - iconAreaWidth; - searchTextBox.Height = 22.DpiZoom(); - int textBoxY = (Height - searchTextBox.Height) / 2; - searchTextBox.Location = new Point(12.DpiZoom(), textBoxY); - } - - cachedIconBitmap?.Dispose(); - cachedIconBitmap = null; - UpdateIconRect(); - Invalidate(); - } - - private class GlobalMouseMessageFilter : IMessageFilter - { - private readonly ModernSearchBox searchBox; - public GlobalMouseMessageFilter(ModernSearchBox searchBox) => this.searchBox = searchBox; - - public bool PreFilterMessage(ref Message m) - { - if ((m.Msg == 0x201 || m.Msg == 0x202) && !searchBox.IsMouseInside(searchBox, Control.MousePosition)) - searchBox.LoseFocus(); - return false; - } - } - - private bool IsMouseInside(Control control, Point screenPoint) - { - if (control == null || control.IsDisposed) return false; - Point clientPoint = control.PointToClient(screenPoint); - - if (control.ClientRectangle.Contains(clientPoint)) return true; - foreach (Control child in control.Controls) - if (!child.IsDisposed && IsMouseInside(child, screenPoint)) return true; - - return false; - } - } +using System; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; +using BluePointLilac.Methods; + +namespace BluePointLilac.Controls +{ + public class SearchBox : UserControl + { + private readonly TextBox textBox = new TextBox + { + BorderStyle = BorderStyle.None, + Font = new Font("Segoe UI", 9f), + Multiline = false + }; + + private readonly PictureBox clearButton = new PictureBox + { + Size = new Size(16, 16).DpiZoom(), + Cursor = Cursors.Hand, + SizeMode = PictureBoxSizeMode.StretchImage, + Visible = false, + BackColor = Color.Transparent + }; + + [Category("外观"), Description("占位符文本")] + public string PlaceholderText { get; set; } = "搜索..."; + + [Category("外观"), Description("是否显示清除按钮"), DefaultValue(true)] + public bool ShowClearButton { get; set; } = true; + + [Browsable(false)] + public new string Text + { + get => textBox.Text; + set { textBox.Text = value; UpdateClearButton(); Invalidate(); } + } + + [Browsable(false)] + public new Font Font + { + get => textBox.Font; + set { textBox.Font = value; AdjustLayout(); } + } + + public new event EventHandler TextChanged + { + add => textBox.TextChanged += value; + remove => textBox.TextChanged -= value; + } + + public SearchBox() + { + SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | + ControlStyles.DoubleBuffer | ControlStyles.ResizeRedraw, true); + + Size = new Size(200, 32.DpiZoom()); + InitializeComponents(); + UpdateThemeColors(); + AdjustLayout(); + + DarkModeHelper.ThemeChanged += OnThemeChanged; + } + + private void InitializeComponents() + { + BackColor = DarkModeHelper.SearchBoxBack; + textBox.BackColor = DarkModeHelper.SearchBoxBack; + textBox.ForeColor = DarkModeHelper.FormFore; + + textBox.TextChanged += (s, e) => { UpdateClearButton(); Invalidate(); }; + textBox.GotFocus += (s, e) => Invalidate(); + textBox.LostFocus += (s, e) => Invalidate(); + textBox.KeyDown += (s, e) => + { + if (e.KeyCode == Keys.Escape && !string.IsNullOrEmpty(textBox.Text)) + { + textBox.Text = string.Empty; + e.Handled = e.SuppressKeyPress = true; + } + }; + + clearButton.Click += (s, e) => + { + textBox.Text = string.Empty; + textBox.Focus(); + }; + + Controls.AddRange(new Control[] { textBox, clearButton }); + } + + private void UpdateThemeColors() + { + BackColor = DarkModeHelper.SearchBoxBack; + textBox.BackColor = DarkModeHelper.SearchBoxBack; + textBox.ForeColor = DarkModeHelper.FormFore; + } + + protected override void OnPaint(PaintEventArgs e) + { + var g = e.Graphics; + var rect = ClientRectangle; + + // 绘制背景 + g.FillRectangle(new SolidBrush(DarkModeHelper.SearchBoxBack), rect); + + // 绘制边框 + var borderRect = rect; + borderRect.Inflate(-1, -1); + g.DrawRectangle(new Pen(DarkModeHelper.GetBorderColor(textBox.ContainsFocus)), borderRect); + + // 绘制搜索图标 + DrawSearchIcon(g); + + // 绘制占位符文本 + if (string.IsNullOrEmpty(textBox.Text) && !string.IsNullOrEmpty(PlaceholderText)) + { + var placeholderRect = new Rectangle(textBox.Left, textBox.Top, textBox.Width, textBox.Height); + TextRenderer.DrawText(g, PlaceholderText, textBox.Font, placeholderRect, + DarkModeHelper.GetPlaceholderColor(), TextFormatFlags.Left | TextFormatFlags.VerticalCenter); + } + } + + private void DrawSearchIcon(Graphics g) + { + var searchIcon = ContextMenuManager.Methods.AppImage.Search; + if (searchIcon != null) + { + int iconSize = 20.DpiZoom(); + int iconY = (Height - iconSize) / 2; + int iconX = 12.DpiZoom(); + + g.DrawImage(searchIcon, iconX, iconY, iconSize, iconSize); + } + } + + private void UpdateClearButton() => + clearButton.Visible = ShowClearButton && !string.IsNullOrEmpty(textBox.Text); + + private void AdjustLayout() + { + if (textBox == null || clearButton == null) return; + + int textBoxHeight = Math.Min(textBox.PreferredHeight, (int)(Height * 0.7f)); + int textBoxY = (Height - textBoxHeight) / 2; + + int textBoxX = 44.DpiZoom(); // 12 + 20 + 12 + int textBoxWidth = Width - textBoxX - 32.DpiZoom(); + + textBox.Location = new Point(textBoxX, textBoxY); + textBox.Size = new Size(textBoxWidth, textBoxHeight); + + int btnSize = 16.DpiZoom(); + clearButton.Location = new Point(Width - 30.DpiZoom(), (Height - btnSize) / 2); + clearButton.Size = new Size(btnSize, btnSize); + } + + protected override void OnResize(EventArgs e) + { + base.OnResize(e); + AdjustLayout(); + Invalidate(); + } + + private void OnThemeChanged(object sender, EventArgs e) + { + UpdateThemeColors(); + Invalidate(); + } + + protected override void OnParentChanged(EventArgs e) + { + base.OnParentChanged(e); + UpdateThemeColors(); + Invalidate(); + } + + public void Clear() => Text = string.Empty; + public void FocusTextBox() => textBox.Focus(); + + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { + if (keyData == (Keys.Control | Keys.F)) + { + FocusTextBox(); + return true; + } + return base.ProcessCmdKey(ref msg, keyData); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + DarkModeHelper.ThemeChanged -= OnThemeChanged; + } + base.Dispose(disposing); + } + } } \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Controls/SelectDialog.cs b/ContextMenuManager/BluePointLilac.Controls/SelectDialog.cs index d94a511c..c02e054b 100644 --- a/ContextMenuManager/BluePointLilac.Controls/SelectDialog.cs +++ b/ContextMenuManager/BluePointLilac.Controls/SelectDialog.cs @@ -1,4 +1,4 @@ -using BluePointLilac.Methods; +using BluePointLilac.Methods; using System; using System.Drawing; using System.Windows.Forms; @@ -17,16 +17,16 @@ public override void Reset() { } protected override bool RunDialog(IntPtr hwndOwner) { - using (SelectForm frm = new SelectForm()) + using(SelectForm frm = new SelectForm()) { frm.Text = Title; frm.Items = Items; - if (Selected != null) frm.Selected = Selected; + if(Selected != null) frm.Selected = Selected; else frm.SelectedIndex = SelectedIndex; frm.CanEdit = CanEdit; if (Control.FromHandle(hwndOwner) is Form owner) frm.TopMost = true; bool flag = frm.ShowDialog() == DialogResult.OK; - if (flag) + if(flag) { Selected = frm.Selected; SelectedIndex = frm.SelectedIndex; @@ -76,7 +76,22 @@ public string[] Items public bool CanEdit { get => cmbItems.DropDownStyle == ComboBoxStyle.DropDown; - set => cmbItems.DropDownStyle = value ? ComboBoxStyle.DropDown : ComboBoxStyle.DropDownList; + set + { + cmbItems.DropDownStyle = value ? ComboBoxStyle.DropDown : ComboBoxStyle.DropDownList; + // 根据 DropDownStyle 设置合适的 AutoCompleteMode + if (value) + { + cmbItems.AutoCompleteMode = AutoCompleteMode.SuggestAppend; + cmbItems.AutoCompleteSource = AutoCompleteSource.ListItems; + } + else + { + // 当 DropDownStyle 是 DropDownList 时,AutoCompleteMode 必须为 None + cmbItems.AutoCompleteMode = AutoCompleteMode.None; + cmbItems.AutoCompleteSource = AutoCompleteSource.None; + } + } } public int SelectedIndex @@ -99,8 +114,8 @@ public int SelectedIndex }; readonly RComboBox cmbItems = new RComboBox { - AutoCompleteMode = AutoCompleteMode.SuggestAppend, - AutoCompleteSource = AutoCompleteSource.ListItems, + // 移除初始化时的 AutoCompleteMode 和 AutoCompleteSource 设置 + // 这些设置将在 CanEdit 属性中根据模式动态设置 DropDownHeight = 294.DpiZoom(), ImeMode = ImeMode.Disable }; diff --git a/ContextMenuManager/BluePointLilac.Controls/UAWebClient.cs b/ContextMenuManager/BluePointLilac.Controls/UAWebClient.cs index 8c8a2731..80a638f6 100644 --- a/ContextMenuManager/BluePointLilac.Controls/UAWebClient.cs +++ b/ContextMenuManager/BluePointLilac.Controls/UAWebClient.cs @@ -57,7 +57,7 @@ public bool WebStringToFile(string filePath, string fileUrl) { string contents = GetWebString(fileUrl); bool flag = contents != null; - if (flag) File.WriteAllText(filePath, contents, Encoding.Unicode); + if(flag) File.WriteAllText(filePath, contents, Encoding.Unicode); return flag; } @@ -67,7 +67,7 @@ public XmlDocument GetWebJsonToXml(string url) try { byte[] bytes = DownloadData(url); - using (XmlReader xReader = JsonReaderWriterFactory.CreateJsonReader(bytes, XmlDictionaryReaderQuotas.Max)) + using(XmlReader xReader = JsonReaderWriterFactory.CreateJsonReader(bytes, XmlDictionaryReaderQuotas.Max)) { XmlDocument doc = new XmlDocument(); doc.Load(xReader); diff --git a/ContextMenuManager/BluePointLilac.Methods/ComboBoxExtension.cs b/ContextMenuManager/BluePointLilac.Methods/ComboBoxExtension.cs index a8aaca82..da323c81 100644 --- a/ContextMenuManager/BluePointLilac.Methods/ComboBoxExtension.cs +++ b/ContextMenuManager/BluePointLilac.Methods/ComboBoxExtension.cs @@ -11,7 +11,7 @@ public static void AutosizeDropDownWidth(this RComboBox box) box.DropDown += (sender, e) => { int maxWidth = 0; - foreach (var item in box.Items) + foreach(var item in box.Items) { maxWidth = Math.Max(maxWidth, TextRenderer.MeasureText(item.ToString(), box.Font).Width); } diff --git a/ContextMenuManager/BluePointLilac.Methods/ControlExtension.cs b/ContextMenuManager/BluePointLilac.Methods/ControlExtension.cs index 176e6fe4..89eb1afa 100644 --- a/ContextMenuManager/BluePointLilac.Methods/ControlExtension.cs +++ b/ContextMenuManager/BluePointLilac.Methods/ControlExtension.cs @@ -20,7 +20,7 @@ public static void CanMoveForm(this Control ctr) const int HT_CAPTION = 0x2; ctr.MouseMove += (sender, e) => { - if (e.Button != MouseButtons.Left) return; + if(e.Button != MouseButtons.Left) return; ReleaseCapture(); PostMessage(ctr.FindForm().Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0); }; @@ -41,7 +41,7 @@ public static void SetEnabled(this Control ctr, bool enabled) const int GWL_STYLE = -16; const int WS_DISABLED = 0x8000000; int value = GetWindowLong(ctr.Handle, GWL_STYLE); - if (enabled) value &= ~WS_DISABLED; + if(enabled) value &= ~WS_DISABLED; else value |= WS_DISABLED; SetWindowLong(ctr.Handle, GWL_STYLE, value); } diff --git a/ContextMenuManager/BluePointLilac.Methods/DirectoryEx.cs b/ContextMenuManager/BluePointLilac.Methods/DirectoryEx.cs index 08db1536..3903c8d1 100644 --- a/ContextMenuManager/BluePointLilac.Methods/DirectoryEx.cs +++ b/ContextMenuManager/BluePointLilac.Methods/DirectoryEx.cs @@ -9,12 +9,12 @@ public static void CopyTo(string srcDirPath, string dstDirPath) DirectoryInfo srcDi = new DirectoryInfo(srcDirPath); DirectoryInfo dstDi = new DirectoryInfo(dstDirPath); dstDi.Create(); - foreach (FileInfo srcFi in srcDi.GetFiles()) + foreach(FileInfo srcFi in srcDi.GetFiles()) { string dstFilePath = $@"{dstDirPath}\{srcFi.Name}"; srcFi.CopyTo(dstFilePath, true); } - foreach (DirectoryInfo srcSubDi in srcDi.GetDirectories()) + foreach(DirectoryInfo srcSubDi in srcDi.GetDirectories()) { DirectoryInfo dstSubDi = dstDi.CreateSubdirectory(srcSubDi.Name); CopyTo(srcSubDi.FullName, dstSubDi.FullName); diff --git a/ContextMenuManager/BluePointLilac.Methods/ElevatedFileDroper.cs b/ContextMenuManager/BluePointLilac.Methods/ElevatedFileDroper.cs index 2d4ef040..8f387670 100644 --- a/ContextMenuManager/BluePointLilac.Methods/ElevatedFileDroper.cs +++ b/ContextMenuManager/BluePointLilac.Methods/ElevatedFileDroper.cs @@ -80,12 +80,12 @@ public ElevatedFileDroper(Control ctr) Application.AddMessageFilter(this); ctr.Disposed += (sender, e) => Application.RemoveMessageFilter(this); - if (ctr is Form frm) + if(ctr is Form frm) { double opacity = frm.Opacity; frm.Paint += (sender, e) => { - if (frm.Opacity != opacity) + if(frm.Opacity != opacity) { //窗体透明度变化时需要重新注册接受文件拖拽标识符 DragAcceptFiles(ctr.Handle, true); @@ -98,12 +98,12 @@ public ElevatedFileDroper(Control ctr) bool isVistaOrHigher = ver >= new Version(6, 0); bool isWin7OrHigher = ver >= new Version(6, 1); var status = new ChangeFilterStruct { CbSize = 8 }; - if (isVistaOrHigher) + if(isVistaOrHigher) { - foreach (uint msg in new[] { WM_DROPFILES, WM_COPYGLOBALDATA, WM_COPYDATA }) + foreach(uint msg in new[] { WM_DROPFILES, WM_COPYGLOBALDATA, WM_COPYDATA }) { bool error = false; - if (isWin7OrHigher) + if(isWin7OrHigher) { error = !ChangeWindowMessageFilterEx(ctr.Handle, msg, ChangeFilterAction.MSGFLT_ALLOW, in status); } @@ -111,22 +111,22 @@ public ElevatedFileDroper(Control ctr) { error = !ChangeWindowMessageFilter(msg, ChangeWindowMessageFilterFlags.MSGFLT_ADD); } - if (error) throw new Win32Exception(Marshal.GetLastWin32Error()); + if(error) throw new Win32Exception(Marshal.GetLastWin32Error()); } } } public bool PreFilterMessage(ref Message m) { - if (m.Msg != WM_DROPFILES) return false; + if(m.Msg != WM_DROPFILES) return false; IntPtr handle = m.WParam; uint fileCount = DragQueryFile(handle, uint.MaxValue, null, 0); string[] filePaths = new string[fileCount]; - for (uint i = 0; i < fileCount; i++) + for(uint i = 0; i < fileCount; i++) { StringBuilder sb = new StringBuilder(260); uint result = DragQueryFile(handle, i, sb, sb.Capacity); - if (result > 0) filePaths[i] = sb.ToString(); + if(result > 0) filePaths[i] = sb.ToString(); } DragQueryPoint(handle, out Point point); DragFinish(handle); diff --git a/ContextMenuManager/BluePointLilac.Methods/EncodingType.cs b/ContextMenuManager/BluePointLilac.Methods/EncodingType.cs index 05e0dcca..1ee084ef 100644 --- a/ContextMenuManager/BluePointLilac.Methods/EncodingType.cs +++ b/ContextMenuManager/BluePointLilac.Methods/EncodingType.cs @@ -26,14 +26,14 @@ public static class EncodingType public static Encoding GetType(string filePath) { byte[] fs = File.ReadAllBytes(filePath); - foreach (var kv in EncodingBomBytes) + foreach(var kv in EncodingBomBytes) { - if (fs.Length < kv.Key.Length) continue; + if(fs.Length < kv.Key.Length) continue; int i = -1; bool flag = kv.Key.All(s => { i++; return s == fs[i]; }); - if (flag) return kv.Value; + if(flag) return kv.Value; } - if (IsUTF8Bytes(fs)) return Encoding.UTF8; //不带BOM的UTF-8 + if(IsUTF8Bytes(fs)) return Encoding.UTF8; //不带BOM的UTF-8 return Encoding.Default; } @@ -42,12 +42,12 @@ public static Encoding GetType(string filePath) private static bool IsUTF8Bytes(byte[] bytes) { int count = 1; //计算当前正分析的字符应还有的字节数 - for (int i = 0; i < bytes.Length; i++) + for(int i = 0; i < bytes.Length; i++) { byte curByte = bytes[i];//当前分析的字节. - if (count == 1) + if(count == 1) { - if (curByte >= 0x80) + if(curByte >= 0x80) { //计算当前字符所占的字节数 //修复了EncodingType内造成en语言下debug错误的问题(算术溢出) @@ -92,7 +92,7 @@ private static bool IsUTF8Bytes(byte[] bytes) else { //若是UTF-8 此时第一位必须为1 - if ((curByte & 0xC0) != 0x80) return false; + if((curByte & 0xC0) != 0x80) return false; else count--; } } diff --git a/ContextMenuManager/BluePointLilac.Methods/FileExtension.cs b/ContextMenuManager/BluePointLilac.Methods/FileExtension.cs index bed1dfce..4169389e 100644 --- a/ContextMenuManager/BluePointLilac.Methods/FileExtension.cs +++ b/ContextMenuManager/BluePointLilac.Methods/FileExtension.cs @@ -55,25 +55,25 @@ public static string GetExtentionInfo(AssocStr assocStr, string extension) public static string GetOpenMode(string extension) { - if (string.IsNullOrEmpty(extension)) return null; + if(string.IsNullOrEmpty(extension)) return null; string mode; bool CheckMode() { - if (mode.IsNullOrWhiteSpace()) return false; - if (mode.Length > 255) return false; - if (mode.ToLower().StartsWith(@"applications\")) return false; - using (RegistryKey root = Registry.ClassesRoot) - using (RegistryKey key = root.OpenSubKey(mode)) + if(mode.IsNullOrWhiteSpace()) return false; + if(mode.Length > 255) return false; + if(mode.ToLower().StartsWith(@"applications\")) return false; + using(RegistryKey root = Registry.ClassesRoot) + using(RegistryKey key = root.OpenSubKey(mode)) { return key != null; } } mode = Registry.GetValue($@"{FILEEXTSPATH}\{extension}\UserChoice", "ProgId", null)?.ToString(); - if (CheckMode()) return mode; + if(CheckMode()) return mode; mode = Registry.GetValue($@"{HKLMCLASSES}\{extension}", "", null)?.ToString(); - if (CheckMode()) return mode; + if(CheckMode()) return mode; mode = Registry.GetValue($@"{HKCRCLASSES}\{extension}", "", null)?.ToString(); - if (CheckMode()) return mode; + if(CheckMode()) return mode; return null; } } diff --git a/ContextMenuManager/BluePointLilac.Methods/FormExtension.cs b/ContextMenuManager/BluePointLilac.Methods/FormExtension.cs index 560e0765..4aa16718 100644 --- a/ContextMenuManager/BluePointLilac.Methods/FormExtension.cs +++ b/ContextMenuManager/BluePointLilac.Methods/FormExtension.cs @@ -10,12 +10,12 @@ public static class FormExtension /// 同时被移动的窗体 public static void MoveAsMove(this Form frm1, Form frm2) { - if (frm2 == null) return; + if(frm2 == null) return; Point pLast = Point.Empty; frm1.Load += (sender, e) => pLast = frm1.Location; frm1.LocationChanged += (sender, e) => { - if (pLast == Point.Empty) return; + if(pLast == Point.Empty) return; frm2.Left += frm1.Left - pLast.X; frm2.Top += frm1.Top - pLast.Y; pLast = frm1.Location; diff --git a/ContextMenuManager/BluePointLilac.Methods/GuidEx.cs b/ContextMenuManager/BluePointLilac.Methods/GuidEx.cs index 3a190a57..15fd79b2 100644 --- a/ContextMenuManager/BluePointLilac.Methods/GuidEx.cs +++ b/ContextMenuManager/BluePointLilac.Methods/GuidEx.cs @@ -8,7 +8,7 @@ public static class GuidEx { public static bool TryParse(string str, out Guid guid) { - if (IsGuid(str)) + if(IsGuid(str)) { guid = new Guid(str); return true; @@ -24,9 +24,9 @@ public static bool TryParse(string str, out Guid guid) public static bool IsGuid(string str) { - if (string.IsNullOrEmpty(str)) return false; - if (str.Length == 38 && str.StartsWith("{") && str.EndsWith("}") && GuidRegex.IsMatch(str)) return true; - if (str.Length == 36 && GuidRegex.IsMatch(str)) return true; + if(string.IsNullOrEmpty(str)) return false; + if(str.Length == 38 && str.StartsWith("{") && str.EndsWith("}") && GuidRegex.IsMatch(str)) return true; + if(str.Length == 36 && GuidRegex.IsMatch(str)) return true; return false; } } diff --git a/ContextMenuManager/BluePointLilac.Methods/ImageExtension.cs b/ContextMenuManager/BluePointLilac.Methods/ImageExtension.cs index 576ac006..c53de28a 100644 --- a/ContextMenuManager/BluePointLilac.Methods/ImageExtension.cs +++ b/ContextMenuManager/BluePointLilac.Methods/ImageExtension.cs @@ -9,8 +9,8 @@ public static class ImageExtension public static Image ToTransparent(this Image image, float opacity = 0.5F) { Bitmap bitmap = new Bitmap(image.Width, image.Height); - using (Graphics g = Graphics.FromImage(bitmap)) - using (ImageAttributes attributes = new ImageAttributes()) + using(Graphics g = Graphics.FromImage(bitmap)) + using(ImageAttributes attributes = new ImageAttributes()) { ColorMatrix matrix = new ColorMatrix { Matrix33 = opacity }; attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); @@ -23,10 +23,10 @@ public static Image ToTransparent(this Image image, float opacity = 0.5F) public static Image ResizeImage(this Image image, int width, int height) { //return image.GetThumbnailImage(width, height, null, System.IntPtr.Zero);//质量稍微低一点 - if (image.Width == width && image.Height == height) return image; + if(image.Width == width && image.Height == height) return image; Bitmap destImage = new Bitmap(width, height); destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); - using (Graphics g = Graphics.FromImage(destImage)) + using(Graphics g = Graphics.FromImage(destImage)) { g.CompositingMode = CompositingMode.SourceCopy; g.InterpolationMode = InterpolationMode.HighQualityBicubic; @@ -34,7 +34,7 @@ public static Image ResizeImage(this Image image, int width, int height) g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; - using (ImageAttributes attributes = new ImageAttributes()) + using(ImageAttributes attributes = new ImageAttributes()) { attributes.SetWrapMode(WrapMode.TileFlipXY); g.DrawImage(image, new Rectangle(0, 0, width, height), @@ -46,7 +46,7 @@ public static Image ResizeImage(this Image image, int width, int height) public static Image ResizeImage(this Image image, double scale) { - if (scale == 1) return image; + if(scale == 1) return image; int width = (int)(image.Width * scale); int height = (int)(image.Height * scale); return image.ResizeImage(width, height); @@ -54,7 +54,7 @@ public static Image ResizeImage(this Image image, double scale) public static Image ResizeImage(this Image image, Size newSize) { - if (newSize == image.Size) return image; + if(newSize == image.Size) return image; return image.ResizeImage(newSize.Width, newSize.Height); } diff --git a/ContextMenuManager/BluePointLilac.Methods/IniReader.cs b/ContextMenuManager/BluePointLilac.Methods/IniReader.cs index 9a760c8a..38718579 100644 --- a/ContextMenuManager/BluePointLilac.Methods/IniReader.cs +++ b/ContextMenuManager/BluePointLilac.Methods/IniReader.cs @@ -22,7 +22,7 @@ private readonly Dictionary> RootDic public void LoadStringBuilder(StringBuilder sb) { RootDic.Clear(); - if (sb.ToString().IsNullOrWhiteSpace()) return; + if(sb.ToString().IsNullOrWhiteSpace()) return; List lines = sb.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();//拆分为行 lines.ForEach(line => line.Trim()); @@ -32,14 +32,14 @@ public void LoadStringBuilder(StringBuilder sb) public void LoadFile(string filePath) { RootDic.Clear(); - if (!File.Exists(filePath)) return; + if(!File.Exists(filePath)) return; List lines = new List(); - using (StreamReader reader = new StreamReader(filePath, EncodingType.GetType(filePath))) + using(StreamReader reader = new StreamReader(filePath, EncodingType.GetType(filePath))) { - while (!reader.EndOfStream) + while(!reader.EndOfStream) { string line = reader.ReadLine().Trim(); - if (line != string.Empty) lines.Add(line); + if(line != string.Empty) lines.Add(line); } } ReadLines(lines); @@ -51,31 +51,31 @@ private void ReadLines(List lines) line => line.StartsWith(";") || line.StartsWith("#")//移除注释 || (!line.StartsWith("[") && !line.Contains("=")));//移除非section行且非key行 - if (lines.Count == 0) return; + if(lines.Count == 0) return; List indexs = new List { 0 }; - for (int i = 1; i < lines.Count; i++) + for(int i = 1; i < lines.Count; i++) { - if (lines[i].StartsWith("[")) indexs.Add(i);//获取section行号 + if(lines[i].StartsWith("[")) indexs.Add(i);//获取section行号 } indexs.Add(lines.Count); - for (int i = 0; i < indexs.Count - 1; i++) + for(int i = 0; i < indexs.Count - 1; i++) { string section = lines[indexs[i]]; int m = section.IndexOf(']') - 1; - if (m < 0) continue; + if(m < 0) continue; section = section.Substring(1, m); - if (RootDic.ContainsKey(section)) continue; + if(RootDic.ContainsKey(section)) continue; var keyValues = new Dictionary(StringComparer.OrdinalIgnoreCase); RootDic.Add(section, keyValues); - for (int j = indexs[i] + 1; j < indexs[i + 1]; j++) + for(int j = indexs[i] + 1; j < indexs[i + 1]; j++) { int k = lines[j].IndexOf('='); string key = lines[j].Substring(0, k).TrimEnd(); string value = lines[j].Substring(k + 1).TrimStart(); - if (keyValues.ContainsKey(key)) continue; + if(keyValues.ContainsKey(key)) continue; keyValues.Add(key, value); } } @@ -83,8 +83,8 @@ private void ReadLines(List lines) public string GetValue(string section, string key) { - if (RootDic.TryGetValue(section, out Dictionary sectionDic)) - if (sectionDic.TryGetValue(key, out string value)) + if(RootDic.TryGetValue(section, out Dictionary sectionDic)) + if(sectionDic.TryGetValue(key, out string value)) return value; return string.Empty; } @@ -97,7 +97,7 @@ public bool TryGetValue(string section, string key, out string value) public string[] GetSectionKeys(string section) { - if (!RootDic.ContainsKey(section)) return null; + if(!RootDic.ContainsKey(section)) return null; else return RootDic[section].Keys.ToArray(); } @@ -108,7 +108,7 @@ public bool RemoveSection(string section) public bool RemoveKey(string section, string key) { - if (RootDic.ContainsKey(section)) + if(RootDic.ContainsKey(section)) { return RootDic[section].Remove(key); } @@ -117,9 +117,9 @@ public bool RemoveKey(string section, string key) public void AddValue(string section, string key, string value) { - if (RootDic.ContainsKey(section)) + if(RootDic.ContainsKey(section)) { - if (RootDic[section].ContainsKey(key)) + if(RootDic[section].ContainsKey(key)) { RootDic[section][key] = value; } @@ -139,10 +139,10 @@ public void AddValue(string section, string key, string value) public void SaveFile(string filePath) { List lines = new List(); - foreach (var item in RootDic) + foreach(var item in RootDic) { lines.Add("[" + item.Key + "]"); - foreach (var key in item.Value) + foreach(var key in item.Value) { lines.Add(key.Key + " = " + key.Value); } @@ -151,7 +151,7 @@ public void SaveFile(string filePath) Directory.CreateDirectory(Path.GetDirectoryName(filePath)); FileAttributes attributes = FileAttributes.Normal; Encoding encoding = Encoding.Unicode; - if (File.Exists(filePath)) + if(File.Exists(filePath)) { encoding = EncodingType.GetType(filePath); attributes = File.GetAttributes(filePath); diff --git a/ContextMenuManager/BluePointLilac.Methods/IniWriter.cs b/ContextMenuManager/BluePointLilac.Methods/IniWriter.cs index 5cc40197..bfe7f07f 100644 --- a/ContextMenuManager/BluePointLilac.Methods/IniWriter.cs +++ b/ContextMenuManager/BluePointLilac.Methods/IniWriter.cs @@ -21,10 +21,10 @@ public IniWriter(string filePath) private List GetLines() { List lines = new List(); - if (!File.Exists(FilePath)) return lines; - using (StreamReader reader = new StreamReader(FilePath, EncodingType.GetType(FilePath))) + if(!File.Exists(FilePath)) return lines; + using(StreamReader reader = new StreamReader(FilePath, EncodingType.GetType(FilePath))) { - while (!reader.EndOfStream) + while(!reader.EndOfStream) { lines.Add(reader.ReadLine().Trim()); } @@ -35,39 +35,39 @@ private List GetLines() /// 是否是获取value值 private void SetValue(string section, string key, ref string value, bool isGetValue) { - if (section == null) return; + if(section == null) return; List lines = GetLines(); string sectionLine = $"[{section}]"; string keyLine = $"{key}={value}"; int sectionRow = -1, keyRow = -1;//先假设不存在目标section和目标key int nextSectionRow = -1;//下一个section的行数 - for (int i = 0; i < lines.Count; i++) + for(int i = 0; i < lines.Count; i++) { - if (lines[i].StartsWith(sectionLine, StringComparison.OrdinalIgnoreCase)) + if(lines[i].StartsWith(sectionLine, StringComparison.OrdinalIgnoreCase)) { sectionRow = i; break;//得到目标section所在行 } } - if (sectionRow >= 0)//如果目标section存在 + if(sectionRow >= 0)//如果目标section存在 { - for (int i = sectionRow + 1; i < lines.Count; i++) + for(int i = sectionRow + 1; i < lines.Count; i++) { - if (lines[i].StartsWith(";") || lines[i].StartsWith("#")) + if(lines[i].StartsWith(";") || lines[i].StartsWith("#")) { continue;//跳过注释 } - if (lines[i].StartsWith("[")) + if(lines[i].StartsWith("[")) { nextSectionRow = i; break;//读取到下一个section } - if (key != null && keyRow == -1) + if(key != null && keyRow == -1) { int index = lines[i].IndexOf('='); - if (index < 0) continue; + if(index < 0) continue; string str = lines[i].Substring(0, index).TrimEnd(); - if (str.Equals(key, StringComparison.OrdinalIgnoreCase)) + if(str.Equals(key, StringComparison.OrdinalIgnoreCase)) { - if (isGetValue)//如果是获取Value值,直接返回 + if(isGetValue)//如果是获取Value值,直接返回 { value = lines[i].Substring(index + 1).Trim(); return; @@ -78,11 +78,11 @@ private void SetValue(string section, string key, ref string value, bool isGetVa } } - if (isGetValue) return; + if(isGetValue) return; - if (sectionRow == -1) + if(sectionRow == -1) { - if (key != null && value != null) + if(key != null && value != null) { lines.Add(string.Empty);//添加空行 //目标section不存在则添加到最后 @@ -92,12 +92,12 @@ private void SetValue(string section, string key, ref string value, bool isGetVa } else { - if (keyRow == -1) + if(keyRow == -1) { - if (key != null) + if(key != null) { //存在下一个section时插入到其上方 - if (nextSectionRow != -1) + if(nextSectionRow != -1) { //目标section存在但目标key不存在 keyRow = nextSectionRow; @@ -113,14 +113,14 @@ private void SetValue(string section, string key, ref string value, bool isGetVa { //key为null则删除整个section int count; - if (nextSectionRow == -1) count = lines.Count - sectionRow; + if(nextSectionRow == -1) count = lines.Count - sectionRow; else count = nextSectionRow - sectionRow; lines.RemoveRange(sectionRow, count); } } else { - if (value != null) + if(value != null) { //目标section和目标key都存在 lines[keyRow] = keyLine; @@ -136,7 +136,7 @@ private void SetValue(string section, string key, ref string value, bool isGetVa Directory.CreateDirectory(Path.GetDirectoryName(FilePath)); FileAttributes attributes = FileAttributes.Normal; Encoding encoding = Encoding.Unicode; - if (File.Exists(FilePath)) + if(File.Exists(FilePath)) { encoding = EncodingType.GetType(FilePath); attributes = File.GetAttributes(FilePath); @@ -145,7 +145,7 @@ private void SetValue(string section, string key, ref string value, bool isGetVa File.WriteAllLines(FilePath, lines.ToArray(), encoding); File.SetAttributes(FilePath, attributes); - if (DeleteFileWhenEmpty && lines.TrueForAll(line => line.IsNullOrWhiteSpace())) + if(DeleteFileWhenEmpty && lines.TrueForAll(line => line.IsNullOrWhiteSpace())) { File.Delete(FilePath); } diff --git a/ContextMenuManager/BluePointLilac.Methods/MessageBoxEx.cs b/ContextMenuManager/BluePointLilac.Methods/MessageBoxEx.cs index 90bb6a8a..4e2774b0 100644 --- a/ContextMenuManager/BluePointLilac.Methods/MessageBoxEx.cs +++ b/ContextMenuManager/BluePointLilac.Methods/MessageBoxEx.cs @@ -21,7 +21,7 @@ public static DialogResult Show(string text, string caption = null, MessageBoxButtons buttons = MessageBoxButtons.OK, MessageBoxIcon boxIcon = MessageBoxIcon.None, IWin32Window owner = null, DialogResult defaultResult = DialogResult.None, bool canMoveParent = true) { - using (MessageBoxForm frm = new MessageBoxForm(text, caption, buttons, boxIcon, defaultResult, canMoveParent)) + using(MessageBoxForm frm = new MessageBoxForm(text, caption, buttons, boxIcon, defaultResult, canMoveParent)) { return frm.ShowDialog(owner); } @@ -42,7 +42,7 @@ public static string Show(string text, string caption, IWin32Window owner = null, string defaultResult = null, bool canMoveParent = true, bool closeBox = true) { - using (MessageBoxForm frm = new MessageBoxForm(text, caption, buttonTexts, boxImaage, defaultResult, canMoveParent, closeBox)) + using(MessageBoxForm frm = new MessageBoxForm(text, caption, buttonTexts, boxImaage, defaultResult, canMoveParent, closeBox)) { frm.ShowDialog(owner); return frm.Tag?.ToString(); @@ -70,7 +70,7 @@ public MessageBoxForm(string text, string caption, { CloseBox = closeBox; InitializeComponents(buttonTexts, boxImage); - foreach (Button button in flpButtons.Controls) + foreach(Button button in flpButtons.Controls) { button.Click += (sender, e) => { @@ -79,7 +79,7 @@ public MessageBoxForm(string text, string caption, }; Shown += (sender, e) => { - if (button.Text == defaultResult) button.Focus(); + if(button.Text == defaultResult) button.Focus(); }; } } @@ -90,7 +90,7 @@ public MessageBoxForm(string text, string caption, { string[] buttonTexts = null; Image boxImage = null; - switch (buttons) + switch(buttons) { case MessageBoxButtons.OK: buttonTexts = new[] { "OK" }; break; @@ -105,7 +105,7 @@ public MessageBoxForm(string text, string caption, case MessageBoxButtons.RetryCancel: buttonTexts = new[] { "Cancel", "&Retry" }; break; } - switch (boxIcon) + switch(boxIcon) { case MessageBoxIcon.Question: boxImage = MessageBoxImage.Question; break; @@ -117,12 +117,12 @@ public MessageBoxForm(string text, string caption, boxImage = MessageBoxImage.Information; break; } InitializeComponents(buttonTexts, boxImage); - foreach (Button button in flpButtons.Controls) + foreach(Button button in flpButtons.Controls) { - switch (button.Text) + switch(button.Text) { case "OK": - if (buttons == MessageBoxButtons.OK) + if(buttons == MessageBoxButtons.OK) { CancelButton = button; FormClosing += (sender, e) => button.PerformClick(); @@ -144,7 +144,7 @@ public MessageBoxForm(string text, string caption, } Shown += (sender, e) => { - if (button.DialogResult == defaultResult) button.Focus(); + if(button.DialogResult == defaultResult) button.Focus(); }; } CloseBox = CancelButton != null; @@ -155,7 +155,7 @@ private void InitializeComponents(string[] buttonTexts, Image boxImage) SuspendLayout(); int w1 = 36.DpiZoom(); Size buttonSize = new Size(75, 27).DpiZoom(); - for (int i = 0; i < buttonTexts.Length; i++) + for(int i = 0; i < buttonTexts.Length; i++) { Button button = new Button { @@ -170,7 +170,7 @@ private void InitializeComponents(string[] buttonTexts, Image boxImage) w1 += button.Width + button.Margin.Horizontal; } picIcon.Image = boxImage; - if (boxImage == null) + if(boxImage == null) { picIcon.Visible = false; lblText.Left = picIcon.Left; @@ -178,7 +178,7 @@ private void InitializeComponents(string[] buttonTexts, Image boxImage) pnlInfo.Controls.AddRange(new Control[] { picIcon, lblText }); Controls.AddRange(new Control[] { pnlInfo, flpButtons }); pnlInfo.Height = lblText.Height + lblText.Top * 2; - if (picIcon.Height > lblText.Height / 2) + if(picIcon.Height > lblText.Height / 2) { picIcon.Top = (pnlInfo.Height - picIcon.Height) / 2; } @@ -199,8 +199,8 @@ private void InitializeComponents(string[] buttonTexts, Image boxImage) }; readonly Panel pnlInfo = new Panel { - ForeColor = MyMainForm.FormFore, - BackColor = MyMainForm.FormBack, + ForeColor = DarkModeHelper.FormFore, + BackColor = DarkModeHelper.FormBack, Dock = DockStyle.Top, }; readonly PictureBox picIcon = new PictureBox @@ -210,8 +210,8 @@ private void InitializeComponents(string[] buttonTexts, Image boxImage) }; readonly Label lblText = new Label { - ForeColor = MyMainForm.FormFore, - BackColor = MyMainForm.FormBack, + ForeColor = DarkModeHelper.FormFore, + BackColor = DarkModeHelper.FormBack, Location = new Point(68, 32).DpiZoom(), AutoSize = true, }; @@ -225,20 +225,20 @@ protected override CreateParams CreateParams { const int CP_NOCLOSE_BUTTON = 0x200; CreateParams cp = base.CreateParams; - if (!CloseBox) cp.ClassStyle |= CP_NOCLOSE_BUTTON; //禁用关闭按钮 + if(!CloseBox) cp.ClassStyle |= CP_NOCLOSE_BUTTON; //禁用关闭按钮 return cp; } } protected override void OnLoad(EventArgs e) { - if (Owner == null && Form.ActiveForm != this) Owner = Form.ActiveForm; - if (Owner == null) StartPosition = FormStartPosition.CenterScreen; + if(Owner == null && Form.ActiveForm != this) Owner = Form.ActiveForm; + if(Owner == null) StartPosition = FormStartPosition.CenterScreen; else { TopMost = true; StartPosition = FormStartPosition.CenterParent; - if (CanMoveParent) this.MoveAsMove(Owner); + if(CanMoveParent) this.MoveAsMove(Owner); } base.OnLoad(e); } @@ -255,7 +255,7 @@ public static class MessageBoxImage private static Image GetImage(int index) { - using (Icon icon = ResourceIcon.GetIcon("imageres.dll", index)) + using(Icon icon = ResourceIcon.GetIcon("imageres.dll", index)) { return icon?.ToBitmap(); } diff --git a/ContextMenuManager/BluePointLilac.Methods/RegTrustedInstaller.cs b/ContextMenuManager/BluePointLilac.Methods/RegTrustedInstaller.cs index a2beb88c..e7aab65c 100644 --- a/ContextMenuManager/BluePointLilac.Methods/RegTrustedInstaller.cs +++ b/ContextMenuManager/BluePointLilac.Methods/RegTrustedInstaller.cs @@ -131,25 +131,25 @@ public static bool TrySetPrivilege(string sPrivilege, bool enablePrivilege) //本地进程令牌恢复 blRc = OpenProcessToken(GetCurrentProcess(), TokenAccessRights.AllAccess, ref processToken); - if (blRc == false) return false; + if(blRc == false) return false; //恢复特权的唯一标识符空间 blRc = LookupPrivilegeValue(null, sPrivilege, ref luid); - if (blRc == false) return false; + if(blRc == false) return false; //建立或取消特权 newTP.PrivilegeCount = 1; newTP.Privileges = new LUID_AND_ATTRIBUTES[64]; newTP.Privileges[0].Luid = luid; - if (enablePrivilege) newTP.Privileges[0].Attributes = (int)PrivilegeAttributes.Enabled; + if(enablePrivilege) newTP.Privileges[0].Attributes = (int)PrivilegeAttributes.Enabled; else newTP.Privileges[0].Attributes = (int)PrivilegeAttributes.Disabled; oldTP.PrivilegeCount = 64; oldTP.Privileges = new LUID_AND_ATTRIBUTES[64]; blRc = AdjustTokenPrivileges(processToken, false, ref newTP, 16, ref oldTP, ref retrunLength); - if (blRc == false) { GetLastError(); return false; } + if(blRc == false) { GetLastError(); return false; } return true; } } @@ -159,7 +159,7 @@ public static bool TrySetPrivilege(string sPrivilege, bool enablePrivilege) /// 要获取权限的注册表完整路径 public static void TakeRegKeyOwnerShip(string regPath) { - if (regPath.IsNullOrWhiteSpace()) return; + if(regPath.IsNullOrWhiteSpace()) return; RegistryKey key = null; WindowsIdentity id = null; //利用试错判断是否有写入权限 @@ -173,11 +173,11 @@ public static void TakeRegKeyOwnerShip(string regPath) //添加TakeOwnership特权 bool flag = NativeMethod.TrySetPrivilege(NativeMethod.TakeOwnership, true); - if (!flag) throw new PrivilegeNotHeldException(NativeMethod.TakeOwnership); + if(!flag) throw new PrivilegeNotHeldException(NativeMethod.TakeOwnership); //添加恢复特权(必须这样做才能更改所有者) flag = NativeMethod.TrySetPrivilege(NativeMethod.Restore, true); - if (!flag) throw new PrivilegeNotHeldException(NativeMethod.Restore); + if(!flag) throw new PrivilegeNotHeldException(NativeMethod.Restore); //打开没有权限的注册表路径 key = RegistryEx.GetRegistryKey(regPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership); @@ -224,14 +224,14 @@ public static void TakeRegKeyOwnerShip(string regPath) /// 要获取权限的注册表完整路径 public static void TakeRegTreeOwnerShip(string regPath) { - if (regPath.IsNullOrWhiteSpace()) return; + if(regPath.IsNullOrWhiteSpace()) return; TakeRegKeyOwnerShip(regPath); try { - using (RegistryKey key = RegistryEx.GetRegistryKey(regPath)) + using(RegistryKey key = RegistryEx.GetRegistryKey(regPath)) { - if (key == null) return; - foreach (string subKeyName in key.GetSubKeyNames()) + if(key == null) return; + foreach(string subKeyName in key.GetSubKeyNames()) { TakeRegTreeOwnerShip($@"{key.Name}\{subKeyName}"); } diff --git a/ContextMenuManager/BluePointLilac.Methods/RegistryEx.cs b/ContextMenuManager/BluePointLilac.Methods/RegistryEx.cs index 15cf93ee..cc8c3396 100644 --- a/ContextMenuManager/BluePointLilac.Methods/RegistryEx.cs +++ b/ContextMenuManager/BluePointLilac.Methods/RegistryEx.cs @@ -20,22 +20,22 @@ public static class RegistryEx public static void CopyTo(this RegistryKey srcKey, RegistryKey dstKey) { - foreach (string name in srcKey.GetValueNames()) + foreach(string name in srcKey.GetValueNames()) { dstKey.SetValue(name, srcKey.GetValue(name), srcKey.GetValueKind(name)); } - foreach (string name in srcKey.GetSubKeyNames()) + foreach(string name in srcKey.GetSubKeyNames()) { - using (RegistryKey srcSubKey = srcKey.OpenSubKey(name)) - using (RegistryKey dstSubKey = dstKey.CreateSubKey(name, true)) + using(RegistryKey srcSubKey = srcKey.OpenSubKey(name)) + using(RegistryKey dstSubKey = dstKey.CreateSubKey(name, true)) srcSubKey.CopyTo(dstSubKey); } } public static void CopyTo(string srcPath, string dstPath) { - using (RegistryKey srcKey = GetRegistryKey(srcPath)) - using (RegistryKey dstKey = GetRegistryKey(dstPath, true, true)) + using(RegistryKey srcKey = GetRegistryKey(srcPath)) + using(RegistryKey dstKey = GetRegistryKey(dstPath, true, true)) { CopyTo(srcKey, dstKey); } @@ -55,7 +55,7 @@ public static void MoveTo(string srcPath, string dstPath) public static RegistryKey CreateSubKey(this RegistryKey key, string subKeyName, bool writable) { - using (key.CreateSubKey(subKeyName)) + using(key.CreateSubKey(subKeyName)) return key.OpenSubKey(subKeyName, writable); } @@ -91,9 +91,9 @@ public static void DeleteKeyTree(string regPath, bool throwOnMissingKey = false) { GetRegistryKey(dirPath, true)?.DeleteSubKeyTree(keyName); } - catch (Exception) + catch(Exception) { - if (throwOnMissingKey) throw; + if(throwOnMissingKey) throw; } } @@ -105,7 +105,7 @@ public static void GetRootAndSubRegPath(string regPath, out RegistryKey root, ou { string rootPath; int index = regPath.IndexOf('\\'); - if (index > 0) + if(index > 0) { rootPath = regPath.Substring(0, index).ToUpper(); subRegPath = regPath.Substring(index + 1); @@ -115,7 +115,7 @@ public static void GetRootAndSubRegPath(string regPath, out RegistryKey root, ou rootPath = regPath; subRegPath = string.Empty; } - switch (rootPath) + switch(rootPath) { case HKCR: case CLASSES_ROOT: @@ -149,9 +149,9 @@ public static void GetRootAndSubRegPath(string regPath, out RegistryKey root, ou public static RegistryKey GetRegistryKey(string regPath, bool writable = false, bool create = false) { GetRootAndSubRegPath(regPath, out RegistryKey root, out string keyPath); - using (root) + using(root) { - if (create) return root.CreateSubKey(keyPath, writable); + if(create) return root.CreateSubKey(keyPath, writable); else { RegTrustedInstaller.TakeRegTreeOwnerShip(keyPath); @@ -163,7 +163,7 @@ public static RegistryKey GetRegistryKey(string regPath, bool writable = false, public static RegistryKey GetRegistryKey(string regPath, RegistryKeyPermissionCheck check, RegistryRights rights) { GetRootAndSubRegPath(regPath, out RegistryKey root, out string keyPath); - using (root) return root.OpenSubKey(keyPath, check, rights); + using(root) return root.OpenSubKey(keyPath, check, rights); } } } \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Methods/ResourceIcon.cs b/ContextMenuManager/BluePointLilac.Methods/ResourceIcon.cs index 44594777..0a9f7497 100644 --- a/ContextMenuManager/BluePointLilac.Methods/ResourceIcon.cs +++ b/ContextMenuManager/BluePointLilac.Methods/ResourceIcon.cs @@ -88,7 +88,7 @@ public static Icon GetIcon(string filePath, FileInfoFlags flags) { SHFILEINFO info = new SHFILEINFO(); IntPtr hInfo = SHGetFileInfo(filePath, 0, ref info, (uint)Marshal.SizeOf(info), flags); - if (hInfo.Equals(IntPtr.Zero)) return null; + if(hInfo.Equals(IntPtr.Zero)) return null; Icon icon = (Icon)Icon.FromHandle(info.hIcon).Clone(); DestroyIcon(info.hIcon); //释放资源 return icon; @@ -110,13 +110,13 @@ public static Icon GetIcon(string iconLocation) public static Icon GetIcon(string iconLocation, out string iconPath, out int iconIndex) { iconIndex = 0; iconPath = null; - if (iconLocation.IsNullOrWhiteSpace()) return null; + if(iconLocation.IsNullOrWhiteSpace()) return null; iconLocation = Environment.ExpandEnvironmentVariables(iconLocation).Replace("\"", ""); int index = iconLocation.LastIndexOf(','); - if (index == -1) iconPath = iconLocation; + if(index == -1) iconPath = iconLocation; else { - if (File.Exists(iconLocation)) iconPath = iconLocation; + if(File.Exists(iconLocation)) iconPath = iconLocation; else { bool flag = int.TryParse(iconLocation.Substring(index + 1), out iconIndex); @@ -133,20 +133,20 @@ public static Icon GetIcon(string iconLocation, out string iconPath, out int ico public static Icon GetIcon(string iconPath, int iconIndex) { Icon icon = null; - if (iconPath.IsNullOrWhiteSpace()) return icon; + if(iconPath.IsNullOrWhiteSpace()) return icon; iconPath = Environment.ExpandEnvironmentVariables(iconPath).Replace("\"", ""); - if (Path.GetFileName(iconPath).ToLower() == "shell32.dll") + if(Path.GetFileName(iconPath).ToLower() == "shell32.dll") { iconPath = "shell32.dll";//系统强制文件重定向 icon = GetReplacedShellIcon(iconIndex);//注册表图标重定向 - if (icon != null) return icon; + if(icon != null) return icon; } IntPtr hInst = IntPtr.Zero; IntPtr[] hIcons = new[] { IntPtr.Zero }; //iconIndex为负数就是指定资源标识符, 为正数就是该图标在资源文件中的顺序序号, 为-1时不能使用ExtractIconEx提取图标 - if (iconIndex == -1) + if(iconIndex == -1) { hInst = LoadLibrary(iconPath); hIcons[0] = LoadImage(hInst, "#1", 1, SystemInformation.IconSize.Width, SystemInformation.IconSize.Height, 0); @@ -166,7 +166,7 @@ public static Icon GetIcon(string iconPath, int iconIndex) public static Icon GetReplacedShellIcon(int iconIndex) { string iconLocation = Registry.GetValue(ShellIconPath, iconIndex.ToString(), null)?.ToString(); - if (iconLocation != null) return GetIcon(iconLocation) ?? GetIcon("imageres.dll", 2); + if(iconLocation != null) return GetIcon(iconLocation) ?? GetIcon("imageres.dll", 2); else return null; } } diff --git a/ContextMenuManager/BluePointLilac.Methods/RichTextBoxExtension.cs b/ContextMenuManager/BluePointLilac.Methods/RichTextBoxExtension.cs index 69b9a888..2338a3c4 100644 --- a/ContextMenuManager/BluePointLilac.Methods/RichTextBoxExtension.cs +++ b/ContextMenuManager/BluePointLilac.Methods/RichTextBoxExtension.cs @@ -12,16 +12,16 @@ public static class RichTextBoxExtension public static void LoadIni(this RichTextBox box, string iniStr) { string[] lines = iniStr.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None); - for (int i = 0; i < lines.Length; i++) + for(int i = 0; i < lines.Length; i++) { string str = lines[i].Trim(); - if (str.StartsWith(";") || str.StartsWith("#")) + if(str.StartsWith(";") || str.StartsWith("#")) { box.AppendText(str, Color.SkyBlue);//注释 } - else if (str.StartsWith("[")) + else if(str.StartsWith("[")) { - if (str.Contains("]")) + if(str.Contains("]")) { int index = str.IndexOf(']'); box.AppendText(str.Substring(0, index + 1), Color.DarkCyan, null, true);//section @@ -29,14 +29,14 @@ public static void LoadIni(this RichTextBox box, string iniStr) } else box.AppendText(str, Color.SkyBlue);//section标签未关闭视作注释 } - else if (str.Contains("=")) + else if(str.Contains("=")) { int index = str.IndexOf('='); box.AppendText(str.Substring(0, index), Color.DodgerBlue);//key box.AppendText(str.Substring(index), Color.DimGray);//value } else box.AppendText(str, Color.SkyBlue);//非section行和非key行视作注释 - if (i != lines.Length - 1) box.AppendText("\r\n"); + if(i != lines.Length - 1) box.AppendText("\r\n"); } } @@ -48,13 +48,13 @@ public static void LoadIni(this RichTextBox box, string iniStr) public static void LoadXml(this RichTextBox box, string xmlStr) { XmlStateMachine machine = new XmlStateMachine(); - if (xmlStr.StartsWith(" 10 || tokenTryCount > xmlStr.Length) + if(token.Length == 0) failCount++; + if(failCount > 10 || tokenTryCount > xmlStr.Length) { string theRestOfIt = xmlStr.Substring(location, xmlStr.Length - location); //box.AppendText(Environment.NewLine + Environment.NewLine + theRestOfIt); // DEBUG @@ -108,10 +108,10 @@ public string GetNextToken(string s, out XmlTokenType ttype) string whitespace = GetWhitespace(s); subString = s.TrimStart(); token = string.Empty; - if (CurrentState == XmlTokenType.CDataStart) + if(CurrentState == XmlTokenType.CDataStart) { // check for empty CDATA - if (subString.StartsWith("]]>")) + if(subString.StartsWith("]]>")) { CurrentState = XmlTokenType.CDataEnd; token = "]]>"; @@ -123,25 +123,25 @@ public string GetNextToken(string s, out XmlTokenType ttype) token = subString.Substring(0, n); } } - else if (CurrentState == XmlTokenType.DocTypeStart) + else if(CurrentState == XmlTokenType.DocTypeStart) { CurrentState = XmlTokenType.DocTypeName; token = "DOCTYPE"; } - else if (CurrentState == XmlTokenType.DocTypeName) + else if(CurrentState == XmlTokenType.DocTypeName) { CurrentState = XmlTokenType.DocTypeDeclaration; int n = subString.IndexOf("["); token = subString.Substring(0, n); } - else if (CurrentState == XmlTokenType.DocTypeDeclaration) + else if(CurrentState == XmlTokenType.DocTypeDeclaration) { CurrentState = XmlTokenType.DocTypeDefStart; token = "["; } - else if (CurrentState == XmlTokenType.DocTypeDefStart) + else if(CurrentState == XmlTokenType.DocTypeDefStart) { - if (subString.StartsWith("]>")) + if(subString.StartsWith("]>")) { CurrentState = XmlTokenType.DocTypeDefEnd; token = "]>"; @@ -153,15 +153,15 @@ public string GetNextToken(string s, out XmlTokenType ttype) token = subString.Substring(0, n); } } - else if (CurrentState == XmlTokenType.DocTypeDefValue) + else if(CurrentState == XmlTokenType.DocTypeDefValue) { CurrentState = XmlTokenType.DocTypeDefEnd; token = "]>"; } - else if (CurrentState == XmlTokenType.DoubleQuotationMarkStart) + else if(CurrentState == XmlTokenType.DoubleQuotationMarkStart) { // check for empty attribute value - if (subString[0] == '\"') + if(subString[0] == '\"') { CurrentState = XmlTokenType.DoubleQuotationMarkEnd; token = "\""; @@ -173,10 +173,10 @@ public string GetNextToken(string s, out XmlTokenType ttype) token = subString.Substring(0, n); } } - else if (CurrentState == XmlTokenType.SingleQuotationMarkStart) + else if(CurrentState == XmlTokenType.SingleQuotationMarkStart) { // check for empty attribute value - if (subString[0] == '\'') + if(subString[0] == '\'') { CurrentState = XmlTokenType.SingleQuotationMarkEnd; token = "\'"; @@ -188,10 +188,10 @@ public string GetNextToken(string s, out XmlTokenType ttype) token = subString.Substring(0, n); } } - else if (CurrentState == XmlTokenType.CommentStart) + else if(CurrentState == XmlTokenType.CommentStart) { // check for empty comment - if (subString.StartsWith("-->")) + if(subString.StartsWith("-->")) { CurrentState = XmlTokenType.CommentEnd; token = "-->"; @@ -202,19 +202,19 @@ public string GetNextToken(string s, out XmlTokenType ttype) token = ReadCommentValue(subString); } } - else if (CurrentState == XmlTokenType.NodeStart) + else if(CurrentState == XmlTokenType.NodeStart) { CurrentState = XmlTokenType.NodeName; token = ReadNodeName(subString); } - else if (CurrentState == XmlTokenType.XmlDeclarationStart) + else if(CurrentState == XmlTokenType.XmlDeclarationStart) { CurrentState = XmlTokenType.NodeName; token = ReadNodeName(subString); } - else if (CurrentState == XmlTokenType.NodeName) + else if(CurrentState == XmlTokenType.NodeName) { - if (subString[0] != '/' && + if(subString[0] != '/' && subString[0] != '>') { CurrentState = XmlTokenType.AttributeName; @@ -225,9 +225,9 @@ public string GetNextToken(string s, out XmlTokenType ttype) HandleReservedXmlToken(); } } - else if (CurrentState == XmlTokenType.NodeEndValueStart) + else if(CurrentState == XmlTokenType.NodeEndValueStart) { - if (subString[0] == '<') + if(subString[0] == '<') { HandleReservedXmlToken(); } @@ -237,11 +237,11 @@ public string GetNextToken(string s, out XmlTokenType ttype) token = ReadNodeValue(subString); } } - else if (CurrentState == XmlTokenType.DoubleQuotationMarkEnd) + else if(CurrentState == XmlTokenType.DoubleQuotationMarkEnd) { HandleAttributeEnd(); } - else if (CurrentState == XmlTokenType.SingleQuotationMarkEnd) + else if(CurrentState == XmlTokenType.SingleQuotationMarkEnd) { HandleAttributeEnd(); } @@ -249,7 +249,7 @@ public string GetNextToken(string s, out XmlTokenType ttype) { HandleReservedXmlToken(); } - if (token != string.Empty) + if(token != string.Empty) { ttype = CurrentState; return whitespace + token; @@ -259,7 +259,7 @@ public string GetNextToken(string s, out XmlTokenType ttype) public Color GetTokenColor(XmlTokenType ttype) { - switch (ttype) + switch(ttype) { case XmlTokenType.NodeValue: case XmlTokenType.EqualSignStart: @@ -304,7 +304,7 @@ public string GetXmlDeclaration(string s) { int start = s.IndexOf(""); - if (start > -1 && end > start) + if(start > -1 && end > start) { return s.Substring(start, end - start + 2); } @@ -313,15 +313,15 @@ public string GetXmlDeclaration(string s) private void HandleAttributeEnd() { - if (subString.StartsWith(">")) + if(subString.StartsWith(">")) { HandleReservedXmlToken(); } - else if (subString.StartsWith("/>")) + else if(subString.StartsWith("/>")) { HandleReservedXmlToken(); } - else if (subString.StartsWith("?>")) + else if(subString.StartsWith("?>")) { HandleReservedXmlToken(); } @@ -336,74 +336,74 @@ private void HandleReservedXmlToken() { // check if state changer // <, >, =, , - if (subString.StartsWith("")) + else if(subString.StartsWith("?>")) { CurrentState = XmlTokenType.XmlDeclarationEnd; token = "?>"; } - else if (subString.StartsWith(">")) + else if(subString.StartsWith(">")) { CurrentState = XmlTokenType.NodeEndValueStart; token = ">"; } - else if (subString.StartsWith("-->")) + else if(subString.StartsWith("-->")) { CurrentState = XmlTokenType.CommentEnd; token = "-->"; } - else if (subString.StartsWith("]>")) + else if(subString.StartsWith("]>")) { CurrentState = XmlTokenType.DocTypeEnd; token = "]>"; } - else if (subString.StartsWith("]]>")) + else if(subString.StartsWith("]]>")) { CurrentState = XmlTokenType.CDataEnd; token = "]]>"; } - else if (subString.StartsWith("/>")) + else if(subString.StartsWith("/>")) { CurrentState = XmlTokenType.NodeEnd; token = "/>"; } - else if (subString.StartsWith("\"")) + else if(subString.StartsWith("\"")) { - if (CurrentState == XmlTokenType.AttributeValue) + if(CurrentState == XmlTokenType.AttributeValue) { CurrentState = XmlTokenType.DoubleQuotationMarkEnd; } @@ -413,9 +413,9 @@ private void HandleReservedXmlToken() } token = "\""; } - else if (subString.StartsWith("'")) + else if(subString.StartsWith("'")) { - if (CurrentState == XmlTokenType.AttributeValue) + if(CurrentState == XmlTokenType.AttributeValue) { CurrentState = XmlTokenType.SingleQuotationMarkEnd; } @@ -430,9 +430,9 @@ private void HandleReservedXmlToken() private string ReadNodeName(string s) { string nodeName = ""; - for (int i = 0; i < s.Length; i++) + for(int i = 0; i < s.Length; i++) { - if (s[i] == '/' || s[i] == ' ' || s[i] == '>') return nodeName; + if(s[i] == '/' || s[i] == ' ' || s[i] == '>') return nodeName; else nodeName += s[i].ToString(); } return nodeName; @@ -442,7 +442,7 @@ private string ReadAttributeName(string s) { string attName = ""; int n = s.IndexOf('='); - if (n != -1) attName = s.Substring(0, n); + if(n != -1) attName = s.Substring(0, n); return attName; } @@ -450,7 +450,7 @@ private string ReadNodeValue(string s) { string nodeValue = ""; int n = s.IndexOf('<'); - if (n != -1) nodeValue = s.Substring(0, n); + if(n != -1) nodeValue = s.Substring(0, n); return nodeValue; } @@ -458,17 +458,17 @@ private string ReadCommentValue(string s) { string commentValue = ""; int n = s.IndexOf("-->"); - if (n != -1) commentValue = s.Substring(0, n); + if(n != -1) commentValue = s.Substring(0, n); return commentValue; } private string GetWhitespace(string s) { string whitespace = ""; - for (int i = 0; i < s.Length; i++) + for(int i = 0; i < s.Length; i++) { char c = s[i]; - if (char.IsWhiteSpace(c)) whitespace += c; + if(char.IsWhiteSpace(c)) whitespace += c; else break; } return whitespace; diff --git a/ContextMenuManager/BluePointLilac.Methods/ShellLink.cs b/ContextMenuManager/BluePointLilac.Methods/ShellLink.cs index 122d8a87..caa1af6d 100644 --- a/ContextMenuManager/BluePointLilac.Methods/ShellLink.cs +++ b/ContextMenuManager/BluePointLilac.Methods/ShellLink.cs @@ -212,7 +212,7 @@ public Keys HotKey } set { - if ((value & Keys.Modifiers) == 0) throw new ArgumentException("Hotkey must include a modifier key."); + if((value & Keys.Modifiers) == 0) throw new ArgumentException("Hotkey must include a modifier key."); ushort key = unchecked((ushort)(((int)(value & Keys.Modifiers) >> 8) | (int)(value & Keys.KeyCode))); shellLinkW.SetHotKey(key); } @@ -223,7 +223,7 @@ public FormWindowState WindowStyle get { shellLinkW.GetShowCmd(out int style); - switch (style) + switch(style) { case SW_SHOWMINIMIZED: case SW_SHOWMINNOACTIVE: @@ -238,7 +238,7 @@ public FormWindowState WindowStyle set { int style; - switch (value) + switch(value) { case FormWindowState.Minimized: style = SW_SHOWMINIMIZED; break; @@ -262,7 +262,7 @@ public bool RunAsAdministrator set { LinkDataList.GetFlags(out ShellLinkDataFlags flags); - if (value) flags |= ShellLinkDataFlags.RunasUser; + if(value) flags |= ShellLinkDataFlags.RunasUser; else flags &= ~ShellLinkDataFlags.RunasUser; LinkDataList.SetFlags(flags); } @@ -285,7 +285,7 @@ public void Dispose() protected virtual void Dispose(bool disposing) { - if (shellLinkW == null) return; + if(shellLinkW == null) return; Marshal.FinalReleaseComObject(shellLinkW); shellLinkW = null; } @@ -302,7 +302,7 @@ public void Save(string lnkPath) public void Load(string lnkPath) { ShortcutPath = lnkPath; - if (File.Exists(lnkPath)) PersistFile.Load(lnkPath, STGM_READWRITE); + if(File.Exists(lnkPath)) PersistFile.Load(lnkPath, STGM_READWRITE); } } } \ No newline at end of file diff --git a/ContextMenuManager/BluePointLilac.Methods/SingleInstance.cs b/ContextMenuManager/BluePointLilac.Methods/SingleInstance.cs index f23ee33e..0ffe2f36 100644 --- a/ContextMenuManager/BluePointLilac.Methods/SingleInstance.cs +++ b/ContextMenuManager/BluePointLilac.Methods/SingleInstance.cs @@ -20,14 +20,14 @@ public static class SingleInstance /// 若正在运行激活窗口 public static bool IsRunning() { - using (Process current = Process.GetCurrentProcess()) + using(Process current = Process.GetCurrentProcess()) { - foreach (Process process in Process.GetProcessesByName(current.ProcessName)) + foreach(Process process in Process.GetProcessesByName(current.ProcessName)) { - using (process) + using(process) { - if (process.Id == current.Id) continue; - if (process.MainModule.FileName == current.MainModule.FileName) + if(process.Id == current.Id) continue; + if(process.MainModule.FileName == current.MainModule.FileName) { const int SW_RESTORE = 9; ShowWindowAsync(process.MainWindowHandle, SW_RESTORE); @@ -47,7 +47,7 @@ public static void Restart(string[] args = null, string updatePath = null) { string appPath = Application.ExecutablePath; string command = appPath; - if (args != null && args.Length > 0) command += "," + string.Join(" ", args); + if(args != null && args.Length > 0) command += "," + string.Join(" ", args); List contents = new List(); //vbs命令逐行执行不等待,故加些代码确定上一条命令执行是否完成 contents.AddRange(new[] @@ -59,7 +59,7 @@ public static void Restart(string[] args = null, string updatePath = null) "Set fso = CreateObject(\"Scripting.FileSystemObject\")", }); - if (File.Exists(updatePath)) + if(File.Exists(updatePath)) { contents.AddRange(new[] { @@ -83,7 +83,7 @@ public static void Restart(string[] args = null, string updatePath = null) string vbsPath = Path.GetTempPath() + Guid.NewGuid() + ".vbs"; File.WriteAllLines(vbsPath, contents.ToArray(), Encoding.Unicode); - using (Process process = new Process()) + using(Process process = new Process()) { process.StartInfo.FileName = "wscript.exe"; process.StartInfo.Arguments = vbsPath; diff --git a/ContextMenuManager/BluePointLilac.Methods/StringExtension.cs b/ContextMenuManager/BluePointLilac.Methods/StringExtension.cs index b89466f3..166eebec 100644 --- a/ContextMenuManager/BluePointLilac.Methods/StringExtension.cs +++ b/ContextMenuManager/BluePointLilac.Methods/StringExtension.cs @@ -5,7 +5,7 @@ public static class StringExtension { public static bool IsNullOrWhiteSpace(this string str) { - if (string.IsNullOrEmpty(str)) return true; + if(string.IsNullOrEmpty(str)) return true; return str.Trim().Length == 0; } } diff --git a/ContextMenuManager/BluePointLilac.Methods/TextBoxExtension.cs b/ContextMenuManager/BluePointLilac.Methods/TextBoxExtension.cs index d96e2521..8f4f7329 100644 --- a/ContextMenuManager/BluePointLilac.Methods/TextBoxExtension.cs +++ b/ContextMenuManager/BluePointLilac.Methods/TextBoxExtension.cs @@ -10,10 +10,10 @@ public static void CanResizeFont(this TextBox box) { box.MouseWheel += (sender, e) => { - if (Control.ModifierKeys != Keys.Control) return; + if(Control.ModifierKeys != Keys.Control) return; float size = box.Font.Size; - if (size < 8F && e.Delta < 0) return; - if (size > 40F && e.Delta > 0) return; + if(size < 8F && e.Delta < 0) return; + if(size > 40F && e.Delta > 0) return; box.Font = new Font(box.Font.FontFamily, size + (e.Delta > 0 ? 1F : -1F)); }; } @@ -26,9 +26,9 @@ void SetScrollVisible() { Size szBox = box.ClientSize; Size szText = TextRenderer.MeasureText(box.Text, box.Font); - if ((scrollBars | ScrollBars.Vertical) == ScrollBars.Vertical) + if((scrollBars | ScrollBars.Vertical) == ScrollBars.Vertical) { - if (szText.Height > szBox.Height) + if(szText.Height > szBox.Height) { box.ScrollBars = scrollBars | ScrollBars.Vertical; } @@ -37,9 +37,9 @@ void SetScrollVisible() box.ScrollBars = scrollBars & ~ScrollBars.Vertical; } } - if ((scrollBars | ScrollBars.Horizontal) == ScrollBars.Horizontal) + if((scrollBars | ScrollBars.Horizontal) == ScrollBars.Horizontal) { - if (szText.Width > szBox.Width) + if(szText.Width > szBox.Width) { box.ScrollBars = scrollBars | ScrollBars.Horizontal; } @@ -48,8 +48,7 @@ void SetScrollVisible() box.ScrollBars = scrollBars & ~ScrollBars.Horizontal; } } - } - ; + }; box.TextChanged += (sender, e) => SetScrollVisible(); box.FontChanged += (sender, e) => SetScrollVisible(); box.ClientSizeChanged += (sender, e) => SetScrollVisible(); @@ -60,7 +59,7 @@ public static void CanSelectAllWhenReadOnly(this TextBox box) { box.KeyDown += (sender, e) => { - if (box.ReadOnly && e.Control && e.KeyCode == Keys.A) box.SelectAll(); + if(box.ReadOnly && e.Control && e.KeyCode == Keys.A) box.SelectAll(); }; } } diff --git a/ContextMenuManager/BluePointLilac.Methods/ToolTipBox.cs b/ContextMenuManager/BluePointLilac.Methods/ToolTipBox.cs index 382b6605..518d9bae 100644 --- a/ContextMenuManager/BluePointLilac.Methods/ToolTipBox.cs +++ b/ContextMenuManager/BluePointLilac.Methods/ToolTipBox.cs @@ -6,7 +6,7 @@ public static class ToolTipBox { public static void SetToolTip(Control ctr, string tip) { - if (tip.IsNullOrWhiteSpace()) return; + if(tip.IsNullOrWhiteSpace()) return; ToolTip toolTip = new ToolTip { InitialDelay = 1 }; toolTip.SetToolTip(ctr, tip); ctr.Disposed += (sender, e) => toolTip.Dispose(); diff --git a/ContextMenuManager/ContextMenuManager.csproj b/ContextMenuManager/ContextMenuManager.csproj index c4f7e30e..99a5c55f 100644 --- a/ContextMenuManager/ContextMenuManager.csproj +++ b/ContextMenuManager/ContextMenuManager.csproj @@ -54,7 +54,6 @@ del $(TargetDir)\Config\Dictionaries\Web\AppLanguageDic.ini--> Auto - @@ -293,18 +292,7 @@ del $(TargetDir)\Config\Dictionaries\Web\AppLanguageDic.ini--> - + diff --git a/ContextMenuManager/Controls/AppSettingBox.cs b/ContextMenuManager/Controls/AppSettingBox.cs index e2305f3b..b463aecb 100644 --- a/ContextMenuManager/Controls/AppSettingBox.cs +++ b/ContextMenuManager/Controls/AppSettingBox.cs @@ -156,7 +156,7 @@ public void LoadItems() { AddItems(new[] { mliConfigDir, mliUpdate, mliRepo, mliEngine, mliBackup, mliTopMost, mliProtect, mliShowFilePath, mliHideDisabledItems, mliHideSysStoreItems, mliOpenMoreRegedit, mliOpenMoreExplorer }); - foreach (MyListItem item in Controls) item.HasImage = false; + foreach(MyListItem item in Controls) item.HasImage = false; cmbConfigDir.SelectedIndex = AppConfig.SaveToAppDir ? 1 : 0; cmbRepo.SelectedIndex = AppConfig.RequestUseGithub ? 0 : 1; cmbUpdate.SelectedIndex = GetUpdateSelectIndex(); @@ -174,8 +174,8 @@ public void LoadItems() private void ChangeConfigDir() { string newPath = (cmbConfigDir.SelectedIndex == 0) ? AppConfig.AppDataConfigDir : AppConfig.AppConfigDir; - if (newPath == AppConfig.ConfigDir) return; - if (AppMessageBox.Show(AppString.Message.RestartApp, MessageBoxButtons.OKCancel) != DialogResult.OK) + if(newPath == AppConfig.ConfigDir) return; + if(AppMessageBox.Show(AppString.Message.RestartApp, MessageBoxButtons.OKCancel) != DialogResult.OK) { cmbConfigDir.SelectedIndex = AppConfig.SaveToAppDir ? 1 : 0; } @@ -189,17 +189,17 @@ private void ChangeConfigDir() private void ChangeEngineUrl() { - if (cmbEngine.SelectedIndex < cmbEngine.Items.Count - 1) + if(cmbEngine.SelectedIndex < cmbEngine.Items.Count - 1) { AppConfig.EngineUrl = AppConfig.EngineUrlsDic[cmbEngine.Text]; } else { - using (InputDialog dlg = new InputDialog()) + using(InputDialog dlg = new InputDialog()) { dlg.Text = AppConfig.EngineUrl; dlg.Title = AppString.Other.SetCustomEngine; - if (dlg.ShowDialog() == DialogResult.OK) AppConfig.EngineUrl = dlg.Text; + if(dlg.ShowDialog() == DialogResult.OK) AppConfig.EngineUrl = dlg.Text; cmbEngine.SelectedIndex = GetEngineSelectIndex(); } } @@ -208,7 +208,7 @@ private void ChangeEngineUrl() private void ChangeUpdateFrequency() { int day = 30; - switch (cmbUpdate.SelectedIndex) + switch(cmbUpdate.SelectedIndex) { case 0: day = 7; break; @@ -223,7 +223,7 @@ private void ChangeUpdateFrequency() private int GetUpdateSelectIndex() { int index = 1; - switch (AppConfig.UpdateFrequency) + switch(AppConfig.UpdateFrequency) { case 7: index = 0; break; @@ -238,9 +238,9 @@ private int GetUpdateSelectIndex() private int GetEngineSelectIndex() { string[] urls = AppConfig.EngineUrlsDic.Values.ToArray(); - for (int i = 0; i < urls.Length; i++) + for(int i = 0; i < urls.Length; i++) { - if (AppConfig.EngineUrl.Equals(urls[i])) return i; + if(AppConfig.EngineUrl.Equals(urls[i])) return i; } return cmbEngine.Items.Count - 1; } diff --git a/ContextMenuManager/Controls/BackupListBox.cs b/ContextMenuManager/Controls/BackupListBox.cs index 5c9c2f6b..c550c164 100644 --- a/ContextMenuManager/Controls/BackupListBox.cs +++ b/ContextMenuManager/Controls/BackupListBox.cs @@ -29,7 +29,7 @@ public void LoadItems() // 新增备份项目 string deviceName = BackupList.metaData?.Device; string createTime = BackupList.metaData?.CreateTime.ToString("G"); - AddItem(new RestoreItem(this, xmlFile, deviceName ?? AppString.Other.Unknown, + AddItem(new RestoreItem(this, xmlFile, deviceName ?? AppString.Other.Unknown, createTime ?? AppString.Other.Unknown)); } } @@ -56,7 +56,7 @@ private void BackupItems() dlg.TvTitle = AppString.Dialog.BackupContent; dlg.TvItems = BackupHelper.BackupScenesText; dlg.CmbTitle = AppString.Dialog.BackupMode; - dlg.CmbItems = new[] { AppString.Dialog.BackupMode1, AppString.Dialog.BackupMode2, + dlg.CmbItems = new[] { AppString.Dialog.BackupMode1, AppString.Dialog.BackupMode2, AppString.Dialog.BackupMode3 }; if (dlg.ShowDialog() != DialogResult.OK) return; switch (dlg.CmbSelectedIndex) diff --git a/ContextMenuManager/Controls/DetailedEditDialog.cs b/ContextMenuManager/Controls/DetailedEditDialog.cs index b1b47404..ce34cc5e 100644 --- a/ContextMenuManager/Controls/DetailedEditDialog.cs +++ b/ContextMenuManager/Controls/DetailedEditDialog.cs @@ -13,8 +13,8 @@ public override void Reset() { } protected override bool RunDialog(IntPtr hwndOwner) { - using (SubItemsForm frm = new SubItemsForm()) - using (DetailedEditList list = new DetailedEditList()) + using(SubItemsForm frm = new SubItemsForm()) + using(DetailedEditList list = new DetailedEditList()) { var location = GuidInfo.GetIconLocation(GroupGuid); frm.Icon = ResourceIcon.GetIcon(location.IconPath, location.IconIndex); diff --git a/ContextMenuManager/Controls/DetailedEditList.cs b/ContextMenuManager/Controls/DetailedEditList.cs index 87e0d3cd..509cdeb2 100644 --- a/ContextMenuManager/Controls/DetailedEditList.cs +++ b/ContextMenuManager/Controls/DetailedEditList.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Drawing; using System.IO; +using System.Windows.Forms; using System.Xml; namespace ContextMenuManager.Controls @@ -19,23 +20,23 @@ public override void LoadItems() int index = UseUserDic ? 1 : 0; // 获取系统字典或用户字典 XmlDocument doc = XmlDicHelper.DetailedEditDic[index]; - if (doc?.DocumentElement == null) return; + if(doc?.DocumentElement == null) return; // 遍历所有子节点 - foreach (XmlNode groupXN in doc.DocumentElement.ChildNodes) + foreach(XmlNode groupXN in doc.DocumentElement.ChildNodes) { try { // 获取Guid列表 List guids = new List(); XmlNodeList guidList = groupXN.SelectNodes("Guid"); - foreach (XmlNode guidXN in guidList) + foreach(XmlNode guidXN in guidList) { - if (!GuidEx.TryParse(guidXN.InnerText, out Guid guid)) continue; - if (!File.Exists(GuidInfo.GetFilePath(guid))) continue; - if (GroupGuid != Guid.Empty && GroupGuid != guid) continue; + if(!GuidEx.TryParse(guidXN.InnerText, out Guid guid)) continue; + if(!File.Exists(GuidInfo.GetFilePath(guid))) continue; + if(GroupGuid != Guid.Empty && GroupGuid != guid) continue; guids.Add(guid); } - if (guidList.Count > 0 && guids.Count == 0) continue; + if(guidList.Count > 0 && guids.Count == 0) continue; // 获取groupItem列表 FoldGroupItem groupItem; @@ -43,26 +44,26 @@ public override void LoadItems() string attribute = isIniGroup ? "FilePath" : "RegPath"; ObjectPath.PathType pathType = isIniGroup ? ObjectPath.PathType.File : ObjectPath.PathType.Registry; groupItem = new FoldGroupItem(groupXN.SelectSingleNode(attribute)?.InnerText, pathType); - foreach (XmlElement textXE in groupXN.SelectNodes("Text")) + foreach(XmlElement textXE in groupXN.SelectNodes("Text")) { - if (XmlDicHelper.JudgeCulture(textXE)) groupItem.Text = ResourceString.GetDirectString(textXE.GetAttribute("Value")); + if(XmlDicHelper.JudgeCulture(textXE)) groupItem.Text = ResourceString.GetDirectString(textXE.GetAttribute("Value")); } - if (guids.Count > 0) + if(guids.Count > 0) { groupItem.Tag = guids; - if (groupItem.Text.IsNullOrWhiteSpace()) groupItem.Text = GuidInfo.GetText(guids[0]); + if(groupItem.Text.IsNullOrWhiteSpace()) groupItem.Text = GuidInfo.GetText(guids[0]); groupItem.Image = GuidInfo.GetImage(guids[0]); string filePath = GuidInfo.GetFilePath(guids[0]); string clsidPath = GuidInfo.GetClsidPath(guids[0]); - if (filePath != null || clsidPath != null) groupItem.ContextMenuStrip.Items.Add(new RToolStripSeparator()); - if (filePath != null) + if(filePath != null || clsidPath != null) groupItem.ContextMenuStrip.Items.Add(new RToolStripSeparator()); + if(filePath != null) { var tsi = new RToolStripMenuItem(AppString.Menu.FileLocation); // 打开文件夹 tsi.Click += (sender, e) => ExternalProgram.JumpExplorer(filePath, AppConfig.OpenMoreExplorer); groupItem.ContextMenuStrip.Items.Add(tsi); } - if (clsidPath != null) + if(clsidPath != null) { var tsi = new RToolStripMenuItem(AppString.Menu.ClsidLocation); // 打开注册表 @@ -71,43 +72,42 @@ public override void LoadItems() } } XmlNode iconXN = groupXN.SelectSingleNode("Icon"); - using (Icon icon = ResourceIcon.GetIcon(iconXN?.InnerText)) + using(Icon icon = ResourceIcon.GetIcon(iconXN?.InnerText)) { - if (icon != null) groupItem.Image = icon.ToBitmap(); + if(icon != null) groupItem.Image = icon.ToBitmap(); } AddItem(groupItem); string GetRuleFullRegPath(string regPath) { - if (string.IsNullOrEmpty(regPath)) regPath = groupItem.GroupPath; - else if (regPath.StartsWith("\\")) regPath = groupItem.GroupPath + regPath; + if(string.IsNullOrEmpty(regPath)) regPath = groupItem.GroupPath; + else if(regPath.StartsWith("\\")) regPath = groupItem.GroupPath + regPath; return regPath; - } - ; + }; // 遍历groupItem内所有Item节点 - foreach (XmlElement itemXE in groupXN.SelectNodes("Item")) + foreach(XmlElement itemXE in groupXN.SelectNodes("Item")) { try { - if (!XmlDicHelper.JudgeOSVersion(itemXE)) continue; + if(!XmlDicHelper.JudgeOSVersion(itemXE)) continue; RuleItem ruleItem; ItemInfo info = new ItemInfo(); // 获取文本、提示文本 - foreach (XmlElement textXE in itemXE.SelectNodes("Text")) + foreach(XmlElement textXE in itemXE.SelectNodes("Text")) { - if (XmlDicHelper.JudgeCulture(textXE)) info.Text = ResourceString.GetDirectString(textXE.GetAttribute("Value")); + if(XmlDicHelper.JudgeCulture(textXE)) info.Text = ResourceString.GetDirectString(textXE.GetAttribute("Value")); } - foreach (XmlElement tipXE in itemXE.SelectNodes("Tip")) + foreach(XmlElement tipXE in itemXE.SelectNodes("Tip")) { - if (XmlDicHelper.JudgeCulture(tipXE)) info.Tip = ResourceString.GetDirectString(tipXE.GetAttribute("Value")); + if(XmlDicHelper.JudgeCulture(tipXE)) info.Tip = ResourceString.GetDirectString(tipXE.GetAttribute("Value")); } info.RestartExplorer = itemXE.SelectSingleNode("RestartExplorer") != null; // 如果是数值类型的,初始化默认值、最大值、最小值 int defaultValue = 0, maxValue = 0, minValue = 0; - if (itemXE.SelectSingleNode("IsNumberItem") != null) + if(itemXE.SelectSingleNode("IsNumberItem") != null) { XmlElement ruleXE = (XmlElement)itemXE.SelectSingleNode("Rule"); defaultValue = ruleXE.HasAttribute("Default") ? Convert.ToInt32(ruleXE.GetAttribute("Default")) : 0; @@ -116,14 +116,14 @@ string GetRuleFullRegPath(string regPath) } // 建立三种类型的RuleItem - if (isIniGroup) + if(isIniGroup) { XmlElement ruleXE = (XmlElement)itemXE.SelectSingleNode("Rule"); string iniPath = ruleXE.GetAttribute("FilePath"); if (iniPath.IsNullOrWhiteSpace()) iniPath = groupItem.GroupPath; string section = ruleXE.GetAttribute("Section"); string keyName = ruleXE.GetAttribute("KeyName"); - if (itemXE.SelectSingleNode("IsNumberItem") != null) + if(itemXE.SelectSingleNode("IsNumberItem") != null) { var rule = new NumberIniRuleItem.IniRule { @@ -136,7 +136,7 @@ string GetRuleFullRegPath(string regPath) }; ruleItem = new NumberIniRuleItem(rule, info); } - else if (itemXE.SelectSingleNode("IsStringItem") != null) + else if(itemXE.SelectSingleNode("IsStringItem") != null) { var rule = new StringIniRuleItem.IniRule { @@ -175,7 +175,7 @@ string GetRuleFullRegPath(string regPath) }; ruleItem = new NumberRegRuleItem(rule, info); } - else if (itemXE.SelectSingleNode("IsStringItem") != null) + else if(itemXE.SelectSingleNode("IsStringItem") != null) { XmlElement ruleXE = (XmlElement)itemXE.SelectSingleNode("Rule"); var rule = new StringRegRuleItem.RegRule @@ -189,7 +189,7 @@ string GetRuleFullRegPath(string regPath) { XmlNodeList ruleXNList = itemXE.SelectNodes("Rule"); var rules = new VisibleRegRuleItem.RegRule[ruleXNList.Count]; - for (int i = 0; i < ruleXNList.Count; i++) + for(int i = 0; i < ruleXNList.Count; i++) { XmlElement ruleXE = (XmlElement)ruleXNList[i]; rules[i] = new VisibleRegRuleItem.RegRule @@ -200,16 +200,16 @@ string GetRuleFullRegPath(string regPath) }; string turnOn = ruleXE.HasAttribute("On") ? ruleXE.GetAttribute("On") : null; string turnOff = ruleXE.HasAttribute("Off") ? ruleXE.GetAttribute("Off") : null; - switch (rules[i].ValueKind) + switch(rules[i].ValueKind) { case RegistryValueKind.Binary: rules[i].TurnOnValue = turnOn != null ? XmlDicHelper.ConvertToBinary(turnOn) : null; rules[i].TurnOffValue = turnOff != null ? XmlDicHelper.ConvertToBinary(turnOff) : null; break; case RegistryValueKind.DWord: - if (turnOn == null) rules[i].TurnOnValue = null; + if(turnOn == null) rules[i].TurnOnValue = null; else rules[i].TurnOnValue = Convert.ToInt32(turnOn); - if (turnOff == null) rules[i].TurnOffValue = null; + if(turnOff == null) rules[i].TurnOffValue = null; else rules[i].TurnOffValue = Convert.ToInt32(turnOff); break; default: diff --git a/ContextMenuManager/Controls/DictionariesBox.cs b/ContextMenuManager/Controls/DictionariesBox.cs index 92feeadc..7aa7ca68 100644 --- a/ContextMenuManager/Controls/DictionariesBox.cs +++ b/ContextMenuManager/Controls/DictionariesBox.cs @@ -16,15 +16,15 @@ public DictionariesBox() SuspendLayout(); Dock = DockStyle.Fill; Controls.AddRange(pages); - ForeColor = MyMainForm.FormFore; - BackColor = MyMainForm.FormBack; + ForeColor = DarkModeHelper.FormFore; // 修改这里 + BackColor = DarkModeHelper.FormBack; // 修改这里 Font = SystemFonts.MenuFont; Font = new Font(Font.FontFamily, Font.Size + 1F); cms.Items.AddRange(items); - for (int i = 0; i < 6; i++) + for(int i = 0; i < 6; i++) { boxs[i] = new ReadOnlyRichTextBox { Parent = pages[i] }; - if (i > 0) boxs[i].ContextMenuStrip = cms; + if(i > 0) boxs[i].ContextMenuStrip = cms; } items[0].Click += (sender, e) => ExternalProgram.OpenNotepadWithText(GetInitialText()); items[2].Click += (sender, e) => SaveFile(); @@ -62,10 +62,10 @@ public DictionariesBox() private void SaveFile() { - using (SaveFileDialog dlg = new SaveFileDialog()) + using(SaveFileDialog dlg = new SaveFileDialog()) { string dirPath = AppConfig.UserDicsDir; - switch (SelectedIndex) + switch(SelectedIndex) { case 1: dirPath = AppConfig.LangsDir; @@ -87,7 +87,7 @@ private void SaveFile() dlg.Filter = $"{dlg.FileName}|*{Path.GetExtension(dlg.FileName)}"; Directory.CreateDirectory(dirPath); dlg.InitialDirectory = dirPath; - if (dlg.ShowDialog() == DialogResult.OK) + if(dlg.ShowDialog() == DialogResult.OK) { File.WriteAllText(dlg.FileName, GetInitialText(), Encoding.Unicode); } @@ -96,7 +96,7 @@ private void SaveFile() private string GetInitialText() { - switch (SelectedIndex) + switch(SelectedIndex) { case 0: return AppString.Other.Dictionaries; @@ -118,9 +118,9 @@ private string GetInitialText() public void LoadText() { int index = SelectedIndex; - if (boxs[index].Text.Length > 0) return; + if(boxs[index].Text.Length > 0) return; Action action = null; - switch (index) + switch(index) { case 0: case 1: diff --git a/ContextMenuManager/Controls/DonateBox.cs b/ContextMenuManager/Controls/DonateBox.cs index 785d3075..0d06e59f 100644 --- a/ContextMenuManager/Controls/DonateBox.cs +++ b/ContextMenuManager/Controls/DonateBox.cs @@ -16,8 +16,8 @@ public DonateBox() SuspendLayout(); AutoScroll = true; Dock = DockStyle.Fill; - ForeColor = MyMainForm.FormFore; - BackColor = MyMainForm.FormBack; + ForeColor = DarkModeHelper.FormFore; // 修改这里 + BackColor = DarkModeHelper.FormBack; // 修改这里 Font = SystemFonts.MenuFont; Font = new Font(Font.FontFamily, Font.Size + 1F); Controls.AddRange(new Control[] { lblInfo, picQR, lblList }); @@ -36,7 +36,7 @@ public DonateBox() readonly Label lblList = new Label { - ForeColor = MyMainForm.FormFore, + ForeColor = DarkModeHelper.FormFore, // 修改这里 Text = AppString.Other.DonationList, Cursor = Cursors.Hand, AutoSize = true @@ -56,7 +56,7 @@ public DonateBox() private static Image GetSingleQR(int index) { Bitmap bitmap = new Bitmap(200, 200); - using (Graphics g = Graphics.FromImage(bitmap)) + using(Graphics g = Graphics.FromImage(bitmap)) { Rectangle destRect = new Rectangle(0, 0, 200, 200); Rectangle srcRect = new Rectangle(index * 200, 0, 200, 200); @@ -79,10 +79,10 @@ protected override void OnResize(EventArgs e) private void SwitchQR(object sender, MouseEventArgs e) { - if (picQR.Image == AllQR) + if(picQR.Image == AllQR) { - if (e.X < 200) picQR.Image = WechatQR; - else if (e.X < 400) picQR.Image = AlipayQR; + if(e.X < 200) picQR.Image = WechatQR; + else if(e.X < 400) picQR.Image = AlipayQR; else picQR.Image = QQQR; } else @@ -94,14 +94,14 @@ private void SwitchQR(object sender, MouseEventArgs e) private void ShowDonateDialog() { Cursor = Cursors.WaitCursor; - using (UAWebClient client = new UAWebClient()) + using(UAWebClient client = new UAWebClient()) { string url = AppConfig.RequestUseGithub ? AppConfig.GithubDonateRaw : AppConfig.GiteeDonateRaw; string contents = client.GetWebString(url); //contents = System.IO.File.ReadAllText(@"..\..\..\Donate.md");//用于求和更新Donate.md文件 - if (contents == null) + if(contents == null) { - if (AppMessageBox.Show(AppString.Message.WebDataReadFailed + "\r\n" + if(AppMessageBox.Show(AppString.Message.WebDataReadFailed + "\r\n" + AppString.Message.OpenWebUrl, MessageBoxButtons.OKCancel) == DialogResult.OK) { url = AppConfig.RequestUseGithub ? AppConfig.GithubDonate : AppConfig.GiteeDonate; @@ -110,7 +110,7 @@ private void ShowDonateDialog() } else { - using (DonateListDialog dlg = new DonateListDialog()) + using(DonateListDialog dlg = new DonateListDialog()) { dlg.DanateData = contents; dlg.ShowDialog(); @@ -128,7 +128,7 @@ public override void Reset() { } protected override bool RunDialog(IntPtr hwndOwner) { - using (DonateListForm frm = new DonateListForm()) + using(DonateListForm frm = new DonateListForm()) { frm.ShowDonateList(DanateData); MainForm mainForm = (MainForm)FromHandle(hwndOwner); @@ -156,7 +156,7 @@ public DonateListForm() = dgvDonate.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter; Controls.AddRange(new Control[] { lblThank, lblDonate, dgvDonate }); - lblThank.MouseEnter += (sender, e) => lblThank.ForeColor = MyMainForm.MainColor; + lblThank.MouseEnter += (sender, e) => lblThank.ForeColor = DarkModeHelper.MainColor; // 修改这里 lblThank.MouseLeave += (sender, e) => lblThank.ForeColor = Color.DimGray;//Fixed lblDonate.Resize += (sender, e) => OnResize(null); this.AddEscapeButton(); @@ -202,21 +202,21 @@ public void ShowDonateList(string contents) { string[] lines = contents.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries); int index = Array.FindIndex(lines, line => line == "|:--:|:--:|:--:|:--:|:--:"); - if (index == -1) return; + if(index == -1) return; string[] heads = lines[index - 1].Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); dgvDonate.ColumnCount = heads.Length; dgvDonate.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - for (int m = 0; m < heads.Length; m++) + for(int m = 0; m < heads.Length; m++) { dgvDonate.Columns[m].HeaderText = heads[m]; } - for (int n = index + 1; n < lines.Length; n++) + for(int n = index + 1; n < lines.Length; n++) { string[] strs = lines[n].Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); object[] values = new object[strs.Length]; - for (int k = 0; k < strs.Length; k++) + for(int k = 0; k < strs.Length; k++) { - switch (k) + switch(k) { case 3: values[k] = Convert.ToSingle(strs[k]); diff --git a/ContextMenuManager/Controls/EnhanceMenuList.cs b/ContextMenuManager/Controls/EnhanceMenuList.cs index d2c9ff74..21c52ef7 100644 --- a/ContextMenuManager/Controls/EnhanceMenuList.cs +++ b/ContextMenuManager/Controls/EnhanceMenuList.cs @@ -15,26 +15,26 @@ public override void LoadItems() base.LoadItems(); int index = UseUserDic ? 1 : 0; XmlDocument doc = XmlDicHelper.EnhanceMenusDic[index]; - if (doc?.DocumentElement == null) return; - foreach (XmlNode xn in doc.DocumentElement.ChildNodes) + if(doc?.DocumentElement == null) return; + foreach(XmlNode xn in doc.DocumentElement.ChildNodes) { try { Image image = null; string text = null; string path = xn.SelectSingleNode("RegPath")?.InnerText; - foreach (XmlElement textXE in xn.SelectNodes("Text")) + foreach(XmlElement textXE in xn.SelectNodes("Text")) { - if (XmlDicHelper.JudgeCulture(textXE)) + if(XmlDicHelper.JudgeCulture(textXE)) { text = ResourceString.GetDirectString(textXE.GetAttribute("Value")); } } - if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(text)) continue; - if (!string.IsNullOrEmpty(ScenePath) && !path.Equals(ScenePath, StringComparison.OrdinalIgnoreCase)) continue; + if(string.IsNullOrEmpty(path) || string.IsNullOrEmpty(text)) continue; + if(!string.IsNullOrEmpty(ScenePath) && !path.Equals(ScenePath, StringComparison.OrdinalIgnoreCase)) continue; string iconLocation = xn.SelectSingleNode("Icon")?.InnerText; - using (Icon icon = ResourceIcon.GetIcon(iconLocation)) + using(Icon icon = ResourceIcon.GetIcon(iconLocation)) { image = icon?.ToBitmap(); image = image ?? AppImage.NotFound; @@ -47,8 +47,8 @@ public override void LoadItems() AddItem(groupItem); XmlNode shellXN = xn.SelectSingleNode("Shell"); XmlNode shellExXN = xn.SelectSingleNode("ShellEx"); - if (shellXN != null) LoadShellItems(shellXN, groupItem); - if (shellExXN != null) LoadShellExItems(shellExXN, groupItem); + if(shellXN != null) LoadShellItems(shellXN, groupItem); + if(shellExXN != null) LoadShellExItems(shellExXN, groupItem); groupItem.SetVisibleWithSubItemCount(); } catch { continue; } @@ -57,33 +57,33 @@ public override void LoadItems() private void LoadShellItems(XmlNode shellXN, FoldGroupItem groupItem) { - foreach (XmlElement itemXE in shellXN.SelectNodes("Item")) + foreach(XmlElement itemXE in shellXN.SelectNodes("Item")) { - if (!XmlDicHelper.FileExists(itemXE)) continue; - if (!XmlDicHelper.JudgeCulture(itemXE)) continue; - if (!XmlDicHelper.JudgeOSVersion(itemXE)) continue; + if(!XmlDicHelper.FileExists(itemXE)) continue; + if(!XmlDicHelper.JudgeCulture(itemXE)) continue; + if(!XmlDicHelper.JudgeOSVersion(itemXE)) continue; string keyName = itemXE.GetAttribute("KeyName"); - if (keyName.IsNullOrWhiteSpace()) continue; + if(keyName.IsNullOrWhiteSpace()) continue; EnhanceShellItem item = new EnhanceShellItem() { RegPath = $@"{groupItem.GroupPath}\shell\{keyName}", FoldGroupItem = groupItem, ItemXE = itemXE }; - foreach (XmlElement szXE in itemXE.SelectNodes("Value/REG_SZ")) + foreach(XmlElement szXE in itemXE.SelectNodes("Value/REG_SZ")) { - if (!XmlDicHelper.JudgeCulture(szXE)) continue; - if (szXE.HasAttribute("MUIVerb")) item.Text = ResourceString.GetDirectString(szXE.GetAttribute("MUIVerb")); - if (szXE.HasAttribute("Icon")) item.Image = ResourceIcon.GetIcon(szXE.GetAttribute("Icon"))?.ToBitmap(); - else if (szXE.HasAttribute("HasLUAShield")) item.Image = AppImage.Shield; + if(!XmlDicHelper.JudgeCulture(szXE)) continue; + if(szXE.HasAttribute("MUIVerb")) item.Text = ResourceString.GetDirectString(szXE.GetAttribute("MUIVerb")); + if(szXE.HasAttribute("Icon")) item.Image = ResourceIcon.GetIcon(szXE.GetAttribute("Icon"))?.ToBitmap(); + else if(szXE.HasAttribute("HasLUAShield")) item.Image = AppImage.Shield; } - if (item.Image == null) + if(item.Image == null) { XmlElement cmdXE = (XmlElement)itemXE.SelectSingleNode("SubKey/Command"); - if (cmdXE != null) + if(cmdXE != null) { Icon icon = null; - if (cmdXE.HasAttribute("Default")) + if(cmdXE.HasAttribute("Default")) { string filePath = ObjectPath.ExtractFilePath(cmdXE.GetAttribute("Default")); icon = ResourceIcon.GetIcon(filePath); @@ -91,7 +91,7 @@ private void LoadShellItems(XmlNode shellXN, FoldGroupItem groupItem) else { XmlNode fileXE = cmdXE.SelectSingleNode("FileName"); - if (fileXE != null) + if(fileXE != null) { string filePath = ObjectPath.ExtractFilePath(fileXE.InnerText); icon = ResourceIcon.GetIcon(filePath); @@ -101,16 +101,16 @@ private void LoadShellItems(XmlNode shellXN, FoldGroupItem groupItem) icon?.Dispose(); } } - if (item.Image == null) item.Image = AppImage.NotFound; - if (item.Text.IsNullOrWhiteSpace()) item.Text = keyName; + if(item.Image == null) item.Image = AppImage.NotFound; + if(item.Text.IsNullOrWhiteSpace()) item.Text = keyName; string tip = ""; - foreach (XmlElement tipXE in itemXE.SelectNodes("Tip")) + foreach(XmlElement tipXE in itemXE.SelectNodes("Tip")) { - if (XmlDicHelper.JudgeCulture(tipXE)) tip = tipXE.GetAttribute("Value"); + if(XmlDicHelper.JudgeCulture(tipXE)) tip = tipXE.GetAttribute("Value"); } - if (itemXE.GetElementsByTagName("CreateFile").Count > 0) + if(itemXE.GetElementsByTagName("CreateFile").Count > 0) { - if (!tip.IsNullOrWhiteSpace()) tip += "\n"; + if(!tip.IsNullOrWhiteSpace()) tip += "\n"; tip += AppString.Tip.CommandFiles; } ToolTipBox.SetToolTip(item.ChkVisible, tip); @@ -122,12 +122,12 @@ private void LoadShellItems(XmlNode shellXN, FoldGroupItem groupItem) private void LoadShellExItems(XmlNode shellExXN, FoldGroupItem groupItem) { - foreach (XmlNode itemXN in shellExXN.SelectNodes("Item")) + foreach(XmlNode itemXN in shellExXN.SelectNodes("Item")) { - if (!XmlDicHelper.FileExists(itemXN)) continue; - if (!XmlDicHelper.JudgeCulture(itemXN)) continue; - if (!XmlDicHelper.JudgeOSVersion(itemXN)) continue; - if (!GuidEx.TryParse(itemXN.SelectSingleNode("Guid")?.InnerText, out Guid guid)) continue; + if(!XmlDicHelper.FileExists(itemXN)) continue; + if(!XmlDicHelper.JudgeCulture(itemXN)) continue; + if(!XmlDicHelper.JudgeOSVersion(itemXN)) continue; + if(!GuidEx.TryParse(itemXN.SelectSingleNode("Guid")?.InnerText, out Guid guid)) continue; EnhanceShellExItem item = new EnhanceShellExItem { FoldGroupItem = groupItem, @@ -136,19 +136,19 @@ private void LoadShellExItems(XmlNode shellExXN, FoldGroupItem groupItem) DefaultKeyName = itemXN.SelectSingleNode("KeyName")?.InnerText, Guid = guid }; - foreach (XmlNode textXE in itemXN.SelectNodes("Text")) + foreach(XmlNode textXE in itemXN.SelectNodes("Text")) { - if (XmlDicHelper.JudgeCulture(textXE)) + if(XmlDicHelper.JudgeCulture(textXE)) { item.Text = ResourceString.GetDirectString(textXE.InnerText); } } - if (item.Text.IsNullOrWhiteSpace()) item.Text = GuidInfo.GetText(guid); - if (item.DefaultKeyName.IsNullOrWhiteSpace()) item.DefaultKeyName = guid.ToString("B"); + if(item.Text.IsNullOrWhiteSpace()) item.Text = GuidInfo.GetText(guid); + if(item.DefaultKeyName.IsNullOrWhiteSpace()) item.DefaultKeyName = guid.ToString("B"); string tip = ""; - foreach (XmlElement tipXE in itemXN.SelectNodes("Tip")) + foreach(XmlElement tipXE in itemXN.SelectNodes("Tip")) { - if (XmlDicHelper.JudgeCulture(tipXE)) tip = tipXE.GetAttribute("Text"); + if(XmlDicHelper.JudgeCulture(tipXE)) tip = tipXE.GetAttribute("Text"); } ToolTipBox.SetToolTip(item.ChkVisible, tip); string itemText = item.Text; diff --git a/ContextMenuManager/Controls/EnhanceMenusDialog.cs b/ContextMenuManager/Controls/EnhanceMenusDialog.cs index 40c132c6..1a76b68f 100644 --- a/ContextMenuManager/Controls/EnhanceMenusDialog.cs +++ b/ContextMenuManager/Controls/EnhanceMenusDialog.cs @@ -13,8 +13,8 @@ public override void Reset() { } protected override bool RunDialog(IntPtr hwndOwner) { - using (SubItemsForm frm = new SubItemsForm()) - using (EnhanceMenuList list = new EnhanceMenuList()) + using(SubItemsForm frm = new SubItemsForm()) + using(EnhanceMenuList list = new EnhanceMenuList()) { frm.Text = AppString.SideBar.EnhanceMenu; frm.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); diff --git a/ContextMenuManager/Controls/EnhanceMenusItem.cs b/ContextMenuManager/Controls/EnhanceMenusItem.cs index 0c18bf40..bd1c4a38 100644 --- a/ContextMenuManager/Controls/EnhanceMenusItem.cs +++ b/ContextMenuManager/Controls/EnhanceMenusItem.cs @@ -21,12 +21,12 @@ public bool ItemVisible { get { - using (RegistryKey key = RegistryEx.GetRegistryKey(RegPath)) + using(RegistryKey key = RegistryEx.GetRegistryKey(RegPath)) return key != null; } set { - if (value) WriteSubKeysValue(ItemXE, RegPath); + if(value) WriteSubKeysValue(ItemXE, RegPath); else RegistryEx.DeleteKeyTree(RegPath); } } @@ -39,21 +39,21 @@ public EnhanceShellItem() private static void WriteAttributesValue(XmlNode valueXN, string regPath) { - if (valueXN == null) return; - if (!XmlDicHelper.FileExists(valueXN)) return; - if (!XmlDicHelper.JudgeCulture(valueXN)) return; - if (!XmlDicHelper.JudgeOSVersion(valueXN)) return; - using (RegistryKey key = RegistryEx.GetRegistryKey(regPath, true, true)) + if(valueXN == null) return; + if(!XmlDicHelper.FileExists(valueXN)) return; + if(!XmlDicHelper.JudgeCulture(valueXN)) return; + if(!XmlDicHelper.JudgeOSVersion(valueXN)) return; + using(RegistryKey key = RegistryEx.GetRegistryKey(regPath, true, true)) { - foreach (XmlNode xn in valueXN.ChildNodes) + foreach(XmlNode xn in valueXN.ChildNodes) { - if (xn is XmlComment) continue; - if (!XmlDicHelper.FileExists(xn)) continue; - if (!XmlDicHelper.JudgeCulture(xn)) continue; - if (!XmlDicHelper.JudgeOSVersion(xn)) continue; - foreach (XmlAttribute xa in xn.Attributes) + if(xn is XmlComment) continue; + if(!XmlDicHelper.FileExists(xn)) continue; + if(!XmlDicHelper.JudgeCulture(xn)) continue; + if(!XmlDicHelper.JudgeOSVersion(xn)) continue; + foreach(XmlAttribute xa in xn.Attributes) { - switch (xn.Name) + switch(xn.Name) { case "REG_SZ": key.SetValue(xa.Name, Environment.ExpandEnvironmentVariables(xa.Value), RegistryValueKind.String); @@ -76,17 +76,17 @@ private static void WriteAttributesValue(XmlNode valueXN, string regPath) private static void WriteSubKeysValue(XmlNode keyXN, string regPath) { - if (keyXN == null) return; - if (!XmlDicHelper.FileExists(keyXN)) return; - if (!XmlDicHelper.JudgeCulture(keyXN)) return; - if (!XmlDicHelper.JudgeOSVersion(keyXN)) return; + if(keyXN == null) return; + if(!XmlDicHelper.FileExists(keyXN)) return; + if(!XmlDicHelper.JudgeCulture(keyXN)) return; + if(!XmlDicHelper.JudgeOSVersion(keyXN)) return; string defaultValue = ((XmlElement)keyXN).GetAttribute("Default"); - if (!defaultValue.IsNullOrWhiteSpace()) + if(!defaultValue.IsNullOrWhiteSpace()) { defaultValue = Environment.ExpandEnvironmentVariables(defaultValue); Registry.SetValue(regPath, "", defaultValue); } - else if (keyXN.Name == "Command") + else if(keyXN.Name == "Command") { //按照规则Command节点无默认值则创建文件 WriteCommandValue(keyXN, regPath); @@ -94,11 +94,11 @@ private static void WriteSubKeysValue(XmlNode keyXN, string regPath) WriteAttributesValue(keyXN.SelectSingleNode("Value"), regPath); XmlNode subKeyXN = keyXN.SelectSingleNode("SubKey"); - if (subKeyXN != null) + if(subKeyXN != null) { - foreach (XmlNode xn in subKeyXN.ChildNodes) + foreach(XmlNode xn in subKeyXN.ChildNodes) { - if (xn is XmlComment) continue; + if(xn is XmlComment) continue; WriteSubKeysValue(xn, $@"{regPath}\{xn.Name}"); } } @@ -113,14 +113,14 @@ private static void WriteCommandValue(XmlNode cmdXE, string regPath) string command; string fileName = fnXE?.InnerText.Trim(); string arguments = argXE?.InnerText.Trim(); - if (string.IsNullOrEmpty(fileName)) fileName = CreateCommandFile(fnXE); - if (string.IsNullOrEmpty(arguments)) arguments = CreateCommandFile(argXE); + if(string.IsNullOrEmpty(fileName)) fileName = CreateCommandFile(fnXE); + if(string.IsNullOrEmpty(arguments)) arguments = CreateCommandFile(argXE); fileName = Environment.ExpandEnvironmentVariables(fileName); arguments = Environment.ExpandEnvironmentVariables(arguments); string prefix = argXE?.GetAttribute("Prefix");//参数前缀 string suffix = argXE?.GetAttribute("Suffix");//参数后缀 arguments = prefix + arguments + suffix; - if (seXE != null) + if(seXE != null) { string verb = seXE.HasAttribute("Verb") ? seXE.GetAttribute("Verb") : "open"; int windowStyle = seXE.HasAttribute("WindowStyle") ? Convert.ToInt32(seXE.GetAttribute("WindowStyle")) : 1; @@ -130,7 +130,7 @@ private static void WriteCommandValue(XmlNode cmdXE, string regPath) else { command = fileName; - if (arguments != string.Empty) command += $" {arguments}"; + if(arguments != string.Empty) command += $" {arguments}"; } Registry.SetValue(regPath, "", command); } @@ -138,19 +138,19 @@ private static void WriteCommandValue(XmlNode cmdXE, string regPath) private static string CreateCommandFile(XmlNode xe) { string path = string.Empty; - if (xe == null) return path; - foreach (XmlElement cfXE in xe.SelectNodes("CreateFile")) + if(xe == null) return path; + foreach(XmlElement cfXE in xe.SelectNodes("CreateFile")) { - if (!XmlDicHelper.FileExists(cfXE)) continue; - if (!XmlDicHelper.JudgeCulture(cfXE)) continue; - if (!XmlDicHelper.JudgeOSVersion(cfXE)) continue; + if(!XmlDicHelper.FileExists(cfXE)) continue; + if(!XmlDicHelper.JudgeCulture(cfXE)) continue; + if(!XmlDicHelper.JudgeOSVersion(cfXE)) continue; string fileName = cfXE.GetAttribute("FileName"); string content = cfXE.GetAttribute("Content"); string extension = Path.GetExtension(fileName).ToLower(); string filePath = $@"{AppConfig.ProgramsDir}\{fileName}"; - if (path == string.Empty) path = filePath; + if(path == string.Empty) path = filePath; Encoding encoding; - switch (extension) + switch(extension) { case ".bat": case ".cmd": @@ -181,7 +181,7 @@ public bool ItemVisible get => ShellExItem.GetPathAndGuids(ShellExPath).Values.Contains(Guid); set { - if (value) + if(value) { string regPath = ObjectPath.GetNewPathWithIndex(RegPath, ObjectPath.PathType.Registry); Registry.SetValue(regPath, "", Guid.ToString("B")); @@ -189,9 +189,9 @@ public bool ItemVisible else { Dictionary dic = ShellExItem.GetPathAndGuids(ShellExPath); - foreach (string regPath in dic.Keys) + foreach(string regPath in dic.Keys) { - if (dic[regPath].Equals(Guid)) + if(dic[regPath].Equals(Guid)) RegistryEx.DeleteKeyTree(regPath); } } diff --git a/ContextMenuManager/Controls/ExplorerRestarter.cs b/ContextMenuManager/Controls/ExplorerRestarter.cs index 437250fc..0106e399 100644 --- a/ContextMenuManager/Controls/ExplorerRestarter.cs +++ b/ContextMenuManager/Controls/ExplorerRestarter.cs @@ -34,7 +34,7 @@ public ExplorerRestarter() { bool flag = base.Visible != value && Parent != null; base.Visible = value; - if (flag) Parent.Height += value ? Height : -Height; + if(flag) Parent.Height += value ? Height : -Height; } } diff --git a/ContextMenuManager/Controls/FileExtensionDialog.cs b/ContextMenuManager/Controls/FileExtensionDialog.cs index 1cd448ed..98761e9e 100644 --- a/ContextMenuManager/Controls/FileExtensionDialog.cs +++ b/ContextMenuManager/Controls/FileExtensionDialog.cs @@ -43,11 +43,11 @@ public static List FileExtensionItems protected override bool RunDialog(IntPtr hwndOwner) { bool flag = base.RunDialog(hwndOwner); - if (flag) + if(flag) { string extension = ObjectPath.RemoveIllegalChars(Extension); int index = extension.LastIndexOf('.'); - if (index >= 0) Extension = extension.Substring(index); + if(index >= 0) Extension = extension.Substring(index); else Extension = $".{extension}"; } return flag; diff --git a/ContextMenuManager/Controls/FoldSubItem.cs b/ContextMenuManager/Controls/FoldSubItem.cs index 94842df5..613a7b98 100644 --- a/ContextMenuManager/Controls/FoldSubItem.cs +++ b/ContextMenuManager/Controls/FoldSubItem.cs @@ -30,7 +30,7 @@ public bool IsFold get => isFold; set { - if (isFold == value) return; + if(isFold == value) return; isFold = value; FoldMe(value); } @@ -51,13 +51,13 @@ public FoldGroupItem(string groupPath, PathType pathType) BtnShowMenu = new MenuButton(this); btnOpenPath = new PictureButton(AppImage.Open); - if (pathType == PathType.File || pathType == PathType.Directory) + if(pathType == PathType.File || pathType == PathType.Directory) { groupPath = Environment.ExpandEnvironmentVariables(groupPath); } string tip = null; Action openPath = null; - switch (pathType) + switch(pathType) { case PathType.File: tip = AppString.Menu.FileLocation; @@ -83,7 +83,7 @@ public FoldGroupItem(string groupPath, PathType pathType) ContextMenuStrip.Items.AddRange(new[] { tsiFoldAll, tsiUnfoldAll }); MouseDown += (sender, e) => { - if (e.Button == MouseButtons.Left) Fold(); + if(e.Button == MouseButtons.Left) Fold(); }; btnFold.MouseDown += (sender, e) => { @@ -98,9 +98,9 @@ public FoldGroupItem(string groupPath, PathType pathType) public void SetVisibleWithSubItemCount() { - foreach (Control ctr in Parent.Controls) + foreach(Control ctr in Parent.Controls) { - if (ctr is FoldSubItem item && item.FoldGroupItem == this) + if(ctr is FoldSubItem item && item.FoldGroupItem == this) { Visible = true; return; @@ -119,18 +119,18 @@ private void Fold() private void FoldMe(bool isFold) { btnFold.BaseImage = isFold ? AppImage.Down : AppImage.Up; - foreach (Control ctr in Parent?.Controls) + foreach(Control ctr in Parent?.Controls) { - if (ctr is FoldSubItem item && item.FoldGroupItem == this) ctr.Visible = !isFold; + if(ctr is FoldSubItem item && item.FoldGroupItem == this) ctr.Visible = !isFold; } } private void FoldAll(bool isFold) { Parent.SuspendLayout(); - foreach (Control ctr in Parent.Controls) + foreach(Control ctr in Parent.Controls) { - if (ctr is FoldGroupItem groupItem) groupItem.IsFold = isFold; + if(ctr is FoldGroupItem groupItem) groupItem.IsFold = isFold; } Parent.ResumeLayout(); } diff --git a/ContextMenuManager/Controls/GuidBlockedItem.cs b/ContextMenuManager/Controls/GuidBlockedItem.cs index 5465b9aa..9c25b2ca 100644 --- a/ContextMenuManager/Controls/GuidBlockedItem.cs +++ b/ContextMenuManager/Controls/GuidBlockedItem.cs @@ -14,7 +14,7 @@ public GuidBlockedItem(string value) { InitializeComponents(); Value = value; - if (GuidEx.TryParse(value, out Guid guid)) + if(GuidEx.TryParse(value, out Guid guid)) { Guid = guid; Image = GuidInfo.GetImage(guid); @@ -36,12 +36,12 @@ public string RegPath { get { - foreach (string path in GuidBlockedList.BlockedPaths) + foreach(string path in GuidBlockedList.BlockedPaths) { - using (var key = RegistryEx.GetRegistryKey(path)) + using(var key = RegistryEx.GetRegistryKey(path)) { - if (key == null) continue; - if (key.GetValueNames().Contains(Value, StringComparer.OrdinalIgnoreCase)) return path; + if(key == null) continue; + if(key.GetValueNames().Contains(Value, StringComparer.OrdinalIgnoreCase)) return path; } } return null; @@ -53,7 +53,7 @@ public string ItemText get { string text; - if (GuidEx.TryParse(Value, out Guid guid)) text = GuidInfo.GetText(guid); + if(GuidEx.TryParse(Value, out Guid guid)) text = GuidInfo.GetText(guid); else text = AppString.Message.MalformedGuid; text += "\n" + Value; return text; @@ -92,9 +92,9 @@ private void InitializeComponents() public void DeleteMe() { - if (AppMessageBox.Show(AppString.Message.ConfirmDelete, MessageBoxButtons.YesNo) != DialogResult.Yes) return; + if(AppMessageBox.Show(AppString.Message.ConfirmDelete, MessageBoxButtons.YesNo) != DialogResult.Yes) return; Array.ForEach(GuidBlockedList.BlockedPaths, path => RegistryEx.DeleteValue(path, Value)); - if (!Guid.Equals(Guid.Empty)) ExplorerRestarter.Show(); + if(!Guid.Equals(Guid.Empty)) ExplorerRestarter.Show(); int index = Parent.Controls.GetChildIndex(this); index -= (index < Parent.Controls.Count - 1) ? 0 : 1; Parent.Controls[index].Focus(); diff --git a/ContextMenuManager/Controls/GuidBlockedList.cs b/ContextMenuManager/Controls/GuidBlockedList.cs index f1980c91..a0964df8 100644 --- a/ContextMenuManager/Controls/GuidBlockedList.cs +++ b/ContextMenuManager/Controls/GuidBlockedList.cs @@ -24,14 +24,14 @@ public void LoadItems() private void LoadBlockedItems() { List values = new List(); - foreach (string path in BlockedPaths) + foreach(string path in BlockedPaths) { - using (RegistryKey key = RegistryEx.GetRegistryKey(path)) + using(RegistryKey key = RegistryEx.GetRegistryKey(path)) { - if (key == null) continue; - foreach (string value in key.GetValueNames()) + if(key == null) continue; + foreach(string value in key.GetValueNames()) { - if (values.Contains(value, StringComparer.OrdinalIgnoreCase)) continue; + if(values.Contains(value, StringComparer.OrdinalIgnoreCase)) continue; AddItem(new GuidBlockedItem(value)); values.Add(value); } @@ -45,17 +45,17 @@ private void AddNewItem() AddItem(newItem); newItem.AddNewItem += () => { - using (InputDialog dlg = new InputDialog { Title = AppString.Dialog.InputGuid }) + using(InputDialog dlg = new InputDialog { Title = AppString.Dialog.InputGuid }) { - if (GuidEx.TryParse(Clipboard.GetText(), out Guid guid)) dlg.Text = guid.ToString(); - if (dlg.ShowDialog() != DialogResult.OK) return; - if (GuidEx.TryParse(dlg.Text, out guid)) + if(GuidEx.TryParse(Clipboard.GetText(), out Guid guid)) dlg.Text = guid.ToString(); + if(dlg.ShowDialog() != DialogResult.OK) return; + if(GuidEx.TryParse(dlg.Text, out guid)) { string value = guid.ToString("B"); Array.ForEach(BlockedPaths, path => Registry.SetValue(path, value, "")); - for (int i = 1; i < Controls.Count; i++) + for(int i = 1; i < Controls.Count; i++) { - if (((GuidBlockedItem)Controls[i]).Guid.Equals(guid)) + if(((GuidBlockedItem)Controls[i]).Guid.Equals(guid)) { AppMessageBox.Show(AppString.Message.HasBeenAdded); return; diff --git a/ContextMenuManager/Controls/IEItem.cs b/ContextMenuManager/Controls/IEItem.cs index ca65943f..65d93f85 100644 --- a/ContextMenuManager/Controls/IEItem.cs +++ b/ContextMenuManager/Controls/IEItem.cs @@ -43,7 +43,7 @@ public string ItemText { string newPath = $@"{RegistryEx.GetParentPath(RegPath)}\{value.Replace("\\", "")}"; string defaultValue = Registry.GetValue(newPath, "", null)?.ToString(); - if (!defaultValue.IsNullOrWhiteSpace()) + if(!defaultValue.IsNullOrWhiteSpace()) { AppMessageBox.Show(AppString.Message.HasBeenAdded); } diff --git a/ContextMenuManager/Controls/IEList.cs b/ContextMenuManager/Controls/IEList.cs index 8253f9d1..870b79f1 100644 --- a/ContextMenuManager/Controls/IEList.cs +++ b/ContextMenuManager/Controls/IEList.cs @@ -21,20 +21,20 @@ public void LoadItems() private void LoadIEItems() { List names = new List(); - using (RegistryKey ieKey = RegistryEx.GetRegistryKey(IEPath)) + using(RegistryKey ieKey = RegistryEx.GetRegistryKey(IEPath)) { - if (ieKey == null) return; - foreach (string part in IEItem.MeParts) + if(ieKey == null) return; + foreach(string part in IEItem.MeParts) { - using (RegistryKey meKey = ieKey.OpenSubKey(part)) + using(RegistryKey meKey = ieKey.OpenSubKey(part)) { - if (meKey == null) continue; - foreach (string keyName in meKey.GetSubKeyNames()) + if(meKey == null) continue; + foreach(string keyName in meKey.GetSubKeyNames()) { - if (names.Contains(keyName, StringComparer.OrdinalIgnoreCase)) continue; - using (RegistryKey key = meKey.OpenSubKey(keyName)) + if(names.Contains(keyName, StringComparer.OrdinalIgnoreCase)) continue; + using(RegistryKey key = meKey.OpenSubKey(keyName)) { - if (!string.IsNullOrEmpty(key.GetValue("")?.ToString())) + if(!string.IsNullOrEmpty(key.GetValue("")?.ToString())) { AddItem(new IEItem(key.Name)); names.Add(keyName); @@ -52,9 +52,9 @@ private void AddNewItem() AddItem(newItem); newItem.AddNewItem += () => { - using (NewIEDialog dlg = new NewIEDialog()) + using(NewIEDialog dlg = new NewIEDialog()) { - if (dlg.ShowDialog() != DialogResult.OK) return; + if(dlg.ShowDialog() != DialogResult.OK) return; InsertItem(new IEItem(dlg.RegPath), 1); } }; diff --git a/ContextMenuManager/Controls/Interfaces/IBtnDeleteItem.cs b/ContextMenuManager/Controls/Interfaces/IBtnDeleteItem.cs index 638a257a..d3358b67 100644 --- a/ContextMenuManager/Controls/Interfaces/IBtnDeleteItem.cs +++ b/ContextMenuManager/Controls/Interfaces/IBtnDeleteItem.cs @@ -18,7 +18,7 @@ public DeleteButton(IBtnDeleteItem item) : base(AppImage.Delete) listItem.AddCtr(this); MouseDown += (sender, e) => { - if (AppMessageBox.Show(AppString.Message.ConfirmDelete, MessageBoxButtons.YesNo) == DialogResult.Yes) item.DeleteMe(); + if(AppMessageBox.Show(AppString.Message.ConfirmDelete, MessageBoxButtons.YesNo) == DialogResult.Yes) item.DeleteMe(); }; } } diff --git a/ContextMenuManager/Controls/Interfaces/IBtnShowMenuItem.cs b/ContextMenuManager/Controls/Interfaces/IBtnShowMenuItem.cs index ad90118c..c2c77b9f 100644 --- a/ContextMenuManager/Controls/Interfaces/IBtnShowMenuItem.cs +++ b/ContextMenuManager/Controls/Interfaces/IBtnShowMenuItem.cs @@ -19,7 +19,7 @@ public MenuButton(IBtnShowMenuItem item) : base(AppImage.Setting) bool isShow = false; MouseDown += (sender, e) => { - if (!isShow) item.ContextMenuStrip.Show(this, 0, Height); + if(!isShow) item.ContextMenuStrip.Show(this, 0, Height); else item.ContextMenuStrip.Close(); isShow = !isShow; }; diff --git a/ContextMenuManager/Controls/Interfaces/IChkVisibleItem.cs b/ContextMenuManager/Controls/Interfaces/IChkVisibleItem.cs index bb079dcc..d69f0fb6 100644 --- a/ContextMenuManager/Controls/Interfaces/IChkVisibleItem.cs +++ b/ContextMenuManager/Controls/Interfaces/IChkVisibleItem.cs @@ -18,12 +18,12 @@ public VisibleCheckBox(IChkVisibleItem item) CheckChanged += () => item.ItemVisible = Checked; listItem.ParentChanged += (sender, e) => { - if (listItem.IsDisposed) return; - if (listItem.Parent == null) return; + if(listItem.IsDisposed) return; + if(listItem.Parent == null) return; Checked = item.ItemVisible; - if (listItem is FoldSubItem subItem && subItem.FoldGroupItem != null) return; - if (listItem.FindForm() is ShellStoreDialog.ShellStoreForm) return; - if (AppConfig.HideDisabledItems) listItem.Visible = Checked; + if(listItem is FoldSubItem subItem && subItem.FoldGroupItem != null) return; + if(listItem.FindForm() is ShellStoreDialog.ShellStoreForm) return; + if(AppConfig.HideDisabledItems) listItem.Visible = Checked; }; } } diff --git a/ContextMenuManager/Controls/Interfaces/ITsiAdministratorItem.cs b/ContextMenuManager/Controls/Interfaces/ITsiAdministratorItem.cs index 6b2d6a36..a8254afd 100644 --- a/ContextMenuManager/Controls/Interfaces/ITsiAdministratorItem.cs +++ b/ContextMenuManager/Controls/Interfaces/ITsiAdministratorItem.cs @@ -18,14 +18,14 @@ public RunAsAdministratorItem(ITsiAdministratorItem item) : base(AppString.Menu. { item.ContextMenuStrip.Opening += (sender, e) => { - if (item.ShellLink == null) + if(item.ShellLink == null) { Enabled = false; return; } string filePath = item.ShellLink.TargetPath; string extension = Path.GetExtension(filePath)?.ToLower(); - switch (extension) + switch(extension) { case ".exe": case ".bat": @@ -42,7 +42,7 @@ public RunAsAdministratorItem(ITsiAdministratorItem item) : base(AppString.Menu. { item.ShellLink.RunAsAdministrator = !Checked; item.ShellLink.Save(); - if (item is WinXItem) ExplorerRestarter.Show(); + if(item is WinXItem) ExplorerRestarter.Show(); }; } } diff --git a/ContextMenuManager/Controls/Interfaces/ITsiCommandItem.cs b/ContextMenuManager/Controls/Interfaces/ITsiCommandItem.cs index 1ffc9c43..57043cae 100644 --- a/ContextMenuManager/Controls/Interfaces/ITsiCommandItem.cs +++ b/ContextMenuManager/Controls/Interfaces/ITsiCommandItem.cs @@ -21,19 +21,19 @@ public ChangeCommandMenuItem(ITsiCommandItem item) : base(AppString.Menu.ChangeC Click += (sender, e) => { string command = ChangeCommand(item.ItemCommand); - if (command != null) item.ItemCommand = command; + if(command != null) item.ItemCommand = command; }; } private string ChangeCommand(string command) { - using (InputDialog dlg = new InputDialog()) + using(InputDialog dlg = new InputDialog()) { dlg.Text = command; dlg.Title = AppString.Menu.ChangeCommand; dlg.Size = new Size(530, 260).DpiZoom(); - if (dlg.ShowDialog() != DialogResult.OK) return null; - if (!CommandCanBeEmpty && string.IsNullOrEmpty(dlg.Text)) + if(dlg.ShowDialog() != DialogResult.OK) return null; + if(!CommandCanBeEmpty && string.IsNullOrEmpty(dlg.Text)) { AppMessageBox.Show(AppString.Message.CommandCannotBeEmpty); return ChangeCommand(command); diff --git a/ContextMenuManager/Controls/Interfaces/ITsiDeleteItem.cs b/ContextMenuManager/Controls/Interfaces/ITsiDeleteItem.cs index 910c0954..49995db0 100644 --- a/ContextMenuManager/Controls/Interfaces/ITsiDeleteItem.cs +++ b/ContextMenuManager/Controls/Interfaces/ITsiDeleteItem.cs @@ -37,7 +37,7 @@ public DeleteMeMenuItem(ITsiDeleteItem item) : base(item is RestoreItem ? AppStr Directory.CreateDirectory(Path.GetDirectoryName(filePath)); ExternalProgram.ExportRegistry(regItem.RegPath, filePath); } - else if (AppMessageBox.Show(item is RestoreItem ? AppString.Message.ConfirmDeleteBackupPermanently : AppString.Message.ConfirmDeletePermanently, + else if (AppMessageBox.Show(item is RestoreItem ? AppString.Message.ConfirmDeleteBackupPermanently : AppString.Message.ConfirmDeletePermanently, MessageBoxButtons.YesNo) != DialogResult.Yes) { return; diff --git a/ContextMenuManager/Controls/Interfaces/ITsiGuidItem.cs b/ContextMenuManager/Controls/Interfaces/ITsiGuidItem.cs index f677a944..2618e03d 100644 --- a/ContextMenuManager/Controls/Interfaces/ITsiGuidItem.cs +++ b/ContextMenuManager/Controls/Interfaces/ITsiGuidItem.cs @@ -46,17 +46,17 @@ private void CopyGuid() private void BlockGuid() { - foreach (string path in GuidBlockedList.BlockedPaths) + foreach(string path in GuidBlockedList.BlockedPaths) { - if (TsiBlockGuid.Checked) + if(TsiBlockGuid.Checked) { RegistryEx.DeleteValue(path, Item.Guid.ToString("B")); } else { - if (Item.Guid.Equals(ShellExItem.LnkOpenGuid) && AppConfig.ProtectOpenItem) + if(Item.Guid.Equals(ShellExItem.LnkOpenGuid) && AppConfig.ProtectOpenItem) { - if (AppMessageBox.Show(AppString.Message.PromptIsOpenItem, + if(AppMessageBox.Show(AppString.Message.PromptIsOpenItem, MessageBoxButtons.YesNo) != DialogResult.Yes) return; } Microsoft.Win32.Registry.SetValue(path, Item.Guid.ToString("B"), string.Empty); @@ -67,7 +67,7 @@ private void BlockGuid() private void AddGuidDic() { - using (AddGuidDicDialog dlg = new AddGuidDicDialog()) + using(AddGuidDicDialog dlg = new AddGuidDicDialog()) { dlg.ItemText = GuidInfo.GetText(Item.Guid); dlg.ItemIcon = GuidInfo.GetImage(Item.Guid); @@ -81,9 +81,9 @@ private void AddGuidDic() }; string section = Item.Guid.ToString(); MyListItem listItem = (MyListItem)Item; - if (dlg.ShowDialog() != DialogResult.OK) + if(dlg.ShowDialog() != DialogResult.OK) { - if (dlg.IsDelete) + if(dlg.IsDelete) { writer.DeleteSection(section); GuidInfo.RemoveDic(Item.Guid); @@ -92,13 +92,13 @@ private void AddGuidDic() } return; } - if (dlg.ItemText.IsNullOrWhiteSpace()) + if(dlg.ItemText.IsNullOrWhiteSpace()) { AppMessageBox.Show(AppString.Message.TextCannotBeEmpty); return; } dlg.ItemText = ResourceString.GetDirectString(dlg.ItemText); - if (dlg.ItemText.IsNullOrWhiteSpace()) + if(dlg.ItemText.IsNullOrWhiteSpace()) { AppMessageBox.Show(AppString.Message.StringParsingFailed); return; @@ -124,12 +124,12 @@ private void RefreshMenuItem() { TsiClsidLocation.Visible = GuidInfo.GetClsidPath(Item.Guid) != null; TsiBlockGuid.Visible = TsiBlockGuid.Checked = false; - if (Item is ShellExItem) + if(Item is ShellExItem) { TsiBlockGuid.Visible = true; - foreach (string path in GuidBlockedList.BlockedPaths) + foreach(string path in GuidBlockedList.BlockedPaths) { - if (Microsoft.Win32.Registry.GetValue(path, Item.Guid.ToString("B"), null) != null) + if(Microsoft.Win32.Registry.GetValue(path, Item.Guid.ToString("B"), null) != null) { TsiBlockGuid.Checked = true; break; } @@ -148,7 +148,7 @@ public string ItemIconLocation { get { - if (ItemIconPath == null) return null; + if(ItemIconPath == null) return null; return $"{ItemIconPath},{ItemIconIndex}"; } } @@ -157,7 +157,7 @@ public override void Reset() { } protected override bool RunDialog(IntPtr hwndOwner) { - using (AddGuidDicForm frm = new AddGuidDicForm()) + using(AddGuidDicForm frm = new AddGuidDicForm()) { frm.ItemText = ItemText; frm.ItemIcon = ItemIcon; @@ -165,7 +165,7 @@ protected override bool RunDialog(IntPtr hwndOwner) frm.ItemIconIndex = ItemIconIndex; frm.TopMost = true; bool flag = frm.ShowDialog() == DialogResult.OK; - if (flag) + if(flag) { ItemText = frm.ItemText; ItemIcon = frm.ItemIcon; @@ -269,15 +269,15 @@ private void InitializeComponents() private void SelectIcon() { - using (IconDialog dlg = new IconDialog()) + using(IconDialog dlg = new IconDialog()) { dlg.IconPath = ItemIconPath; dlg.IconIndex = ItemIconIndex; - if (dlg.ShowDialog() != DialogResult.OK) return; - using (Icon icon = ResourceIcon.GetIcon(dlg.IconPath, dlg.IconIndex)) + if(dlg.ShowDialog() != DialogResult.OK) return; + using(Icon icon = ResourceIcon.GetIcon(dlg.IconPath, dlg.IconIndex)) { Image image = icon?.ToBitmap(); - if (image == null) return; + if(image == null) return; picIcon.Image = image; ItemIconPath = dlg.IconPath; ItemIconIndex = dlg.IconIndex; @@ -297,13 +297,13 @@ public DetailedEditButton(ITsiGuidItem item) : base(AppImage.SubItems) ToolTipBox.SetToolTip(this, AppString.SideBar.DetailedEdit); listItem.ParentChanged += (sender, e) => { - if (listItem.IsDisposed) return; - if (listItem.Parent == null) return; + if(listItem.IsDisposed) return; + if(listItem.Parent == null) return; Visible = XmlDicHelper.DetailedEditGuidDic.ContainsKey(item.Guid); }; MouseDown += (sender, e) => { - using (DetailedEditDialog dlg = new DetailedEditDialog()) + using(DetailedEditDialog dlg = new DetailedEditDialog()) { dlg.GroupGuid = item.Guid; dlg.ShowDialog(); diff --git a/ContextMenuManager/Controls/Interfaces/ITsiIconItem.cs b/ContextMenuManager/Controls/Interfaces/ITsiIconItem.cs index 2b310c1a..9044c0c1 100644 --- a/ContextMenuManager/Controls/Interfaces/ITsiIconItem.cs +++ b/ContextMenuManager/Controls/Interfaces/ITsiIconItem.cs @@ -22,15 +22,15 @@ public ChangeIconMenuItem(ITsiIconItem item) : base(AppString.Menu.ChangeIcon) { Click += (sender, e) => { - using (IconDialog dlg = new IconDialog()) + using(IconDialog dlg = new IconDialog()) { dlg.IconPath = item.IconPath; dlg.IconIndex = item.IconIndex; - if (dlg.ShowDialog() != DialogResult.OK) return; - using (Icon icon = ResourceIcon.GetIcon(dlg.IconPath, dlg.IconIndex)) + if(dlg.ShowDialog() != DialogResult.OK) return; + using(Icon icon = ResourceIcon.GetIcon(dlg.IconPath, dlg.IconIndex)) { Image image = icon?.ToBitmap(); - if (image == null) return; + if(image == null) return; item.Image = image; item.IconPath = dlg.IconPath; item.IconIndex = dlg.IconIndex; diff --git a/ContextMenuManager/Controls/Interfaces/ITsiRegExportItem.cs b/ContextMenuManager/Controls/Interfaces/ITsiRegExportItem.cs index 0d898a9c..6fed67f8 100644 --- a/ContextMenuManager/Controls/Interfaces/ITsiRegExportItem.cs +++ b/ContextMenuManager/Controls/Interfaces/ITsiRegExportItem.cs @@ -20,12 +20,12 @@ public RegExportMenuItem(ITsiRegExportItem item) : base(AppString.Menu.ExportReg { item.ContextMenuStrip.Opening += (sender, e) => { - using (var key = RegistryEx.GetRegistryKey(item.RegPath)) + using(var key = RegistryEx.GetRegistryKey(item.RegPath)) Visible = key != null; }; Click += (sender, e) => { - using (SaveFileDialog dlg = new SaveFileDialog()) + using(SaveFileDialog dlg = new SaveFileDialog()) { string date = DateTime.Today.ToString("yyyy-MM-dd"); string time = DateTime.Now.ToString("HH-mm-ss"); @@ -36,11 +36,11 @@ public RegExportMenuItem(ITsiRegExportItem item) : base(AppString.Menu.ExportReg dlg.FileName = fileName; dlg.InitialDirectory = dirPath; dlg.Filter = $"{AppString.Dialog.RegistryFile}|*.reg"; - if (dlg.ShowDialog() == DialogResult.OK) + if(dlg.ShowDialog() == DialogResult.OK) { ExternalProgram.ExportRegistry(item.RegPath, dlg.FileName); } - if (Directory.GetFileSystemEntries(dirPath).Length == 0) + if(Directory.GetFileSystemEntries(dirPath).Length == 0) { Directory.Delete(dirPath); } diff --git a/ContextMenuManager/Controls/Interfaces/ITsiRegPathItem.cs b/ContextMenuManager/Controls/Interfaces/ITsiRegPathItem.cs index 0cec4670..98e1c938 100644 --- a/ContextMenuManager/Controls/Interfaces/ITsiRegPathItem.cs +++ b/ContextMenuManager/Controls/Interfaces/ITsiRegPathItem.cs @@ -19,7 +19,7 @@ public RegLocationMenuItem(ITsiRegPathItem item) : base(AppString.Menu.RegistryL Click += (sender, e) => ExternalProgram.JumpRegEdit(item.RegPath, item.ValueName, AppConfig.OpenMoreRegedit); item.ContextMenuStrip.Opening += (sender, e) => { - using (var key = RegistryEx.GetRegistryKey(item.RegPath)) + using(var key = RegistryEx.GetRegistryKey(item.RegPath)) Visible = key != null; }; } diff --git a/ContextMenuManager/Controls/Interfaces/ITsiRestoreItem.cs b/ContextMenuManager/Controls/Interfaces/ITsiRestoreItem.cs index 9faf53a1..ce35199a 100644 --- a/ContextMenuManager/Controls/Interfaces/ITsiRestoreItem.cs +++ b/ContextMenuManager/Controls/Interfaces/ITsiRestoreItem.cs @@ -1,4 +1,5 @@ using ContextMenuManager.Methods; +using System.Windows.Forms; namespace ContextMenuManager.Controls.Interfaces { diff --git a/ContextMenuManager/Controls/Interfaces/ITsiShortcutCommandItem.cs b/ContextMenuManager/Controls/Interfaces/ITsiShortcutCommandItem.cs index c95fc529..035e71fc 100644 --- a/ContextMenuManager/Controls/Interfaces/ITsiShortcutCommandItem.cs +++ b/ContextMenuManager/Controls/Interfaces/ITsiShortcutCommandItem.cs @@ -26,11 +26,11 @@ public ShortcutCommandMenuItem(ITsiShortcutCommandItem item) : base(AppString.Me public bool ChangeCommand(ShellLink shellLink) { - using (CommandDialog dlg = new CommandDialog()) + using(CommandDialog dlg = new CommandDialog()) { dlg.Command = shellLink.TargetPath; dlg.Arguments = shellLink.Arguments; - if (dlg.ShowDialog() != DialogResult.OK) return false; + if(dlg.ShowDialog() != DialogResult.OK) return false; shellLink.TargetPath = dlg.Command; shellLink.Arguments = dlg.Arguments; shellLink.Save(); @@ -47,13 +47,13 @@ public override void Reset() { } protected override bool RunDialog(IntPtr hwndOwner) { - using (CommandForm frm = new CommandForm()) + using(CommandForm frm = new CommandForm()) { frm.Command = Command; frm.Arguments = Arguments; frm.TopMost = true; bool flag = frm.ShowDialog() == DialogResult.OK; - if (flag) + if(flag) { Command = frm.Command; Arguments = frm.Arguments; diff --git a/ContextMenuManager/Controls/Interfaces/ITsiTextItem.cs b/ContextMenuManager/Controls/Interfaces/ITsiTextItem.cs index a11a2e8a..65ba09f5 100644 --- a/ContextMenuManager/Controls/Interfaces/ITsiTextItem.cs +++ b/ContextMenuManager/Controls/Interfaces/ITsiTextItem.cs @@ -19,21 +19,21 @@ public ChangeTextMenuItem(ITsiTextItem item) : base(AppString.Menu.ChangeText) Click += (sender, e) => { string name = ChangeText(item.Text); - if (name != null) item.ItemText = name; + if(name != null) item.ItemText = name; }; } private string ChangeText(string text) { - using (InputDialog dlg = new InputDialog { Text = text, Title = AppString.Menu.ChangeText }) + using(InputDialog dlg = new InputDialog { Text = text, Title = AppString.Menu.ChangeText }) { - if (dlg.ShowDialog() != DialogResult.OK) return null; - if (dlg.Text.Length == 0) + if(dlg.ShowDialog() != DialogResult.OK) return null; + if(dlg.Text.Length == 0) { AppMessageBox.Show(AppString.Message.TextCannotBeEmpty); return ChangeText(text); } - else if (ResourceString.GetDirectString(dlg.Text).Length == 0) + else if(ResourceString.GetDirectString(dlg.Text).Length == 0) { AppMessageBox.Show(AppString.Message.StringParsingFailed); return ChangeText(text); diff --git a/ContextMenuManager/Controls/Interfaces/ITsiWebSearchItem.cs b/ContextMenuManager/Controls/Interfaces/ITsiWebSearchItem.cs index c7ac44e2..0f7f31fa 100644 --- a/ContextMenuManager/Controls/Interfaces/ITsiWebSearchItem.cs +++ b/ContextMenuManager/Controls/Interfaces/ITsiWebSearchItem.cs @@ -1,5 +1,6 @@ using BluePointLilac.Methods; using ContextMenuManager.Methods; +using System.Windows.Forms; namespace ContextMenuManager.Controls.Interfaces { diff --git a/ContextMenuManager/Controls/LanguagesBox.cs b/ContextMenuManager/Controls/LanguagesBox.cs index 471908e8..34b91429 100644 --- a/ContextMenuManager/Controls/LanguagesBox.cs +++ b/ContextMenuManager/Controls/LanguagesBox.cs @@ -25,7 +25,7 @@ public LanguagesBox() VisibleChanged += (sender, e) => this.SetEnabled(Visible); cmbLanguages.SelectionChangeCommitted += (sender, e) => ChangeLanguage(); btnOpenDir.MouseDown += (sender, e) => ExternalProgram.OpenDirectory(AppConfig.LangsDir); - lblThank.MouseEnter += (sender, e) => lblThank.ForeColor = MyMainForm.MainColor; + lblThank.MouseEnter += (sender, e) => lblThank.ForeColor = DarkModeHelper.MainColor; // 修改这里 lblThank.MouseLeave += (sender, e) => lblThank.ForeColor = Color.DimGray;//Fixed btnDownLoad.MouseDown += (sender, e) => { @@ -35,7 +35,7 @@ public LanguagesBox() }; btnTranslate.MouseDown += (sender, e) => { - using (TranslateDialog dlg = new TranslateDialog()) + using(TranslateDialog dlg = new TranslateDialog()) { dlg.ShowDialog(); } @@ -66,7 +66,7 @@ public LanguagesBox() readonly Label lblHeader = new Label { Text = AppString.Other.Translators + "\r\n" + new string('-', 96), - ForeColor = MyMainForm.MainColor, + ForeColor = DarkModeHelper.MainColor, // 修改这里 Dock = DockStyle.Top, AutoSize = true }; @@ -97,13 +97,13 @@ public void LoadLanguages() languages.Add("default"); pnlTranslators.SuspendLayout(); pnlTranslators.Controls.Remove(lblHeader); - foreach (Control ctr in pnlTranslators.Controls) ctr.Dispose(); + foreach(Control ctr in pnlTranslators.Controls) ctr.Dispose(); pnlTranslators.Controls.Clear(); pnlTranslators.Controls.Add(lblHeader); - if (Directory.Exists(AppConfig.LangsDir)) + if(Directory.Exists(AppConfig.LangsDir)) { Dictionary dic = new Dictionary(); - foreach (string fileName in Directory.GetFiles(AppConfig.LangsDir, "*.ini")) + foreach(string fileName in Directory.GetFiles(AppConfig.LangsDir, "*.ini")) { IniWriter writer = new IniWriter(fileName); string language = writer.GetValue("General", "Language"); @@ -111,19 +111,19 @@ public void LoadLanguages() string translatorUrl = writer.GetValue("General", "TranslatorUrl"); string langName = Path.GetFileNameWithoutExtension(fileName); - if (string.IsNullOrEmpty(language)) language = langName; + if(string.IsNullOrEmpty(language)) language = langName; string[] translators = translator.Split(new[] { "\\r\\n", "\\n" }, StringSplitOptions.RemoveEmptyEntries); string[] urls = translatorUrl.Split(new[] { "\\r\\n", "\\n" }, StringSplitOptions.RemoveEmptyEntries); Label lblLanguage = new Label { - ForeColor = MyMainForm.FormFore, + ForeColor = DarkModeHelper.FormFore, // 修改这里 Text = language, AutoSize = true, Font = Font }; Label[] ctrTranslators = new Label[translators.Length]; - for (int i = 0; i < translators.Length; i++) + for(int i = 0; i < translators.Length; i++) { ctrTranslators[i] = new Label { @@ -132,13 +132,13 @@ public void LoadLanguages() Text = translators[i], ForeColor = Color.DimGray,//Fixed }; - if (urls.Length > i) + if(urls.Length > i) { string url = urls[i].Trim(); - if (url != "null") + if(url != "null") { toolTip.SetToolTip(ctrTranslators[i], url); - ctrTranslators[i].ForeColor = MyMainForm.FormFore; + ctrTranslators[i].ForeColor = DarkModeHelper.FormFore; // 修改这里 ctrTranslators[i].Font = new Font(ctrTranslators[i].Font, FontStyle.Underline); ctrTranslators[i].Click += (sender, e) => ExternalProgram.OpenWebUrl(url); } @@ -152,11 +152,11 @@ public void LoadLanguages() dic.Keys.ToList().ForEach(lbl => left = Math.Max(left, lbl.Width)); left += 250.DpiZoom(); int top = lblHeader.Bottom + 10.DpiZoom(); - foreach (var item in dic) + foreach(var item in dic) { item.Key.Top = top; pnlTranslators.Controls.Add(item.Key); - foreach (var ctr in item.Value) + foreach(var ctr in item.Value) { ctr.Location = new Point(left, top); pnlTranslators.Controls.Add(ctr); @@ -171,22 +171,22 @@ public void LoadLanguages() private void ChangeLanguage() { int index = GetSelectIndex(); - if (cmbLanguages.SelectedIndex == index) return; + if(cmbLanguages.SelectedIndex == index) return; string language = languages[cmbLanguages.SelectedIndex]; string msg = ""; - if (cmbLanguages.SelectedIndex != 0) + if(cmbLanguages.SelectedIndex != 0) { string langPath = $@"{AppConfig.LangsDir}\{language}.ini"; msg = new IniWriter(langPath).GetValue("Message", "RestartApp"); } - if (msg == "") msg = AppString.Message.RestartApp; - if (AppMessageBox.Show(msg, MessageBoxButtons.OKCancel) != DialogResult.OK) + if(msg == "") msg = AppString.Message.RestartApp; + if(AppMessageBox.Show(msg, MessageBoxButtons.OKCancel) != DialogResult.OK) { cmbLanguages.SelectedIndex = index; } else { - if (language == CultureInfo.CurrentUICulture.Name) language = ""; + if(language == CultureInfo.CurrentUICulture.Name) language = ""; AppConfig.Language = language; SingleInstance.Restart(); } @@ -195,50 +195,50 @@ private void ChangeLanguage() private int GetSelectIndex() { int index = languages.FindIndex(language => language.Equals(AppConfig.Language, StringComparison.OrdinalIgnoreCase)); - if (index == -1) index = 0; + if(index == -1) index = 0; return index; } public void ShowLanguageDialog() { - using (UAWebClient client = new UAWebClient()) + using(UAWebClient client = new UAWebClient()) { string apiUrl = AppConfig.RequestUseGithub ? AppConfig.GithubLangsApi : AppConfig.GiteeLangsApi; XmlDocument doc = client.GetWebJsonToXml(apiUrl); - if (doc == null) + if(doc == null) { AppMessageBox.Show(AppString.Message.WebDataReadFailed); return; } XmlNodeList list = doc.FirstChild.ChildNodes; string[] langs = new string[list.Count]; - for (int i = 0; i < list.Count; i++) + for(int i = 0; i < list.Count; i++) { XmlNode nameXN = list.Item(i).SelectSingleNode("name"); langs[i] = Path.GetFileNameWithoutExtension(nameXN.InnerText); } - if (langs.Length == 0) + if(langs.Length == 0) { AppMessageBox.Show(AppString.Message.WebDataReadFailed); return; } - using (SelectDialog dlg = new SelectDialog()) + using(SelectDialog dlg = new SelectDialog()) { dlg.Items = langs; dlg.Title = AppString.Dialog.DownloadLanguages; string lang = CultureInfo.CurrentUICulture.Name; - if (dlg.Items.Contains(lang)) dlg.Selected = lang; + if(dlg.Items.Contains(lang)) dlg.Selected = lang; else dlg.SelectedIndex = 0; - if (dlg.ShowDialog() == DialogResult.OK) + if(dlg.ShowDialog() == DialogResult.OK) { string fileName = $"{dlg.Selected}.ini"; string filePath = $@"{AppConfig.LangsDir}\{fileName}"; string dirUrl = AppConfig.RequestUseGithub ? AppConfig.GithubLangsRawDir : AppConfig.GiteeLangsRawDir; string fileUrl = $"{dirUrl}/{fileName}"; bool flag = client.WebStringToFile(filePath, fileUrl); - if (!flag) + if(!flag) { - if (AppMessageBox.Show(AppString.Message.WebDataReadFailed + "\r\n ● " + fileName + "\r\n" + if(AppMessageBox.Show(AppString.Message.WebDataReadFailed + "\r\n ● " + fileName + "\r\n" + AppString.Message.OpenWebUrl, MessageBoxButtons.YesNo) == DialogResult.Yes) { ExternalProgram.OpenWebUrl(fileUrl); @@ -248,7 +248,7 @@ public void ShowLanguageDialog() { LoadLanguages(); string language = new IniWriter(filePath).GetValue("General", "Language"); - if (language == "") language = dlg.Selected; + if(language == "") language = dlg.Selected; cmbLanguages.Text = language; ChangeLanguage(); } @@ -263,7 +263,7 @@ public override void Reset() { } protected override bool RunDialog(IntPtr hwndOwner) { - using (TranslateForm frm = new TranslateForm()) + using(TranslateForm frm = new TranslateForm()) { frm.TopMost = true; return frm.ShowDialog() == DialogResult.OK; @@ -353,10 +353,10 @@ public TranslateForm() static TranslateForm() { - foreach (string section in AppString.DefLangReader.Sections) + foreach(string section in AppString.DefLangReader.Sections) { var dic = new Dictionary(); - foreach (string key in AppString.DefLangReader.GetSectionKeys(section)) + foreach(string key in AppString.DefLangReader.GetSectionKeys(section)) { dic.Add(key, string.Empty); } @@ -436,7 +436,7 @@ private void InitializeComponents() }; cmbSections.SelectedIndex = 0; - txtOld.TextChanged += (sender, e) => { if (txtNew.Text == string.Empty) txtNew.Text = txtOld.Text; }; + txtOld.TextChanged += (sender, e) => { if(txtNew.Text == string.Empty) txtNew.Text = txtOld.Text; }; txtNew.TextChanged += (sender, e) => EditingDic[Section][Key] = txtNew.Text.Replace("\n", "\\n").Replace("\r", "\\r"); btnBrowse.Click += (sender, e) => SelectFile(); btnSave.Click += (sender, e) => Save(); @@ -444,11 +444,11 @@ private void InitializeComponents() private void SelectFile() { - using (OpenFileDialog dlg = new OpenFileDialog()) + using(OpenFileDialog dlg = new OpenFileDialog()) { dlg.InitialDirectory = AppConfig.LangsDir; dlg.Filter = $"{AppString.SideBar.AppLanguage}|*.ini"; - if (dlg.ShowDialog() != DialogResult.OK) return; + if(dlg.ShowDialog() != DialogResult.OK) return; ReferentialWirter.FilePath = dlg.FileName; txtOld.Text = ReferentialWirter.GetValue(Section, Key).Replace("\\r", "\r").Replace("\\n", "\n"); } @@ -456,21 +456,21 @@ private void SelectFile() private void Save() { - using (SaveFileDialog dlg = new SaveFileDialog()) + using(SaveFileDialog dlg = new SaveFileDialog()) { string language = EditingDic["General"]["Language"]; int index = language.IndexOf(' '); - if (index > 0) language = language.Substring(0, index); + if(index > 0) language = language.Substring(0, index); dlg.FileName = $"{language}.ini"; dlg.InitialDirectory = AppConfig.LangsDir; dlg.Filter = $"{AppString.SideBar.AppLanguage}|*.ini"; - if (dlg.ShowDialog() != DialogResult.OK) return; + if(dlg.ShowDialog() != DialogResult.OK) return; string contents = string.Empty; - foreach (string section in EditingDic.Keys) + foreach(string section in EditingDic.Keys) { contents += $"[{section}]" + "\r\n"; - foreach (string key in EditingDic[section].Keys) + foreach(string key in EditingDic[section].Keys) { string value = EditingDic[section][key]; contents += $"{key} = {value}" + "\r\n"; @@ -483,4 +483,4 @@ private void Save() } } } -} +} \ No newline at end of file diff --git a/ContextMenuManager/Controls/NewIEDialog.cs b/ContextMenuManager/Controls/NewIEDialog.cs index fe6800cb..bee4375c 100644 --- a/ContextMenuManager/Controls/NewIEDialog.cs +++ b/ContextMenuManager/Controls/NewIEDialog.cs @@ -13,11 +13,11 @@ public override void Reset() { } protected override bool RunDialog(IntPtr hwndOwner) { - using (NewIEForm frm = new NewIEForm()) + using(NewIEForm frm = new NewIEForm()) { frm.TopMost = true; bool flag = frm.ShowDialog() == DialogResult.OK; - if (flag) RegPath = frm.RegPath; + if(flag) RegPath = frm.RegPath; return flag; } } @@ -31,12 +31,12 @@ protected override void InitializeComponents() base.InitializeComponents(); btnOK.Click += (sender, e) => { - if (ItemText.IsNullOrWhiteSpace()) + if(ItemText.IsNullOrWhiteSpace()) { AppMessageBox.Show(AppString.Message.TextCannotBeEmpty); return; } - if (ItemCommand.IsNullOrWhiteSpace()) + if(ItemCommand.IsNullOrWhiteSpace()) { AppMessageBox.Show(AppString.Message.CommandCannotBeEmpty); return; @@ -47,9 +47,9 @@ protected override void InitializeComponents() btnBrowse.Click += (sender, e) => { - using (OpenFileDialog dlg = new OpenFileDialog()) + using(OpenFileDialog dlg = new OpenFileDialog()) { - if (dlg.ShowDialog() != DialogResult.OK) return; + if(dlg.ShowDialog() != DialogResult.OK) return; ItemFilePath = dlg.FileName; ItemText = Path.GetFileNameWithoutExtension(dlg.FileName); } diff --git a/ContextMenuManager/Controls/NewItemForm.cs b/ContextMenuManager/Controls/NewItemForm.cs index d318a3fd..1f7e4d40 100644 --- a/ContextMenuManager/Controls/NewItemForm.cs +++ b/ContextMenuManager/Controls/NewItemForm.cs @@ -32,10 +32,10 @@ public string ItemCommand { string filePath = ItemFilePath; string arguments = Arguments; - if (arguments.IsNullOrWhiteSpace()) return filePath; - if (filePath.IsNullOrWhiteSpace()) return arguments; - if (filePath.Contains(" ")) filePath = $"\"{filePath}\""; - if (!arguments.Contains("\"")) arguments = $"\"{arguments}\""; + if(arguments.IsNullOrWhiteSpace()) return filePath; + if(filePath.IsNullOrWhiteSpace()) return arguments; + if(filePath.Contains(" ")) filePath = $"\"{filePath}\""; + if(!arguments.Contains("\"")) arguments = $"\"{arguments}\""; return $"{filePath} {arguments}"; } } diff --git a/ContextMenuManager/Controls/NewLnkFileDialog.cs b/ContextMenuManager/Controls/NewLnkFileDialog.cs index a71323a1..d56cb37d 100644 --- a/ContextMenuManager/Controls/NewLnkFileDialog.cs +++ b/ContextMenuManager/Controls/NewLnkFileDialog.cs @@ -16,12 +16,12 @@ public override void Reset() { } protected override bool RunDialog(IntPtr hwndOwner) { - using (NewLnkForm frm = new NewLnkForm()) + using(NewLnkForm frm = new NewLnkForm()) { frm.FileFilter = FileFilter; frm.TopMost = true; bool flag = frm.ShowDialog() == DialogResult.OK; - if (flag) + if(flag) { ItemText = frm.ItemText; ItemFilePath = frm.ItemFilePath; @@ -57,25 +57,25 @@ protected override void InitializeComponents() btnBrowse.Click += (sender, e) => { - if (rdoFile.Checked) BrowseFile(); + if(rdoFile.Checked) BrowseFile(); else BrowseFolder(); }; btnOK.Click += (sender, e) => { - if (ItemText.IsNullOrWhiteSpace()) + if(ItemText.IsNullOrWhiteSpace()) { AppMessageBox.Show(AppString.Message.TextCannotBeEmpty); } - else if (ItemFilePath.IsNullOrWhiteSpace()) + else if(ItemFilePath.IsNullOrWhiteSpace()) { AppMessageBox.Show(AppString.Message.CommandCannotBeEmpty); } - else if (rdoFile.Checked && !ObjectPath.GetFullFilePath(ItemFilePath, out _)) + else if(rdoFile.Checked && !ObjectPath.GetFullFilePath(ItemFilePath, out _)) { AppMessageBox.Show(AppString.Message.FileNotExists); } - else if (rdoFolder.Checked && !Directory.Exists(ItemFilePath)) + else if(rdoFolder.Checked && !Directory.Exists(ItemFilePath)) { AppMessageBox.Show(AppString.Message.FolderNotExists); } @@ -84,11 +84,11 @@ protected override void InitializeComponents() txtFilePath.TextChanged += (sender, e) => { - if (Path.GetExtension(ItemFilePath).ToLower() == ".lnk") + if(Path.GetExtension(ItemFilePath).ToLower() == ".lnk") { - using (ShellLink shortcut = new ShellLink(ItemFilePath)) + using(ShellLink shortcut = new ShellLink(ItemFilePath)) { - if (File.Exists(shortcut.TargetPath)) + if(File.Exists(shortcut.TargetPath)) { ItemFilePath = shortcut.TargetPath; } @@ -99,20 +99,20 @@ protected override void InitializeComponents() private void BrowseFile() { - using (OpenFileDialog dlg = new OpenFileDialog()) + using(OpenFileDialog dlg = new OpenFileDialog()) { dlg.Filter = FileFilter; //取消获取lnk目标路径,可选中UWP快捷方式 dlg.DereferenceLinks = false; - if (dlg.ShowDialog() == DialogResult.OK) + if(dlg.ShowDialog() == DialogResult.OK) { ItemFilePath = dlg.FileName; string extension = Path.GetExtension(dlg.FileName).ToLower(); - if (extension == ".lnk") + if(extension == ".lnk") { - using (ShellLink shortcut = new ShellLink(dlg.FileName)) + using(ShellLink shortcut = new ShellLink(dlg.FileName)) { - if (File.Exists(shortcut.TargetPath)) + if(File.Exists(shortcut.TargetPath)) { ItemFilePath = shortcut.TargetPath; Arguments = shortcut.Arguments; @@ -126,11 +126,11 @@ private void BrowseFile() private void BrowseFolder() { - using (FolderBrowserDialog dlg = new FolderBrowserDialog()) + using(FolderBrowserDialog dlg = new FolderBrowserDialog()) { - if (Directory.Exists(ItemFilePath)) dlg.SelectedPath = ItemFilePath; + if(Directory.Exists(ItemFilePath)) dlg.SelectedPath = ItemFilePath; else dlg.SelectedPath = Application.StartupPath; - if (dlg.ShowDialog() == DialogResult.OK) + if(dlg.ShowDialog() == DialogResult.OK) { ItemFilePath = dlg.SelectedPath; ItemText = Path.GetFileNameWithoutExtension(dlg.SelectedPath); diff --git a/ContextMenuManager/Controls/NewOpenWithDialog.cs b/ContextMenuManager/Controls/NewOpenWithDialog.cs index 91ecf165..c0ca69d4 100644 --- a/ContextMenuManager/Controls/NewOpenWithDialog.cs +++ b/ContextMenuManager/Controls/NewOpenWithDialog.cs @@ -14,11 +14,11 @@ public override void Reset() { } protected override bool RunDialog(IntPtr hwndOwner) { - using (NewOpenWithForm frm = new NewOpenWithForm()) + using(NewOpenWithForm frm = new NewOpenWithForm()) { frm.TopMost = true; bool flag = frm.ShowDialog() == DialogResult.OK; - if (flag) RegPath = frm.RegPath; + if(flag) RegPath = frm.RegPath; return flag; } } @@ -38,27 +38,27 @@ protected override void InitializeComponents() btnBrowse.Click += (sender, e) => BrowseFile(); btnOK.Click += (sender, e) => { - if (string.IsNullOrEmpty(ItemText)) + if(string.IsNullOrEmpty(ItemText)) { AppMessageBox.Show(AppString.Message.TextCannotBeEmpty); return; } - if (ItemCommand.IsNullOrWhiteSpace()) + if(ItemCommand.IsNullOrWhiteSpace()) { AppMessageBox.Show(AppString.Message.CommandCannotBeEmpty); return; } FilePath = ObjectPath.ExtractFilePath(base.ItemFilePath); - using (var key = RegistryEx.GetRegistryKey(CommandPath)) + using(var key = RegistryEx.GetRegistryKey(CommandPath)) { string path = ObjectPath.ExtractFilePath(key?.GetValue("")?.ToString()); string name = Path.GetFileName(path); - if (FilePath != null && FilePath.Equals(path, StringComparison.OrdinalIgnoreCase)) + if(FilePath != null && FilePath.Equals(path, StringComparison.OrdinalIgnoreCase)) { AppMessageBox.Show(AppString.Message.HasBeenAdded); return; } - if (FileName == null || FileName.Equals(name, StringComparison.OrdinalIgnoreCase)) + if(FileName == null || FileName.Equals(name, StringComparison.OrdinalIgnoreCase)) { AppMessageBox.Show(AppString.Message.UnsupportedFilename); return; @@ -71,10 +71,10 @@ protected override void InitializeComponents() private void BrowseFile() { - using (OpenFileDialog dlg = new OpenFileDialog()) + using(OpenFileDialog dlg = new OpenFileDialog()) { dlg.Filter = $"{AppString.Dialog.Program}|*.exe"; - if (dlg.ShowDialog() == DialogResult.OK) + if(dlg.ShowDialog() == DialogResult.OK) { base.ItemFilePath = dlg.FileName; Arguments = "\"%1\""; @@ -85,11 +85,11 @@ private void BrowseFile() private void AddNewItem() { - using (var key = RegistryEx.GetRegistryKey(AppRegPath, true, true)) + using(var key = RegistryEx.GetRegistryKey(AppRegPath, true, true)) { key.SetValue("FriendlyAppName", ItemText); } - using (var cmdKey = RegistryEx.GetRegistryKey(CommandPath, true, true)) + using(var cmdKey = RegistryEx.GetRegistryKey(CommandPath, true, true)) { cmdKey.SetValue("", ItemCommand); RegPath = cmdKey.Name; diff --git a/ContextMenuManager/Controls/NewShellDialog.cs b/ContextMenuManager/Controls/NewShellDialog.cs index 6387b0eb..a7b1987e 100644 --- a/ContextMenuManager/Controls/NewShellDialog.cs +++ b/ContextMenuManager/Controls/NewShellDialog.cs @@ -17,7 +17,7 @@ public override void Reset() { } protected override bool RunDialog(IntPtr hwndOwner) { - using (NewShellForm frm = new NewShellForm + using(NewShellForm frm = new NewShellForm { ScenePath = ScenePath, ShellPath = ShellPath @@ -25,7 +25,7 @@ protected override bool RunDialog(IntPtr hwndOwner) { frm.TopMost = true; bool flag = frm.ShowDialog() == DialogResult.OK; - if (flag) NewItemRegPath = frm.NewItemRegPath; + if(flag) NewItemRegPath = frm.NewItemRegPath; return flag; } } @@ -74,10 +74,10 @@ protected override void InitializeComponents() rdoMulti.CheckedChanged += (sender, e) => { - if (rdoMulti.Checked) + if(rdoMulti.Checked) { chkSE.Checked = false; - if (WinOsVersion.Current == WinOsVersion.Vista) + if(WinOsVersion.Current == WinOsVersion.Vista) { AppMessageBox.Show(AppString.Message.VistaUnsupportedMulti); rdoSingle.Checked = true; @@ -92,7 +92,7 @@ protected override void InitializeComponents() btnOK.Click += (sender, e) => { - if (txtText.Text.IsNullOrWhiteSpace()) + if(txtText.Text.IsNullOrWhiteSpace()) { AppMessageBox.Show(AppString.Message.TextCannotBeEmpty); } @@ -106,18 +106,18 @@ protected override void InitializeComponents() private void BrowseFile() { - using (OpenFileDialog dlg = new OpenFileDialog()) + using(OpenFileDialog dlg = new OpenFileDialog()) { dlg.DereferenceLinks = false; dlg.Filter = $"{AppString.Dialog.Program}|*.exe|{AppString.Dialog.AllFiles}|*"; - if (dlg.ShowDialog() != DialogResult.OK) return; + if(dlg.ShowDialog() != DialogResult.OK) return; string filePath = dlg.FileName; string arguments = ""; ItemText = Path.GetFileNameWithoutExtension(filePath); string extension = Path.GetExtension(filePath).ToLower(); - if (extension == ".lnk") + if(extension == ".lnk") { - using (ShellLink shellLink = new ShellLink(filePath)) + using(ShellLink shellLink = new ShellLink(filePath)) { filePath = shellLink.TargetPath; arguments = shellLink.Arguments; @@ -125,30 +125,30 @@ private void BrowseFile() } } string exePath = FileExtension.GetExtentionInfo(FileExtension.AssocStr.Executable, extension); - if (File.Exists(exePath)) + if(File.Exists(exePath)) { ItemFilePath = exePath; Arguments = filePath; - if (!arguments.IsNullOrWhiteSpace()) Arguments += " " + arguments; + if(!arguments.IsNullOrWhiteSpace()) Arguments += " " + arguments; } else { ItemFilePath = filePath; Arguments = arguments; } - if (Array.FindIndex(DirScenePaths, path + if(Array.FindIndex(DirScenePaths, path => ScenePath.StartsWith(path, StringComparison.OrdinalIgnoreCase)) != -1) { - if (ScenePath != ShellList.MENUPATH_BACKGROUND) + if(ScenePath != ShellList.MENUPATH_BACKGROUND) { - if (!Arguments.IsNullOrWhiteSpace()) Arguments += " "; + if(!Arguments.IsNullOrWhiteSpace()) Arguments += " "; Arguments += "\"%V\"";//自动加目录后缀 } } - else if (Array.FindIndex(FileObjectsScenePaths, path + else if(Array.FindIndex(FileObjectsScenePaths, path => ScenePath.StartsWith(path, StringComparison.OrdinalIgnoreCase)) != -1) { - if (!Arguments.IsNullOrWhiteSpace()) Arguments += " "; + if(!Arguments.IsNullOrWhiteSpace()) Arguments += " "; Arguments += "\"%1\"";//自动加文件对象后缀 } } @@ -156,23 +156,23 @@ private void BrowseFile() private void AddNewItem() { - using (var shellKey = RegistryEx.GetRegistryKey(ShellPath, true, true)) + using(var shellKey = RegistryEx.GetRegistryKey(ShellPath, true, true)) { string keyName = "Item"; NewItemRegPath = ObjectPath.GetNewPathWithIndex($@"{ShellPath}\{keyName}", ObjectPath.PathType.Registry, 0); keyName = RegistryEx.GetKeyName(NewItemRegPath); - using (var key = shellKey.CreateSubKey(keyName, true)) + using(var key = shellKey.CreateSubKey(keyName, true)) { key.SetValue("MUIVerb", ItemText); - if (rdoMulti.Checked) + if(rdoMulti.Checked) key.SetValue("SubCommands", ""); else { - if (!ItemCommand.IsNullOrWhiteSpace()) + if(!ItemCommand.IsNullOrWhiteSpace()) { string command; - if (!chkSE.Checked) command = ItemCommand; + if(!chkSE.Checked) command = ItemCommand; else command = ShellExecuteDialog.GetCommand(ItemFilePath, Arguments, chkSE.Verb, chkSE.WindowStyle); key.CreateSubKey("command", true).SetValue("", command); } diff --git a/ContextMenuManager/Controls/OpenWithItem.cs b/ContextMenuManager/Controls/OpenWithItem.cs index 17ae576e..76e6a99a 100644 --- a/ContextMenuManager/Controls/OpenWithItem.cs +++ b/ContextMenuManager/Controls/OpenWithItem.cs @@ -44,13 +44,13 @@ public string ItemText get { string name = null; - if (NameEquals) + if(NameEquals) { name = Registry.GetValue(AppPath, "FriendlyAppName", null)?.ToString(); name = ResourceString.GetDirectString(name); } - if (string.IsNullOrEmpty(name)) name = FileVersionInfo.GetVersionInfo(ItemFilePath).FileDescription; - if (string.IsNullOrEmpty(name)) name = Path.GetFileName(ItemFilePath); + if(string.IsNullOrEmpty(name)) name = FileVersionInfo.GetVersionInfo(ItemFilePath).FileDescription; + if(string.IsNullOrEmpty(name)) name = Path.GetFileName(ItemFilePath); return name; } set @@ -65,7 +65,7 @@ public string ItemCommand get => Registry.GetValue(RegPath, "", null)?.ToString(); set { - if (ObjectPath.ExtractFilePath(value) != ItemFilePath) + if(ObjectPath.ExtractFilePath(value) != ItemFilePath) { AppMessageBox.Show(AppString.Message.CannotChangePath); } @@ -78,7 +78,7 @@ public bool ItemVisible get => Registry.GetValue(AppPath, "NoOpenWith", null) == null; set { - if (value) RegistryEx.DeleteValue(AppPath, "NoOpenWith"); + if(value) RegistryEx.DeleteValue(AppPath, "NoOpenWith"); else Registry.SetValue(AppPath, "NoOpenWith", ""); } } @@ -125,9 +125,9 @@ private void InitializeComponents() public void DeleteMe() { RegistryEx.DeleteKeyTree(RegPath); - using (RegistryKey key = RegistryEx.GetRegistryKey(ShellPath)) + using(RegistryKey key = RegistryEx.GetRegistryKey(ShellPath)) { - if (key.GetSubKeyNames().Length == 0) RegistryEx.DeleteKeyTree(AppPath); + if(key.GetSubKeyNames().Length == 0) RegistryEx.DeleteKeyTree(AppPath); } } } diff --git a/ContextMenuManager/Controls/OpenWithList.cs b/ContextMenuManager/Controls/OpenWithList.cs index 77bc1edc..5cd092c6 100644 --- a/ContextMenuManager/Controls/OpenWithList.cs +++ b/ContextMenuManager/Controls/OpenWithList.cs @@ -26,34 +26,34 @@ public void LoadItems() private void LoadOpenWithItems() { - using (RegistryKey root = Registry.ClassesRoot) - using (RegistryKey appKey = root.OpenSubKey("Applications")) + using(RegistryKey root = Registry.ClassesRoot) + using(RegistryKey appKey = root.OpenSubKey("Applications")) { - foreach (string appName in appKey.GetSubKeyNames()) + foreach(string appName in appKey.GetSubKeyNames()) { - if (!appName.Contains('.')) continue;//需要为有扩展名的文件名 - using (RegistryKey shellKey = appKey.OpenSubKey($@"{appName}\shell")) + if(!appName.Contains('.')) continue;//需要为有扩展名的文件名 + using(RegistryKey shellKey = appKey.OpenSubKey($@"{appName}\shell")) { - if (shellKey == null) continue; + if(shellKey == null) continue; List names = shellKey.GetSubKeyNames().ToList(); - if (names.Contains("open", StringComparer.OrdinalIgnoreCase)) names.Insert(0, "open"); + if(names.Contains("open", StringComparer.OrdinalIgnoreCase)) names.Insert(0, "open"); string keyName = names.Find(name => { - using (RegistryKey cmdKey = shellKey.OpenSubKey(name)) + using(RegistryKey cmdKey = shellKey.OpenSubKey(name)) return cmdKey.GetValue("NeverDefault") == null; }); - if (keyName == null) continue; + if(keyName == null) continue; - using (RegistryKey commandKey = shellKey.OpenSubKey($@"{keyName}\command")) + using(RegistryKey commandKey = shellKey.OpenSubKey($@"{keyName}\command")) { string command = commandKey?.GetValue("")?.ToString(); - if (ObjectPath.ExtractFilePath(command) != null) + if(ObjectPath.ExtractFilePath(command) != null) { OpenWithItem item = new OpenWithItem(commandKey.Name); AddItem(item); - } + } } } } @@ -66,9 +66,9 @@ private void AddNewItem() InsertItem(newItem, 0); newItem.AddNewItem += () => { - using (NewOpenWithDialog dlg = new NewOpenWithDialog()) + using(NewOpenWithDialog dlg = new NewOpenWithDialog()) { - if (dlg.ShowDialog() == DialogResult.OK) + if(dlg.ShowDialog() == DialogResult.OK) InsertItem(new OpenWithItem(dlg.RegPath), 2); } }; diff --git a/ContextMenuManager/Controls/RComboBox.cs b/ContextMenuManager/Controls/RComboBox.cs deleted file mode 100644 index 5b998632..00000000 --- a/ContextMenuManager/Controls/RComboBox.cs +++ /dev/null @@ -1,266 +0,0 @@ -using System; -using System.ComponentModel; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Runtime.InteropServices; -using System.Windows.Forms; - -namespace BluePointLilac.Controls -{ - /// - /// Edited from: https://github.com/seerge/g-helper - /// - public class RComboBox : ComboBox - { - private Color borderColor = MyMainForm.ButtonMain; - [DefaultValue(typeof(Color), "Gray")] - public Color BorderColor - { - get { return borderColor; } - set - { - if (borderColor != value) - { - borderColor = value; - Invalidate(); - } - } - } - - private Color buttonColor = MyMainForm.ButtonMain; - [DefaultValue(typeof(Color), "255, 255, 255")] - public Color ButtonColor - { - get { return buttonColor; } - set - { - if (buttonColor != value) - { - buttonColor = value; - Invalidate(); - } - } - } - - private Color arrowColor = MyMainForm.FormFore; - [DefaultValue(typeof(Color), "Black")] - public Color ArrowColor - { - get { return arrowColor; } - set - { - if (arrowColor != value) - { - arrowColor = value; - Invalidate(); - } - } - } - - public RComboBox() - { - BackColor = MyMainForm.ButtonMain; - ForeColor = MyMainForm.FormFore; - } - - public static GraphicsPath RoundedRect(Rectangle bounds, int radiusL, int radiusR) - { - int diameterL = radiusL * 2; - int diameterR = radiusR * 2; - - Size sizeL = new Size(diameterL, diameterL); - Size sizeR = new Size(diameterR, diameterR); - - Rectangle arcL = new Rectangle(bounds.Location, sizeL); - Rectangle arcR = new Rectangle(bounds.Location, sizeR); - - GraphicsPath path = new GraphicsPath(); - - // top left arc - path.AddArc(arcL, 180, 90); - - // top right arc - arcR.X = bounds.Right - diameterR; - arcR.Y = bounds.Top; - path.AddArc(arcR, 270, 90); - - // bottom right arc - arcR.Y = bounds.Bottom - diameterR; - arcR.X = bounds.Right - diameterR; - path.AddArc(arcR, 0, 90); - - // bottom left arc - arcL.X = bounds.Left; - arcL.Y = bounds.Bottom - diameterL; - path.AddArc(arcL, 90, 90); - - path.CloseFigure(); - return path; - } - - public static void DrawRoundedRectangle(Graphics graphics, Pen pen, Rectangle bounds, int cornerRadiusL = 5, int cornerRadiusR = 5) - { - if (graphics == null) - throw new ArgumentNullException(nameof(graphics)); - if (pen == null) - throw new ArgumentNullException(nameof(pen)); - - using (GraphicsPath path = RoundedRect(bounds, cornerRadiusL, cornerRadiusR)) - { - graphics.DrawPath(pen, path); - } - } - - public static void FillRoundedRectangle(Graphics graphics, Brush brush, Rectangle bounds, int cornerRadiusL = 5, int cornerRadiusR = 5) - { - if (graphics == null) - throw new ArgumentNullException(nameof(graphics)); - if (brush == null) - throw new ArgumentNullException(nameof(brush)); - - using (GraphicsPath path = RoundedRect(bounds, cornerRadiusL, cornerRadiusR)) - { - graphics.FillPath(brush, path); - } - } - - protected override void WndProc(ref Message m) - { - if (m.Msg == WM_PAINT && DropDownStyle != ComboBoxStyle.Simple) - { - var clientRect = ClientRectangle; - var dropDownButtonWidth = SystemInformation.HorizontalScrollBarArrowWidth; - var outerBorder = new Rectangle(clientRect.Location, - new Size(clientRect.Width - 1, clientRect.Height - 1)); - var innerBorder = new Rectangle(outerBorder.X + 1, outerBorder.Y + 1, - outerBorder.Width - dropDownButtonWidth - 2, outerBorder.Height - 2); - var innerInnerBorder = new Rectangle(innerBorder.X + 1, innerBorder.Y + 1, - innerBorder.Width - 2, innerBorder.Height - 2); - var dropDownRect = new Rectangle(innerBorder.Right + 1, innerBorder.Y, - dropDownButtonWidth, innerBorder.Height + 1); - if (RightToLeft == RightToLeft.Yes) - { - innerBorder.X = clientRect.Width - innerBorder.Right; - innerInnerBorder.X = clientRect.Width - innerInnerBorder.Right; - dropDownRect.X = clientRect.Width - dropDownRect.Right; - dropDownRect.Width += 1; - } - var innerBorderColor = Enabled ? BackColor : SystemColors.Control; - var outerBorderColor = Enabled ? BorderColor : SystemColors.ControlDark; - var buttonColor = Enabled ? ButtonColor : SystemColors.Control; - var middle = new Point(dropDownRect.Left + dropDownRect.Width / 2, - dropDownRect.Top + dropDownRect.Height / 2); - var arrow = new Point[] - { - new Point(middle.X - 3, middle.Y - 2), - new Point(middle.X + 4, middle.Y - 2), - new Point(middle.X, middle.Y + 2) - }; - var ps = new PAINTSTRUCT(); - bool shoulEndPaint = false; - IntPtr dc; - if (m.WParam == IntPtr.Zero) - { - dc = BeginPaint(Handle, ref ps); - m.WParam = dc; - shoulEndPaint = true; - } - else - { - dc = m.WParam; - } - - var rgn = CreateRectRgn(innerInnerBorder.Left, innerInnerBorder.Top, - innerInnerBorder.Right, innerInnerBorder.Bottom); - - SelectClipRgn(dc, rgn); - DefWndProc(ref m); - DeleteObject(rgn); - rgn = CreateRectRgn(clientRect.Left, clientRect.Top, - clientRect.Right, clientRect.Bottom); - SelectClipRgn(dc, rgn); - using (var g = Graphics.FromHdc(dc)) - { - using (var b = new SolidBrush(buttonColor)) - { - //FillRoundedRectangle(g, b, dropDownRect, 1, 3); - g.FillRectangle(b, dropDownRect); - } - using (var b = new SolidBrush(arrowColor)) - { - g.FillPolygon(b, arrow); - } - using (var p = new Pen(innerBorderColor, 2)) - { - DrawRoundedRectangle(g, p, innerBorder, 3, 1); - //DrawRoundedRectangle(g, p, innerInnerBorder, 3, 1); - - //g.DrawRectangle(p, innerBorder); - //g.DrawRectangle(p, innerInnerBorder); - } - using (var p = new Pen(outerBorderColor)) - { - DrawRoundedRectangle(g, p, outerBorder, 4, 4); - //g.DrawRectangle(p, outerBorder); - } - } - if (shoulEndPaint) - EndPaint(Handle, ref ps); - DeleteObject(rgn); - } - else - base.WndProc(ref m); - } - - private const int WM_PAINT = 0xF; - [StructLayout(LayoutKind.Sequential)] - public struct RECT - { - public int L, T, R, B; - } - [StructLayout(LayoutKind.Sequential)] - public struct PAINTSTRUCT - { - public IntPtr hdc; - public bool fErase; - public int rcPaint_left; - public int rcPaint_top; - public int rcPaint_right; - public int rcPaint_bottom; - public bool fRestore; - public bool fIncUpdate; - public int reserved1; - public int reserved2; - public int reserved3; - public int reserved4; - public int reserved5; - public int reserved6; - public int reserved7; - public int reserved8; - } - [DllImport("user32.dll")] - private static extern IntPtr BeginPaint(IntPtr hWnd, - [In, Out] ref PAINTSTRUCT lpPaint); - - [DllImport("user32.dll")] - private static extern bool EndPaint(IntPtr hWnd, ref PAINTSTRUCT lpPaint); - - [DllImport("gdi32.dll")] - public static extern int SelectClipRgn(IntPtr hDC, IntPtr hRgn); - - [DllImport("user32.dll")] - public static extern int GetUpdateRgn(IntPtr hwnd, IntPtr hrgn, bool fErase); - public enum RegionFlags - { - ERROR = 0, - NULLREGION = 1, - SIMPLEREGION = 2, - COMPLEXREGION = 3, - } - [DllImport("gdi32.dll")] - internal static extern bool DeleteObject(IntPtr hObject); - - [DllImport("gdi32.dll")] - private static extern IntPtr CreateRectRgn(int x1, int y1, int x2, int y2); - } -} diff --git a/ContextMenuManager/Controls/RForm.cs b/ContextMenuManager/Controls/RForm.cs index 018e5867..7ee11b29 100644 --- a/ContextMenuManager/Controls/RForm.cs +++ b/ContextMenuManager/Controls/RForm.cs @@ -1,6 +1,7 @@ -using System; +using Microsoft.Win32; using System.Drawing; using System.Runtime.InteropServices; +using System; using System.Windows.Forms; namespace BluePointLilac.Controls @@ -14,14 +15,16 @@ protected override void OnLoad(EventArgs e) { StartPosition = FormStartPosition.CenterScreen; base.OnLoad(e); + // 初始化主题 + InitTheme(); } - public static Color ButtonMain => MyMainForm.ButtonMain; - public static Color ButtonSecond => MyMainForm.ButtonSecond; + public static Color ButtonMain => DarkModeHelper.ButtonMain; + public static Color ButtonSecond => DarkModeHelper.ButtonSecond; - public static Color FormBack => MyMainForm.FormBack; - public static Color FormFore => MyMainForm.FormFore; - public static Color FormBorder => MyMainForm.FormBorder; + public static Color FormBack => DarkModeHelper.FormBack; + public static Color FormFore => DarkModeHelper.FormFore; + public static Color FormBorder => DarkModeHelper.FormBorder; [DllImport("UXTheme.dll", SetLastError = true, EntryPoint = "#138")] public static extern bool CheckSystemDarkModeStatus(); @@ -43,14 +46,30 @@ protected override CreateParams CreateParams public bool InitTheme() { - bool newDarkTheme = MyMainForm.IsDarkTheme(); + bool newDarkTheme = DarkModeHelper.IsDarkTheme; bool changed = darkTheme != newDarkTheme; darkTheme = newDarkTheme; - if (changed) + if (changed && IsHandleCreated) { - DwmSetWindowAttribute(Handle, 20, new[] { darkTheme ? 1 : 0 }, 4); - Adjust(); + try + { + DwmSetWindowAttribute(Handle, 20, new[] { darkTheme ? 1 : 0 }, 4); + } + catch + { + // API调用失败,忽略错误 + } + + // 在UI线程上调整颜色 + if (InvokeRequired) + { + Invoke(new Action(Adjust)); + } + else + { + Adjust(); + } Invalidate(); } @@ -59,29 +78,36 @@ public bool InitTheme() protected void ApplyDarkModeToDataGridView(DataGridView dgv) { + // 确保在UI线程上执行 + if (dgv.InvokeRequired) + { + dgv.Invoke(new Action(() => ApplyDarkModeToDataGridView(dgv))); + return; + } + // Background color - dgv.BackgroundColor = MyMainForm.FormBack; - dgv.DefaultCellStyle.BackColor = MyMainForm.FormBack; - dgv.DefaultCellStyle.ForeColor = MyMainForm.FormFore; + dgv.BackgroundColor = DarkModeHelper.FormBack; + dgv.DefaultCellStyle.BackColor = DarkModeHelper.FormBack; + dgv.DefaultCellStyle.ForeColor = DarkModeHelper.FormFore; // Grid color dgv.GridColor = Color.DimGray; // Header style - dgv.ColumnHeadersDefaultCellStyle.BackColor = MyMainForm.FormBack; - dgv.ColumnHeadersDefaultCellStyle.ForeColor = MyMainForm.FormFore; - dgv.ColumnHeadersDefaultCellStyle.SelectionBackColor = MyMainForm.MainColor; - dgv.ColumnHeadersDefaultCellStyle.SelectionForeColor = MyMainForm.FormFore; + dgv.ColumnHeadersDefaultCellStyle.BackColor = DarkModeHelper.FormBack; + dgv.ColumnHeadersDefaultCellStyle.ForeColor = DarkModeHelper.FormFore; + dgv.ColumnHeadersDefaultCellStyle.SelectionBackColor = DarkModeHelper.MainColor; + dgv.ColumnHeadersDefaultCellStyle.SelectionForeColor = DarkModeHelper.FormFore; dgv.EnableHeadersVisualStyles = false; // Ensure custom header styles apply // Row styles - dgv.RowsDefaultCellStyle.BackColor = MyMainForm.FormBack; - dgv.RowsDefaultCellStyle.ForeColor = MyMainForm.FormFore; - dgv.AlternatingRowsDefaultCellStyle.BackColor = MyMainForm.FormBack; + dgv.RowsDefaultCellStyle.BackColor = DarkModeHelper.FormBack; + dgv.RowsDefaultCellStyle.ForeColor = DarkModeHelper.FormFore; + dgv.AlternatingRowsDefaultCellStyle.BackColor = DarkModeHelper.FormBack; // Selection color - dgv.DefaultCellStyle.SelectionBackColor = MyMainForm.MainColor; - dgv.DefaultCellStyle.SelectionForeColor = MyMainForm.FormFore; + dgv.DefaultCellStyle.SelectionBackColor = DarkModeHelper.MainColor; + dgv.DefaultCellStyle.SelectionForeColor = DarkModeHelper.FormFore; } private void Adjust() @@ -89,5 +115,21 @@ private void Adjust() BackColor = FormBack; ForeColor = FormFore; } + + protected override void OnHandleCreated(EventArgs e) + { + base.OnHandleCreated(e); + // 应用深色模式到窗体 + DarkModeHelper.ApplyDarkModeToForm(this); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + // 清理资源 + } + base.Dispose(disposing); + } } -} +} \ No newline at end of file diff --git a/ContextMenuManager/Controls/RToolStripMenuItem.cs b/ContextMenuManager/Controls/RToolStripMenuItem.cs index 67034a9d..d1f2d1a1 100644 --- a/ContextMenuManager/Controls/RToolStripMenuItem.cs +++ b/ContextMenuManager/Controls/RToolStripMenuItem.cs @@ -9,32 +9,32 @@ internal class RToolStripMenuItem : ToolStripMenuItem { public RToolStripMenuItem() : base() { - ForeColor = MyMainForm.FormFore; - BackColor = MyMainForm.FormBack; + ForeColor = DarkModeHelper.FormFore; + BackColor = DarkModeHelper.FormBack; } public RToolStripMenuItem(string text) : base(text) { - ForeColor = MyMainForm.FormFore; - BackColor = MyMainForm.FormBack; + ForeColor = DarkModeHelper.FormFore; + BackColor = DarkModeHelper.FormBack; } public RToolStripMenuItem(string text, Image image) : base(text, image) { - ForeColor = MyMainForm.FormFore; - BackColor = MyMainForm.FormBack; + ForeColor = DarkModeHelper.FormFore; + BackColor = DarkModeHelper.FormBack; } public RToolStripMenuItem(string text, Image image, EventHandler onClick) : base(text, image, onClick) { - ForeColor = MyMainForm.FormFore; - BackColor = MyMainForm.FormBack; + ForeColor = DarkModeHelper.FormFore; + BackColor = DarkModeHelper.FormBack; } public RToolStripMenuItem(string text, Image image, EventHandler onClick, string name) : base(text, image, onClick, name) { - ForeColor = MyMainForm.FormFore; - BackColor = MyMainForm.FormBack; + ForeColor = DarkModeHelper.FormFore; + BackColor = DarkModeHelper.FormBack; } } @@ -42,8 +42,8 @@ public class RToolStripSeparator : ToolStripSeparator { public RToolStripSeparator() : base() { - ForeColor = MyMainForm.FormFore; - BackColor = MyMainForm.FormBack; + ForeColor = DarkModeHelper.FormFore; + BackColor = DarkModeHelper.FormBack; } } -} +} \ No newline at end of file diff --git a/ContextMenuManager/Controls/RestoreItem.cs b/ContextMenuManager/Controls/RestoreItem.cs index 3e81f650..6ff91696 100644 --- a/ContextMenuManager/Controls/RestoreItem.cs +++ b/ContextMenuManager/Controls/RestoreItem.cs @@ -51,7 +51,7 @@ private void InitializeComponents() TsiRestoreMe = new RestoreMeMenuItem(this); // 设置菜单:详细信息;删除备份;恢复备份 - ContextMenuStrip.Items.AddRange(new ToolStripItem[] { TsiDetails, new RToolStripSeparator(), + ContextMenuStrip.Items.AddRange(new ToolStripItem[] { TsiDetails, new RToolStripSeparator(), TsiRestoreMe, new RToolStripSeparator(), TsiDeleteMe }); // 详细信息 diff --git a/ContextMenuManager/Controls/RestoreListDialog.cs b/ContextMenuManager/Controls/RestoreListDialog.cs index 60b49093..cbb3dadc 100644 --- a/ContextMenuManager/Controls/RestoreListDialog.cs +++ b/ContextMenuManager/Controls/RestoreListDialog.cs @@ -67,8 +67,7 @@ public RestoreListForm() ReadOnly = true }; - readonly Label lblRestore = new Label - { + readonly Label lblRestore = new Label { Width = 480.DpiZoom() }; diff --git a/ContextMenuManager/Controls/RuleItem.cs b/ContextMenuManager/Controls/RuleItem.cs index 472a1ca5..ce16eefe 100644 --- a/ContextMenuManager/Controls/RuleItem.cs +++ b/ContextMenuManager/Controls/RuleItem.cs @@ -31,7 +31,7 @@ public string SearchText { get { - if (FoldGroupItem == null) return Text; + if(FoldGroupItem == null) return Text; else return $"{FoldGroupItem.Text} {Text}"; } } @@ -95,30 +95,30 @@ public bool ItemVisible { get { - for (int i = 0; i < Rules.Length; i++) + for(int i = 0; i < Rules.Length; i++) { RegRule rule = Rules[i]; - using (RegistryKey key = RegistryEx.GetRegistryKey(rule.RegPath)) + using(RegistryKey key = RegistryEx.GetRegistryKey(rule.RegPath)) { string value = key?.GetValue(rule.ValueName)?.ToString().ToLower(); string turnOnValue = rule.TurnOnValue?.ToString().ToLower(); string turnOffValue = rule.TurnOffValue?.ToString().ToLower(); - if (value == null || key.GetValueKind(rule.ValueName) != rule.ValueKind) + if(value == null || key.GetValueKind(rule.ValueName) != rule.ValueKind) { - if (i < Rules.Length - 1) continue; + if(i < Rules.Length - 1) continue; } - if (value == turnOnValue) return true; - if (value == turnOffValue) return false; + if(value == turnOnValue) return true; + if(value == turnOffValue) return false; } } return true; } set { - foreach (RegRule rule in Rules) + foreach(RegRule rule in Rules) { object data = value ? rule.TurnOnValue : rule.TurnOffValue; - if (data != null) + if(data != null) { Registry.SetValue(rule.RegPath, rule.ValueName, data, rule.ValueKind); } @@ -127,7 +127,7 @@ public bool ItemVisible RegistryEx.DeleteValue(rule.RegPath, rule.ValueName); } } - if (RestartExplorer) ExplorerRestarter.Show(); + if(RestartExplorer) ExplorerRestarter.Show(); } } @@ -243,8 +243,8 @@ public struct RegRule readonly NumericUpDown NudValue = new NumericUpDown { - ForeColor = MyMainForm.FormFore, - BackColor = MyMainForm.ButtonMain, + ForeColor = DarkModeHelper.FormFore, + BackColor = DarkModeHelper.ButtonMain, TextAlign = HorizontalAlignment.Center, Width = 80.DpiZoom() }; @@ -262,14 +262,14 @@ public NumberRegRuleItem(RegRule rule, ItemInfo info) : base(info) NudValue.Font = new Font(Font.FontFamily, Font.Size + 3F); NudValue.ValueChanged += (sender, e) => { - if (NudValue.Value == Rule.DefaultValue) + if(NudValue.Value == Rule.DefaultValue) { - NudValue.ForeColor = MyMainForm.MainColor; + NudValue.ForeColor = DarkModeHelper.MainColor; NudValue.Font = new Font(NudValue.Font, FontStyle.Bold); } else { - NudValue.ForeColor = MyMainForm.FormFore; + NudValue.ForeColor = DarkModeHelper.FormFore; NudValue.Font = new Font(NudValue.Font, FontStyle.Regular); } ItemValue = (int)NudValue.Value; @@ -286,16 +286,16 @@ public int ItemValue get { object value = Registry.GetValue(Rule.RegPath, Rule.ValueName, null); - if (value == null) return Rule.DefaultValue; + if(value == null) return Rule.DefaultValue; int num = Convert.ToInt32(value); - if (num > Rule.MaxValue) return Rule.MaxValue; - if (num < Rule.MinValue) return Rule.MinValue; + if(num > Rule.MaxValue) return Rule.MaxValue; + if(num < Rule.MinValue) return Rule.MinValue; else return num; } set { Registry.SetValue(Rule.RegPath, Rule.ValueName, value, Rule.ValueKind); - if (RestartExplorer) ExplorerRestarter.Show(); + if(RestartExplorer) ExplorerRestarter.Show(); } } } @@ -311,7 +311,7 @@ public struct RegRule readonly Label LblValue = new Label { BorderStyle = BorderStyle.FixedSingle, - ForeColor = MyMainForm.FormFore, + ForeColor = DarkModeHelper.FormFore, Cursor = Cursors.Hand, AutoSize = true }; @@ -329,11 +329,11 @@ public StringRegRuleItem(RegRule rule, ItemInfo info) : base(info) LblValue.Font = new Font(Font.FontFamily, Font.Size + 3F); LblValue.MouseDown += (sender, e) => { - using (InputDialog dlg = new InputDialog()) + using(InputDialog dlg = new InputDialog()) { dlg.Title = AppString.Menu.ChangeText; dlg.Text = ItemValue; - if (dlg.ShowDialog() != DialogResult.OK) return; + if(dlg.ShowDialog() != DialogResult.OK) return; ItemValue = LblValue.Text = dlg.Text; } }; @@ -350,7 +350,7 @@ public string ItemValue set { Registry.SetValue(Rule.RegPath, Rule.ValueName, value); - if (RestartExplorer) ExplorerRestarter.Show(); + if(RestartExplorer) ExplorerRestarter.Show(); } } } @@ -383,7 +383,7 @@ public bool ItemVisible set { IniWriter.SetValue(Rule.Section, Rule.KeyName, value ? Rule.TurnOnValue : Rule.TurnOffValue); - if (RestartExplorer) ExplorerRestarter.Show(); + if(RestartExplorer) ExplorerRestarter.Show(); } } } @@ -411,14 +411,14 @@ public NumberIniRuleItem(IniRule rule, ItemInfo info) : base(info) NudValue.Font = new Font(Font.FontFamily, Font.Size + 3F); NudValue.ValueChanged += (sender, e) => { - if (NudValue.Value == Rule.DefaultValue) + if(NudValue.Value == Rule.DefaultValue) { - NudValue.ForeColor = MyMainForm.MainColor; + NudValue.ForeColor = DarkModeHelper.MainColor; NudValue.Font = new Font(NudValue.Font, FontStyle.Bold); } else { - NudValue.ForeColor = MyMainForm.FormFore; + NudValue.ForeColor = DarkModeHelper.FormFore; NudValue.Font = new Font(NudValue.Font, FontStyle.Regular); } ItemValue = (int)NudValue.Value; @@ -431,8 +431,8 @@ public NumberIniRuleItem(IniRule rule, ItemInfo info) : base(info) readonly NumericUpDown NudValue = new NumericUpDown { - ForeColor = MyMainForm.FormFore, - BackColor = MyMainForm.ButtonMain, + ForeColor = DarkModeHelper.FormFore, + BackColor = DarkModeHelper.ButtonMain, TextAlign = HorizontalAlignment.Center, Width = 80.DpiZoom() }; @@ -442,16 +442,16 @@ public int ItemValue get { string value = IniWriter.GetValue(Rule.Section, Rule.KeyName); - if (value.IsNullOrWhiteSpace()) return Rule.DefaultValue; + if(value.IsNullOrWhiteSpace()) return Rule.DefaultValue; int num = Convert.ToInt32(value); - if (num > Rule.MaxValue) return Rule.MaxValue; - if (num < Rule.MinValue) return Rule.MinValue; + if(num > Rule.MaxValue) return Rule.MaxValue; + if(num < Rule.MinValue) return Rule.MinValue; else return num; } set { IniWriter.SetValue(Rule.Section, Rule.KeyName, value); - if (RestartExplorer) ExplorerRestarter.Show(); + if(RestartExplorer) ExplorerRestarter.Show(); } } } @@ -469,7 +469,7 @@ public struct IniRule readonly Label LblValue = new Label { BorderStyle = BorderStyle.FixedSingle, - ForeColor = MyMainForm.FormFore, + ForeColor = DarkModeHelper.FormFore, Cursor = Cursors.Hand, AutoSize = true }; @@ -484,11 +484,11 @@ public StringIniRuleItem(IniRule rule, ItemInfo info) : base(info) LblValue.Font = new Font(Font.FontFamily, Font.Size + 3F); LblValue.MouseDown += (sender, e) => { - using (InputDialog dlg = new InputDialog()) + using(InputDialog dlg = new InputDialog()) { dlg.Title = AppString.Menu.ChangeText; dlg.Text = ItemValue; - if (dlg.ShowDialog() != DialogResult.OK) return; + if(dlg.ShowDialog() != DialogResult.OK) return; ItemValue = LblValue.Text = dlg.Text; } }; @@ -504,7 +504,7 @@ public string ItemValue set { IniWriter.SetValue(Rule.Secation, Rule.KeyName, value); - if (RestartExplorer) ExplorerRestarter.Show(); + if(RestartExplorer) ExplorerRestarter.Show(); } } } diff --git a/ContextMenuManager/Controls/SearchableListBase.cs b/ContextMenuManager/Controls/SearchableListBase.cs deleted file mode 100644 index 84aa914b..00000000 --- a/ContextMenuManager/Controls/SearchableListBase.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Windows.Forms; - -namespace ContextMenuManager.Controls -{ - public abstract class SearchableListBase : UserControl - { - public virtual void SearchItems(string searchText) - { - // 默认实现:搜索所有 MyListItem 控件 - var items = GetAllItems(); - - if (string.IsNullOrWhiteSpace(searchText)) - { - // 清空搜索,显示所有项 - foreach (var item in items) - { - item.Visible = true; - if (item is BluePointLilac.Controls.MyListItem myItem) - { - myItem.HighlightText = null; - } - } - return; - } - - // 搜索所有列表项 - foreach (var item in items) - { - bool matches = item.Text.IndexOf(searchText, StringComparison.OrdinalIgnoreCase) >= 0; - item.Visible = matches; - - if (item is BluePointLilac.Controls.MyListItem myItem) - { - if (matches) - { - myItem.HighlightText = searchText; - } - else - { - myItem.HighlightText = null; - } - } - } - } - - public virtual IEnumerable GetAllItems() - { - // 默认实现:返回所有子控件 - return Controls.Cast(); - } - } -} \ No newline at end of file diff --git a/ContextMenuManager/Controls/SendToItem.cs b/ContextMenuManager/Controls/SendToItem.cs index 104ebea0..6bbcab89 100644 --- a/ContextMenuManager/Controls/SendToItem.cs +++ b/ContextMenuManager/Controls/SendToItem.cs @@ -25,7 +25,7 @@ public string FilePath set { filePath = value; - if (IsShortcut) ShellLink = new ShellLink(value); + if(IsShortcut) ShellLink = new ShellLink(value); Text = ItemText; Image = ItemImage; } @@ -43,23 +43,23 @@ public string ItemFilePath get { string path = null; - if (IsShortcut) path = ShellLink.TargetPath; + if(IsShortcut) path = ShellLink.TargetPath; else { - using (RegistryKey root = Registry.ClassesRoot) - using (RegistryKey extKey = root.OpenSubKey(FileExtension)) + using(RegistryKey root = Registry.ClassesRoot) + using(RegistryKey extKey = root.OpenSubKey(FileExtension)) { string guidPath = extKey?.GetValue("")?.ToString(); - if (!string.IsNullOrEmpty(guidPath)) + if(!string.IsNullOrEmpty(guidPath)) { - using (RegistryKey ipsKey = root.OpenSubKey($@"{guidPath}\InProcServer32")) + using(RegistryKey ipsKey = root.OpenSubKey($@"{guidPath}\InProcServer32")) { path = ipsKey?.GetValue("")?.ToString(); } } } } - if (!File.Exists(path) && !Directory.Exists(path)) path = FilePath; + if(!File.Exists(path) && !Directory.Exists(path)) path = FilePath; return path; } } @@ -70,7 +70,7 @@ public bool ItemVisible set { FileAttributes attributes = File.GetAttributes(FilePath); - if (value) attributes &= ~FileAttributes.Hidden; + if(value) attributes &= ~FileAttributes.Hidden; else attributes |= FileAttributes.Hidden; File.SetAttributes(FilePath, attributes); } @@ -81,8 +81,8 @@ public string ItemText get { string name = DesktopIni.GetLocalizedFileNames(FilePath, true); - if (name == string.Empty) name = Path.GetFileNameWithoutExtension(FilePath); - if (name == string.Empty) name = FileExtension; + if(name == string.Empty) name = Path.GetFileNameWithoutExtension(FilePath); + if(name == string.Empty) name = FileExtension; return name; } set @@ -99,14 +99,14 @@ public Icon ItemIcon { Icon icon = ResourceIcon.GetIcon(IconLocation, out string iconPath, out int iconIndex); IconPath = iconPath; IconIndex = iconIndex; - if (icon != null) return icon; - if (IsShortcut) + if(icon != null) return icon; + if(IsShortcut) { string path = ItemFilePath; - if (File.Exists(path)) icon = ResourceIcon.GetExtensionIcon(path); - else if (Directory.Exists(path)) icon = ResourceIcon.GetFolderIcon(path); + if(File.Exists(path)) icon = ResourceIcon.GetExtensionIcon(path); + else if(Directory.Exists(path)) icon = ResourceIcon.GetFolderIcon(path); } - if (icon == null) icon = ResourceIcon.GetExtensionIcon(FileExtension); + if(icon == null) icon = ResourceIcon.GetExtensionIcon(FileExtension); return icon; } } @@ -116,18 +116,18 @@ public string IconLocation get { string location = null; - if (IsShortcut) + if(IsShortcut) { ShellLink.ICONLOCATION iconLocation = ShellLink.IconLocation; string iconPath = iconLocation.IconPath; int iconIndex = iconLocation.IconIndex; - if (string.IsNullOrEmpty(iconPath)) iconPath = ShellLink.TargetPath; + if(string.IsNullOrEmpty(iconPath)) iconPath = ShellLink.TargetPath; location = $@"{iconPath},{iconIndex}"; } else { - using (RegistryKey root = Registry.ClassesRoot) - using (RegistryKey extensionKey = root.OpenSubKey(FileExtension)) + using(RegistryKey root = Registry.ClassesRoot) + using(RegistryKey extensionKey = root.OpenSubKey(FileExtension)) { // 检查extensionKey是否为null if (extensionKey != null) @@ -135,7 +135,7 @@ public string IconLocation string guidPath = extensionKey.GetValue("")?.ToString(); if (!string.IsNullOrEmpty(guidPath)) { - using (RegistryKey guidKey = root.OpenSubKey($@"{guidPath}\DefaultIcon")) + using(RegistryKey guidKey = root.OpenSubKey($@"{guidPath}\DefaultIcon")) { // 检查guidKey是否为null if (guidKey != null) @@ -151,7 +151,7 @@ public string IconLocation } set { - if (IsShortcut) + if(IsShortcut) { ShellLink.IconLocation = new ShellLink.ICONLOCATION { @@ -162,11 +162,11 @@ public string IconLocation } else { - using (RegistryKey root = Registry.ClassesRoot) - using (RegistryKey extensionKey = root.OpenSubKey(FileExtension)) + using(RegistryKey root = Registry.ClassesRoot) + using(RegistryKey extensionKey = root.OpenSubKey(FileExtension)) { string guidPath = extensionKey.GetValue("")?.ToString(); - if (guidPath != null) + if(guidPath != null) { string regPath = $@"{root.Name}\{guidPath}\DefaultIcon"; RegTrustedInstaller.TakeRegTreeOwnerShip(regPath); @@ -218,7 +218,7 @@ private void InitializeComponents() TsiChangeCommand.Click += (sender, e) => { - if (TsiChangeCommand.ChangeCommand(ShellLink)) + if(TsiChangeCommand.ChangeCommand(ShellLink)) { Image = ItemImage; } diff --git a/ContextMenuManager/Controls/SendToList.cs b/ContextMenuManager/Controls/SendToList.cs index 6cd0c3ca..719c778a 100644 --- a/ContextMenuManager/Controls/SendToList.cs +++ b/ContextMenuManager/Controls/SendToList.cs @@ -14,9 +14,9 @@ sealed class SendToList : MyList // 主页 发送到 public void LoadItems() { - foreach (string path in Directory.GetFileSystemEntries(SendToPath)) + foreach(string path in Directory.GetFileSystemEntries(SendToPath)) { - if (Path.GetFileName(path).ToLower() == "desktop.ini") continue; + if(Path.GetFileName(path).ToLower() == "desktop.ini") continue; AddItem(new SendToItem(path)); } SortItemByText(); @@ -32,13 +32,13 @@ private void AddNewItem() InsertItem(newItem, 0); newItem.AddNewItem += () => { - using (NewLnkFileDialog dlg = new NewLnkFileDialog()) + using(NewLnkFileDialog dlg = new NewLnkFileDialog()) { dlg.FileFilter = $"{AppString.Dialog.Program}|*.exe;*.bat;*.cmd;*.vbs;*.vbe;*.js;*.jse;*.wsf"; - if (dlg.ShowDialog() != DialogResult.OK) return; + if(dlg.ShowDialog() != DialogResult.OK) return; string lnkPath = $@"{SendToPath}\{ObjectPath.RemoveIllegalChars(dlg.ItemText)}.lnk"; lnkPath = ObjectPath.GetNewPathWithIndex(lnkPath, ObjectPath.PathType.File); - using (ShellLink shellLink = new ShellLink(lnkPath)) + using(ShellLink shellLink = new ShellLink(lnkPath)) { shellLink.TargetPath = dlg.ItemFilePath; shellLink.WorkingDirectory = Path.GetDirectoryName(dlg.ItemFilePath); @@ -69,13 +69,13 @@ private void AddDirItem() tsiRestoreDefault.Enabled = Directory.Exists(DefaultSendToPath); tsiRestoreDefault.Click += (sender, e) => { - if (AppMessageBox.Show(AppString.Message.RestoreDefault, MessageBoxButtons.OKCancel) == DialogResult.OK) + if(AppMessageBox.Show(AppString.Message.RestoreDefault, MessageBoxButtons.OKCancel) == DialogResult.OK) { File.SetAttributes(SendToPath, FileAttributes.Normal); Directory.Delete(SendToPath, true); Directory.CreateDirectory(SendToPath); File.SetAttributes(SendToPath, File.GetAttributes(DefaultSendToPath)); - foreach (string srcPath in Directory.GetFiles(DefaultSendToPath)) + foreach(string srcPath in Directory.GetFiles(DefaultSendToPath)) { string dstPath = $@"{SendToPath}\{Path.GetFileName(srcPath)}"; File.Copy(srcPath, dstPath); diff --git a/ContextMenuManager/Controls/ShellExItem.cs b/ContextMenuManager/Controls/ShellExItem.cs index 4f47f38b..889b8386 100644 --- a/ContextMenuManager/Controls/ShellExItem.cs +++ b/ContextMenuManager/Controls/ShellExItem.cs @@ -15,20 +15,20 @@ public static Dictionary GetPathAndGuids(string shellExPath, bool { Dictionary dic = new Dictionary(); string[] parts = isDragDrop ? DdhParts : CmhParts; - foreach (string part in parts) + foreach(string part in parts) { - using (RegistryKey cmKey = RegistryEx.GetRegistryKey($@"{shellExPath}\{part}")) + using(RegistryKey cmKey = RegistryEx.GetRegistryKey($@"{shellExPath}\{part}")) { - if (cmKey == null) continue; - foreach (string keyName in cmKey.GetSubKeyNames()) + if(cmKey == null) continue; + foreach(string keyName in cmKey.GetSubKeyNames()) { try { - using (RegistryKey key = cmKey.OpenSubKey(keyName)) + using(RegistryKey key = cmKey.OpenSubKey(keyName)) { - if (!GuidEx.TryParse(key.GetValue("")?.ToString(), out Guid guid)) + if(!GuidEx.TryParse(key.GetValue("")?.ToString(), out Guid guid)) GuidEx.TryParse(keyName, out guid); - if (!guid.Equals(Guid.Empty)) + if(!guid.Equals(Guid.Empty)) dic.Add(key.Name, guid); } } @@ -143,7 +143,7 @@ private void InitializeComponents() public bool TryProtectOpenItem() { - if (!ChkVisible.Checked || !Guid.Equals(LnkOpenGuid) || !AppConfig.ProtectOpenItem) return true; + if(!ChkVisible.Checked || !Guid.Equals(LnkOpenGuid) || !AppConfig.ProtectOpenItem) return true; return AppMessageBox.Show(AppString.Message.PromptIsOpenItem, MessageBoxButtons.YesNo) == DialogResult.Yes; } diff --git a/ContextMenuManager/Controls/ShellExecuteDialog.cs b/ContextMenuManager/Controls/ShellExecuteDialog.cs index db461184..650dcb35 100644 --- a/ContextMenuManager/Controls/ShellExecuteDialog.cs +++ b/ContextMenuManager/Controls/ShellExecuteDialog.cs @@ -16,11 +16,11 @@ public override void Reset() { } protected override bool RunDialog(IntPtr hwndOwner) { - using (ShellExecuteForm frm = new ShellExecuteForm()) + using(ShellExecuteForm frm = new ShellExecuteForm()) { frm.TopMost = true; bool flag = frm.ShowDialog() == DialogResult.OK; - if (flag) + if(flag) { Verb = frm.Verb; WindowStyle = frm.WindowStyle; @@ -32,7 +32,7 @@ protected override bool RunDialog(IntPtr hwndOwner) public static string GetCommand(string fileName, string arguments, string verb, int windowStyle, string directory = null) { arguments = arguments.Replace("\"", "\"\""); - if (directory == null) + if(directory == null) { ObjectPath.GetFullFilePath(fileName, out string filePath); directory = Path.GetDirectoryName(filePath); @@ -73,8 +73,8 @@ public ShellExecuteForm() }; readonly NumericUpDown nudStyle = new NumericUpDown { - ForeColor = MyMainForm.FormFore, - BackColor = MyMainForm.ButtonMain, + ForeColor = DarkModeHelper.FormFore, // 修改这里 + BackColor = DarkModeHelper.ButtonMain, // 修改这里 TextAlign = HorizontalAlignment.Center, Width = 80.DpiZoom(), Maximum = 10, @@ -99,7 +99,7 @@ private void InitializeComponents() Controls.AddRange(new Control[] { grpVerb, lblStyle, nudStyle, btnOK, btnCancel }); int a = 10.DpiZoom(); int b = 2 * a; - for (int i = 0; i < 6; i++) + for(int i = 0; i < 6; i++) { rdoVerbs[i] = new RadioButton { @@ -108,7 +108,7 @@ private void InitializeComponents() Parent = grpVerb, Location = new Point(a, b + a) }; - if (i > 0) rdoVerbs[i].Left += rdoVerbs[i - 1].Right; + if(i > 0) rdoVerbs[i].Left += rdoVerbs[i - 1].Right; } rdoVerbs[0].Checked = true; grpVerb.Width = rdoVerbs[5].Right + a; @@ -121,9 +121,9 @@ private void InitializeComponents() ClientSize = new Size(btnCancel.Right + b, btnCancel.Bottom + b); btnOK.Click += (sender, e) => { - for (int i = 0; i < 6; i++) + for(int i = 0; i < 6; i++) { - if (rdoVerbs[i].Checked) + if(rdoVerbs[i].Checked) { Verb = rdoVerbs[i].Text; break; @@ -152,16 +152,16 @@ public ShellExecuteCheckBox() protected override void OnClick(EventArgs e) { - if (Checked) + if(Checked) { Checked = false; ttpInfo.RemoveAll(); } else { - using (ShellExecuteDialog dlg = new ShellExecuteDialog()) + using(ShellExecuteDialog dlg = new ShellExecuteDialog()) { - if (dlg.ShowDialog() != DialogResult.OK) return; + if(dlg.ShowDialog() != DialogResult.OK) return; Verb = dlg.Verb; WindowStyle = dlg.WindowStyle; Checked = true; diff --git a/ContextMenuManager/Controls/ShellItem.cs b/ContextMenuManager/Controls/ShellItem.cs index e3956f6e..569af67d 100644 --- a/ContextMenuManager/Controls/ShellItem.cs +++ b/ContextMenuManager/Controls/ShellItem.cs @@ -46,7 +46,7 @@ public string RegPath regPath = value; Text = ItemText; Image = ItemIcon.ToBitmap(); - if (!HasIcon) Image = Image.ToTransparent(); + if(!HasIcon) Image = Image.ToTransparent(); BtnSubItems.Visible = IsMultiItem; } } @@ -65,9 +65,9 @@ private bool IsMultiItem get { object value = Registry.GetValue(RegPath, "SubCommands", null); - if (value != null) return true; + if(value != null) return true; value = Registry.GetValue(RegPath, "ExtendedSubCommandsKey", null); - if (!string.IsNullOrEmpty(value?.ToString())) return true; + if(!string.IsNullOrEmpty(value?.ToString())) return true; return false; } } @@ -77,9 +77,9 @@ private bool OnlyInExplorer get => Registry.GetValue(RegPath, "OnlyInBrowserWindow", null) != null; set { - if (value) + if(value) { - if (!TryProtectOpenItem()) return; + if(!TryProtectOpenItem()) return; Registry.SetValue(RegPath, "OnlyInBrowserWindow", ""); } else RegistryEx.DeleteValue(RegPath, "OnlyInBrowserWindow"); @@ -91,9 +91,9 @@ private bool OnlyWithShift get => Registry.GetValue(RegPath, "Extended", null) != null; set { - if (value) + if(value) { - if (!TryProtectOpenItem()) return; + if(!TryProtectOpenItem()) return; Registry.SetValue(RegPath, "Extended", ""); } else RegistryEx.DeleteValue(RegPath, "Extended"); @@ -105,8 +105,8 @@ private bool NoWorkingDirectory get => Registry.GetValue(RegPath, "NoWorkingDirectory", null) != null; set { - if (!TryProtectOpenItem()) return; - if (value) Registry.SetValue(RegPath, "NoWorkingDirectory", ""); + if(!TryProtectOpenItem()) return; + if(value) Registry.SetValue(RegPath, "NoWorkingDirectory", ""); else RegistryEx.DeleteValue(RegPath, "NoWorkingDirectory"); } } @@ -116,8 +116,8 @@ private bool NeverDefault get => Registry.GetValue(RegPath, "NeverDefault", null) != null; set { - if (!TryProtectOpenItem()) return; - if (value) Registry.SetValue(RegPath, "NeverDefault", ""); + if(!TryProtectOpenItem()) return; + if(value) Registry.SetValue(RegPath, "NeverDefault", ""); else RegistryEx.DeleteValue(RegPath, "NeverDefault"); } } @@ -127,10 +127,10 @@ private bool ShowAsDisabledIfHidden get => Registry.GetValue(RegPath, "ShowAsDisabledIfHidden", null) != null; set { - if (!TryProtectOpenItem()) return; - if (value) Registry.SetValue(RegPath, "ShowAsDisabledIfHidden", ""); + if(!TryProtectOpenItem()) return; + if(value) Registry.SetValue(RegPath, "ShowAsDisabledIfHidden", ""); else RegistryEx.DeleteValue(RegPath, "ShowAsDisabledIfHidden"); - if (value && !ItemVisible) ItemVisible = false; + if(value && !ItemVisible) ItemVisible = false; } } @@ -139,7 +139,7 @@ private Positions ItemPosition get { string value = Registry.GetValue(RegPath, "Position", null)?.ToString()?.ToLower(); - switch (value) + switch(value) { case "top": return Positions.Top; @@ -151,7 +151,7 @@ private Positions ItemPosition } set { - switch (value) + switch(value) { case Positions.Top: Registry.SetValue(RegPath, "Position", "top"); @@ -170,18 +170,18 @@ public bool ItemVisible // 是否显示于右键菜单中 { get { - if (WinOsVersion.Current >= WinOsVersion.Win10_1703) + if(WinOsVersion.Current >= WinOsVersion.Win10_1703) { //HideBasedOnVelocityId键值仅适用于Win10系统1703以上版本 - if (Convert.ToInt32(Registry.GetValue(RegPath, "HideBasedOnVelocityId", 0)) == 0x639bc8) return false; + if(Convert.ToInt32(Registry.GetValue(RegPath, "HideBasedOnVelocityId", 0)) == 0x639bc8) return false; } - if (!IsSubItem) + if(!IsSubItem) { //LegacyDisable和ProgrammaticAccessOnly键值不适用于子菜单 - if (Registry.GetValue(RegPath, "LegacyDisable", null) != null) return false; - if (Registry.GetValue(RegPath, "ProgrammaticAccessOnly", null) != null) return false; + if(Registry.GetValue(RegPath, "LegacyDisable", null) != null) return false; + if(Registry.GetValue(RegPath, "ProgrammaticAccessOnly", null) != null) return false; //CommandFlags键值不适用于Vista系统,子菜单中该键值我用来做分割线键值 - if (WinOsVersion.Current > WinOsVersion.Vista && Convert.ToInt32(Registry.GetValue(RegPath, "CommandFlags", 0)) % 16 >= 8) return false; + if(WinOsVersion.Current > WinOsVersion.Vista && Convert.ToInt32(Registry.GetValue(RegPath, "CommandFlags", 0)) % 16 >= 8) return false; } return true; } @@ -193,43 +193,42 @@ void DeleteSomeValues() { RegistryEx.DeleteValue(RegPath, "LegacyDisable"); RegistryEx.DeleteValue(RegPath, "ProgrammaticAccessOnly"); - if (WinOsVersion.Current > WinOsVersion.Vista && Convert.ToInt32(Registry.GetValue(RegPath, "CommandFlags", 0)) % 16 >= 8) + if(WinOsVersion.Current > WinOsVersion.Vista && Convert.ToInt32(Registry.GetValue(RegPath, "CommandFlags", 0)) % 16 >= 8) { RegistryEx.DeleteValue(RegPath, "CommandFlags"); } - } - ; + }; - if (value) + if(value) { RegistryEx.DeleteValue(RegPath, "HideBasedOnVelocityId"); DeleteSomeValues(); } else { - if (WinOsVersion.Current >= WinOsVersion.Win10_1703) + if(WinOsVersion.Current >= WinOsVersion.Win10_1703) { Registry.SetValue(RegPath, "HideBasedOnVelocityId", 0x639bc8); } else { - if (IsSubItem) + if(IsSubItem) { AppMessageBox.Show(AppString.Message.CannotHideSubItem); return; } } - if (!IsSubItem) + if(!IsSubItem) { //当LegaryDisable键值作用于文件夹-"在新窗口中打开"时 //会导致点击任务栏explorer图标和 Win+E 快捷键错误访问 - if (!RegPath.StartsWith(OpenInNewWindowPath, StringComparison.OrdinalIgnoreCase)) + if(!RegPath.StartsWith(OpenInNewWindowPath, StringComparison.OrdinalIgnoreCase)) { Registry.SetValue(RegPath, "LegacyDisable", ""); } Registry.SetValue(RegPath, "ProgrammaticAccessOnly", ""); } - if (ShowAsDisabledIfHidden) DeleteSomeValues(); + if(ShowAsDisabledIfHidden) DeleteSomeValues(); } } catch @@ -246,25 +245,25 @@ public string ItemText string name; //菜单名称优先级别:MUIVerb > 默认值 > 特殊键值名 > 项名 List valueNames = new List { "MUIVerb" }; - if (!IsMultiItem) valueNames.Add("");//多级母菜单不支持使用默认值作为名称 - foreach (string valueName in valueNames) + if(!IsMultiItem) valueNames.Add("");//多级母菜单不支持使用默认值作为名称 + foreach(string valueName in valueNames) { name = Registry.GetValue(RegPath, valueName, null)?.ToString(); name = ResourceString.GetDirectString(name); - if (!string.IsNullOrEmpty(name)) return name; + if(!string.IsNullOrEmpty(name)) return name; } - if (DefaultNameIndexs.TryGetValue(KeyName, out int index)) + if(DefaultNameIndexs.TryGetValue(KeyName, out int index)) { name = $"@windows.storage.dll,-{index}"; name = ResourceString.GetDirectString(name); - if (!string.IsNullOrEmpty(name)) return name; + if(!string.IsNullOrEmpty(name)) return name; } return KeyName; } set { //MUIVerb长度不可超过80,超过80系统会隐藏该菜单项目 - if (ResourceString.GetDirectString(value).Length >= 80) + if(ResourceString.GetDirectString(value).Length >= 80) { AppMessageBox.Show(AppString.Message.TextLengthCannotExceed80); } @@ -280,14 +279,14 @@ public string ItemCommand { get { - if (IsMultiItem) return null; + if(IsMultiItem) return null; else return Registry.GetValue(CommandPath, "", null)?.ToString(); } set { - if (!TryProtectOpenItem()) return; + if(!TryProtectOpenItem()) return; Registry.SetValue(CommandPath, "", value); - if (!HasIcon) Image = ItemIcon.ToBitmap().ToTransparent(); + if(!HasIcon) Image = ItemIcon.ToBitmap().ToTransparent(); } } @@ -296,7 +295,7 @@ private bool HasLUAShield get => Registry.GetValue(RegPath, "HasLUAShield", null) != null; set { - if (value) Registry.SetValue(RegPath, "HasLUAShield", ""); + if(value) Registry.SetValue(RegPath, "HasLUAShield", ""); else RegistryEx.DeleteValue(RegPath, "HasLUAShield"); } } @@ -306,7 +305,7 @@ public string IconLocation get => Registry.GetValue(RegPath, "Icon", null)?.ToString(); set { - if (value != null) Registry.SetValue(RegPath, "Icon", value); + if(value != null) Registry.SetValue(RegPath, "Icon", value); else RegistryEx.DeleteValue(RegPath, "Icon"); } } @@ -322,16 +321,16 @@ public Icon ItemIcon Icon icon; string iconPath; int iconIndex; - if (IconLocation != null) + if(IconLocation != null) { icon = ResourceIcon.GetIcon(IconLocation, out iconPath, out iconIndex); - if (icon == null && Path.GetExtension(iconPath)?.ToLower() == ".exe")//文件不存在,或为没有图标的exe文件 + if(icon == null && Path.GetExtension(iconPath)?.ToLower() == ".exe")//文件不存在,或为没有图标的exe文件 icon = ResourceIcon.GetIcon(iconPath = "imageres.dll", iconIndex = -15);//不含图标的默认exe图标 } - else if (HasLUAShield) + else if(HasLUAShield) icon = ResourceIcon.GetIcon(iconPath = "imageres.dll", iconIndex = -78);//管理员小盾牌图标 else icon = ResourceIcon.GetIcon(iconPath = ItemFilePath, iconIndex = 0);//文件第一个图标 - if (icon == null) icon = ResourceIcon.GetExtensionIcon(iconPath = ItemFilePath)//文件类型图标 + if(icon == null) icon = ResourceIcon.GetExtensionIcon(iconPath = ItemFilePath)//文件类型图标 ?? ResourceIcon.GetIcon(iconPath = "imageres.dll", iconIndex = -2);//图标资源不存在,白纸图标 IconPath = iconPath; IconIndex = iconIndex; @@ -349,10 +348,10 @@ private Guid Guid { $@"{RegPath}\DropTarget" , "CLSID" }, { RegPath , "ExplorerCommandHandler" }, }; - foreach (var item in keyValues) + foreach(var item in keyValues) { string value = Registry.GetValue(item.Key, item.Value, null)?.ToString(); - if (GuidEx.TryParse(value, out Guid guid)) return guid; + if(GuidEx.TryParse(value, out Guid guid)) return guid; } return Guid.Empty; } @@ -442,9 +441,9 @@ private void DeleteIcon() private void UseShieldIcon() { bool flag = HasLUAShield = TsiShieldIcon.Checked = !TsiShieldIcon.Checked; - if (IconLocation == null) + if(IconLocation == null) { - if (flag) + if(flag) { Image = AppImage.Shield; IconPath = "imageres.dll"; @@ -466,15 +465,15 @@ private void RefreshMenuItem() TsiShowAsDisabled.Checked = ShowAsDisabledIfHidden; TsiChangeCommand.Visible = !IsMultiItem && Guid.Equals(Guid.Empty); TsiClsidLocation.Visible = GuidInfo.GetClsidPath(Guid) != null; - if (!IsSubItem) TsiOnlyWithShift.Checked = OnlyWithShift; + if(!IsSubItem) TsiOnlyWithShift.Checked = OnlyWithShift; - if (WinOsVersion.Current >= WinOsVersion.Vista) + if(WinOsVersion.Current >= WinOsVersion.Vista) { TsiItemIcon.Visible = true; TsiPosition.Visible = !IsSubItem; TsiOnlyInExplorer.Visible = !IsSubItem; TsiNeverDefault.Visible = !IsSubItem; - if (HasIcon) + if(HasIcon) { TsiChangeIcon.Text = AppString.Menu.ChangeIcon; TsiDeleteIcon.Visible = true; @@ -486,12 +485,12 @@ private void RefreshMenuItem() } TsiShieldIcon.Checked = HasLUAShield; - if (!IsSubItem) + if(!IsSubItem) { TsiOnlyInExplorer.Checked = OnlyInExplorer; TsiNeverDefault.Checked = NeverDefault; TsiDefault.Checked = TsiSetTop.Checked = TsiSetBottom.Checked = false; - switch (ItemPosition) + switch(ItemPosition) { case Positions.Default: TsiDefault.Checked = true; @@ -516,12 +515,12 @@ private void RefreshMenuItem() private void ShowSubItems() { - if (WinOsVersion.Current == WinOsVersion.Vista) + if(WinOsVersion.Current == WinOsVersion.Vista) { AppMessageBox.Show(AppString.Message.VistaUnsupportedMulti); return; } - using (ShellSubMenuDialog dlg = new ShellSubMenuDialog()) + using(ShellSubMenuDialog dlg = new ShellSubMenuDialog()) { dlg.Text = AppString.Dialog.EditSubItems.Replace("%s", Text); dlg.Icon = ResourceIcon.GetIcon(IconPath, IconIndex); @@ -532,8 +531,8 @@ private void ShowSubItems() public bool TryProtectOpenItem() { - if (!IsOpenItem) return true; - if (!AppConfig.ProtectOpenItem) return true; + if(!IsOpenItem) return true; + if(!AppConfig.ProtectOpenItem) return true; return AppMessageBox.Show(AppString.Message.PromptIsOpenItem, MessageBoxButtons.YesNo) == DialogResult.Yes; } diff --git a/ContextMenuManager/Controls/ShellList.cs b/ContextMenuManager/Controls/ShellList.cs index 0c9a1a2b..26c19588 100644 --- a/ContextMenuManager/Controls/ShellList.cs +++ b/ContextMenuManager/Controls/ShellList.cs @@ -24,7 +24,7 @@ public sealed class ShellList : MyList // 文件类型 Ink文件 uwp Ink exe文 public const string MENUPATH_ALLOBJECTS = @"HKEY_CLASSES_ROOT\AllFilesystemObjects";//所有对象 public const string MENUPATH_COMPUTER = @"HKEY_CLASSES_ROOT\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}";//此电脑 public const string MENUPATH_RECYCLEBIN = @"HKEY_CLASSES_ROOT\CLSID\{645FF040-5081-101B-9F08-00AA002F954E}";//回收站 - + public const string MENUPATH_LIBRARY = @"HKEY_CLASSES_ROOT\LibraryFolder";//库 public const string MENUPATH_LIBRARY_BACKGROUND = @"HKEY_CLASSES_ROOT\LibraryFolder\Background";//库背景 public const string MENUPATH_LIBRARY_USER = @"HKEY_CLASSES_ROOT\UserLibraryFolder";//用户库 @@ -56,17 +56,17 @@ public sealed class ShellList : MyList // 文件类型 Ink文件 uwp Ink exe文 private static string GetDirectoryTypeName(string directoryType) { - if (directoryType == null) return null; + if(directoryType == null) return null; int index = DirectoryTypes.FindIndex(type => directoryType.Equals(type, StringComparison.OrdinalIgnoreCase)); - if (index >= 0) return DirectoryTypeNames[index]; + if(index >= 0) return DirectoryTypeNames[index]; else return null; } private static string GetPerceivedTypeName(string perceivedType) { int index = 0; - if (perceivedType != null) index = PerceivedTypes.FindIndex(type => perceivedType.Equals(type, StringComparison.OrdinalIgnoreCase)); - if (index == -1) index = 0; + if(perceivedType != null) index = PerceivedTypes.FindIndex(type => perceivedType.Equals(type, StringComparison.OrdinalIgnoreCase)); + if(index == -1) index = 0; return PerceivedTypeNames[index]; } @@ -87,12 +87,12 @@ public static DropEffect DefaultDropEffect { get { - foreach (string path in DropEffectPaths) + foreach(string path in DropEffectPaths) { object value = Registry.GetValue(path, "DefaultDropEffect", null); - if (value != null) + if(value != null) { - switch (value) + switch(value) { case 1: return DropEffect.Copy; @@ -108,7 +108,7 @@ public static DropEffect DefaultDropEffect set { object data; - switch (value) + switch(value) { case DropEffect.Copy: data = 1; break; @@ -119,7 +119,7 @@ public static DropEffect DefaultDropEffect default: data = 0; break; } - foreach (string path in DropEffectPaths) + foreach(string path in DropEffectPaths) { Registry.SetValue(path, "DefaultDropEffect", data, RegistryValueKind.DWord); } @@ -128,7 +128,7 @@ public static DropEffect DefaultDropEffect private static string GetDropEffectName() { - switch (DefaultDropEffect) + switch(DefaultDropEffect) { case DropEffect.Copy: return DropEffectNames[1]; @@ -153,7 +153,7 @@ private static string CurrentExtensionPerceivedType set { string path = $@"{RegistryEx.CLASSES_ROOT}\{CurrentExtension}"; - if (value == null) RegistryEx.DeleteValue(path, "PerceivedType"); + if(value == null) RegistryEx.DeleteValue(path, "PerceivedType"); else Registry.SetValue(path, "PerceivedType", value, RegistryValueKind.String); } } @@ -208,7 +208,7 @@ public void LoadItems() scenePath = MENUPATH_UNKNOWN; break; case Scenes.CustomExtension: bool isLnk = CurrentExtension?.ToLower() == ".lnk"; - if (isLnk) scenePath = GetOpenModePath(".lnk"); + if(isLnk) scenePath = GetOpenModePath(".lnk"); else scenePath = GetSysAssExtPath(CurrentExtension); break; case Scenes.PerceivedType: @@ -257,11 +257,11 @@ public void LoadItems() } AddNewItem(scenePath); // 新建一个菜单项目 LoadItems(scenePath); - if (WinOsVersion.Current >= WinOsVersion.Win10) + if(WinOsVersion.Current >= WinOsVersion.Win10) { LoadUwpModeItem(); } - switch (Scene) + switch(Scene) { case Scenes.Background: VisibleRegRuleItem item = new VisibleRegRuleItem(VisibleRegRuleItem.CustomFolder); @@ -299,37 +299,37 @@ public void LoadItems() private void LoadItems(string scenePath) { - if (scenePath == null) return; + if(scenePath == null) return; RegTrustedInstaller.TakeRegKeyOwnerShip(scenePath); LoadShellItems(GetShellPath(scenePath)); LoadShellExItems(GetShellExPath(scenePath)); } - + private void LoadShellItems(string shellPath) { using (RegistryKey shellKey = RegistryEx.GetRegistryKey(shellPath)) { if (shellKey == null) return; RegTrustedInstaller.TakeRegTreeOwnerShip(shellKey.Name); - foreach (string keyName in shellKey.GetSubKeyNames()) + foreach(string keyName in shellKey.GetSubKeyNames()) { ShellItem item = new ShellItem($@"{shellPath}\{keyName}"); AddItem(item); } } } - + private void LoadShellExItems(string shellExPath) { List names = new List(); - using (RegistryKey shellExKey = RegistryEx.GetRegistryKey(shellExPath)) + using(RegistryKey shellExKey = RegistryEx.GetRegistryKey(shellExPath)) { - if (shellExKey == null) return; + if(shellExKey == null) return; bool isDragDrop = Scene == Scenes.DragDrop; RegTrustedInstaller.TakeRegTreeOwnerShip(shellExKey.Name); Dictionary dic = ShellExItem.GetPathAndGuids(shellExPath, isDragDrop); FoldGroupItem groupItem = null; - if (isDragDrop) + if(isDragDrop) { groupItem = GetDragDropGroupItem(shellExPath); // TODO:什么是groupItem? @@ -347,10 +347,10 @@ private void LoadShellExItems(string shellExPath) foreach (string path in dic.Keys) { string keyName = RegistryEx.GetKeyName(path); - if (!names.Contains(keyName)) + if(!names.Contains(keyName)) { ShellExItem item = new ShellExItem(dic[path], path); - if (groupItem != null) + if(groupItem != null) { item.FoldGroupItem = groupItem; item.Indent(); @@ -368,7 +368,7 @@ private FoldGroupItem GetDragDropGroupItem(string shellExPath) string text = null; Image image = null; string path = shellExPath.Substring(0, shellExPath.LastIndexOf('\\')); - switch (path) + switch(path) { case MENUPATH_FOLDER: text = AppString.SideBar.Folder; @@ -394,9 +394,9 @@ private void LoadStoreItems() { using (RegistryKey shellKey = RegistryEx.GetRegistryKey(ShellItem.CommandStorePath)) { - foreach (string itemName in shellKey.GetSubKeyNames()) + foreach(string itemName in shellKey.GetSubKeyNames()) { - if (AppConfig.HideSysStoreItems && itemName.StartsWith("Windows.", StringComparison.OrdinalIgnoreCase)) continue; + if(AppConfig.HideSysStoreItems && itemName.StartsWith("Windows.", StringComparison.OrdinalIgnoreCase)) continue; AddItem(new StoreShellItem($@"{ShellItem.CommandStorePath}\{itemName}", true, false)); } } @@ -406,22 +406,22 @@ private void LoadUwpModeItem() { foreach (XmlDocument doc in XmlDicHelper.UwpModeItemsDic) { - if (doc?.DocumentElement == null) continue; - foreach (XmlNode sceneXN in doc.DocumentElement.ChildNodes) + if(doc?.DocumentElement == null) continue; + foreach(XmlNode sceneXN in doc.DocumentElement.ChildNodes) { - if (sceneXN.Name == Scene.ToString()) + if(sceneXN.Name == Scene.ToString()) { - foreach (XmlElement itemXE in sceneXN.ChildNodes) + foreach(XmlElement itemXE in sceneXN.ChildNodes) { - if (GuidEx.TryParse(itemXE.GetAttribute("Guid"), out Guid guid)) + if(GuidEx.TryParse(itemXE.GetAttribute("Guid"), out Guid guid)) { bool isAdded = false; - foreach (Control ctr in Controls) + foreach(Control ctr in Controls) { - if (ctr is UwpModeItem item && item.Guid == guid) { isAdded = true; break; } + if(ctr is UwpModeItem item && item.Guid == guid) { isAdded = true; break; } } - if (isAdded) continue; - if (GuidInfo.GetFilePath(guid) == null) continue; + if(isAdded) continue; + if(GuidInfo.GetFilePath(guid) == null) continue; string uwpName = GuidInfo.GetUwpName(guid); UwpModeItem uwpItem = new UwpModeItem(uwpName, guid); AddItem(uwpItem); @@ -439,7 +439,7 @@ private void LoadAnalysisItems() void AddFileItems(string filePath) { string extension = Path.GetExtension(filePath).ToLower(); - if (extension == string.Empty) extension = "."; + if(extension == string.Empty) extension = "."; string perceivedType = GetPerceivedType(extension); string perceivedTypeName = GetPerceivedTypeName(perceivedType); JumpItem.TargetPath = filePath; @@ -447,15 +447,15 @@ void AddFileItems(string filePath) JumpItem.PerceivedType = perceivedType; AddItem(new JumpItem(Scenes.File)); AddItem(new JumpItem(Scenes.AllObjects)); - if (extension == ".exe") AddItem(new JumpItem(Scenes.ExeFile)); + if(extension == ".exe") AddItem(new JumpItem(Scenes.ExeFile)); else AddItem(new JumpItem(Scenes.CustomExtension)); - if (GetOpenMode(extension) == null) AddItem(new JumpItem(Scenes.UnknownType)); - if (perceivedType != null) AddItem(new JumpItem(Scenes.PerceivedType)); + if(GetOpenMode(extension) == null) AddItem(new JumpItem(Scenes.UnknownType)); + if(perceivedType != null) AddItem(new JumpItem(Scenes.PerceivedType)); } void AddDirItems(string dirPath) { - if (!dirPath.EndsWith(":\\")) + if(!dirPath.EndsWith(":\\")) { AddItem(new JumpItem(Scenes.Folder)); AddItem(new JumpItem(Scenes.Directory)); @@ -469,22 +469,22 @@ void AddDirItems(string dirPath) } } - if (File.Exists(CurrentFileObjectPath)) + if(File.Exists(CurrentFileObjectPath)) { string extension = Path.GetExtension(CurrentFileObjectPath).ToLower(); - if (extension == ".lnk") + if(extension == ".lnk") { - using (ShellLink shellLink = new ShellLink(CurrentFileObjectPath)) + using(ShellLink shellLink = new ShellLink(CurrentFileObjectPath)) { string targetPath = shellLink.TargetPath; - if (File.Exists(targetPath)) AddFileItems(targetPath); - else if (Directory.Exists(targetPath)) AddDirItems(targetPath); + if(File.Exists(targetPath)) AddFileItems(targetPath); + else if(Directory.Exists(targetPath)) AddDirItems(targetPath); } AddItem(new JumpItem(Scenes.LnkFile)); } else AddFileItems(CurrentFileObjectPath); } - else if (Directory.Exists(CurrentFileObjectPath)) AddDirItems(CurrentFileObjectPath); + else if(Directory.Exists(CurrentFileObjectPath)) AddDirItems(CurrentFileObjectPath); } public class SelectItem : MyListItem @@ -508,33 +508,33 @@ private void SetTextAndTip() { string tip = ""; string text = ""; - switch (Scene) + switch(Scene) { case Scenes.CustomExtension: tip = AppString.Dialog.SelectExtension; - if (CurrentExtension == null) text = tip; + if(CurrentExtension == null) text = tip; else text = AppString.Other.CurrentExtension.Replace("%s", CurrentExtension); break; case Scenes.PerceivedType: tip = AppString.Dialog.SelectPerceivedType; - if (CurrentPerceivedType == null) text = tip; + if(CurrentPerceivedType == null) text = tip; else text = AppString.Other.CurrentPerceivedType.Replace("%s", GetPerceivedTypeName(CurrentPerceivedType)); break; case Scenes.DirectoryType: tip = AppString.Dialog.SelectDirectoryType; - if (CurrentDirectoryType == null) text = tip; + if(CurrentDirectoryType == null) text = tip; else text = AppString.Other.CurrentDirectoryType.Replace("%s", GetDirectoryTypeName(CurrentDirectoryType)); break; case Scenes.CustomRegPath: SelectedPath = CurrentCustomRegPath; tip = AppString.Other.SelectRegPath; - if (SelectedPath == null) text = tip; + if(SelectedPath == null) text = tip; else text = AppString.Other.CurrentRegPath + "\n" + SelectedPath; break; case Scenes.MenuAnalysis: SelectedPath = CurrentFileObjectPath; tip = AppString.Tip.DropOrSelectObject; - if (SelectedPath == null) text = tip; + if(SelectedPath == null) text = tip; else text = AppString.Other.CurrentFilePath + "\n" + SelectedPath; break; case Scenes.DragDrop: @@ -553,20 +553,20 @@ private void SetTextAndTip() private void SetImage() { - switch (Scene) + switch(Scene) { case Scenes.CustomExtensionPerceivedType: - using (Icon icon = ResourceIcon.GetExtensionIcon(CurrentExtension)) + using(Icon icon = ResourceIcon.GetExtensionIcon(CurrentExtension)) Image = icon?.ToBitmap(); break; } - if (Image == null) Image = AppImage.Custom; + if(Image == null) Image = AppImage.Custom; } private void ShowSelectDialog() { SelectDialog dlg = null; - switch (Scene) + switch(Scene) { case Scenes.CustomExtension: dlg = new FileExtensionDialog @@ -614,17 +614,17 @@ private void ShowSelectDialog() }; break; case Scenes.CustomRegPath: - if (AppMessageBox.Show(AppString.Message.SelectRegPath, + if(AppMessageBox.Show(AppString.Message.SelectRegPath, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; Form frm = FindForm(); frm.Hide(); - using (Process process = Process.Start("regedit.exe", "-m")) + using(Process process = Process.Start("regedit.exe", "-m")) { process.WaitForExit(); } string path = Registry.GetValue(LASTKEYPATH, "LastKey", "").ToString(); int index = path.IndexOf('\\'); - if (index == -1) return; + if(index == -1) return; path = path.Substring(index + 1); CurrentCustomRegPath = path; RefreshList(); @@ -632,7 +632,7 @@ private void ShowSelectDialog() frm.Activate(); break; } - switch (Scene) + switch(Scene) { case Scenes.CustomExtension: case Scenes.PerceivedType: @@ -640,10 +640,10 @@ private void ShowSelectDialog() case Scenes.MenuAnalysis: case Scenes.DragDrop: case Scenes.CustomExtensionPerceivedType: - if (dlg.ShowDialog() != DialogResult.OK) return; + if(dlg.ShowDialog() != DialogResult.OK) return; break; } - switch (Scene) + switch(Scene) { case Scenes.CustomExtension: CurrentExtension = dlg.Selected; @@ -663,7 +663,7 @@ private void ShowSelectDialog() Text = AppString.Other.SetPerceivedType.Replace("%s", CurrentExtension) + " " + GetPerceivedTypeName(selected); break; case Scenes.DragDrop: - switch (dlg.SelectedIndex) + switch(dlg.SelectedIndex) { case 0: DefaultDropEffect = DropEffect.Default; break; case 1: DefaultDropEffect = DropEffect.Copy; break; @@ -673,20 +673,20 @@ private void ShowSelectDialog() Text = AppString.Other.SetDefaultDropEffect + " " + GetDropEffectName(); break; case Scenes.MenuAnalysis: - if (dlg.SelectedIndex == 0) + if(dlg.SelectedIndex == 0) { - using (var dlg1 = new System.Windows.Forms.OpenFileDialog()) + using(var dlg1 = new System.Windows.Forms.OpenFileDialog()) { dlg1.DereferenceLinks = false; - if (dlg1.ShowDialog() != DialogResult.OK) return; + if(dlg1.ShowDialog() != DialogResult.OK) return; CurrentFileObjectPath = dlg1.FileName; } } else { - using (var dlg2 = new FolderBrowserDialog()) + using(var dlg2 = new FolderBrowserDialog()) { - if (dlg2.ShowDialog() != DialogResult.OK) return; + if(dlg2.ShowDialog() != DialogResult.OK) return; CurrentFileObjectPath = dlg2.SelectedPath; } } @@ -712,7 +712,7 @@ public JumpItem(Scenes scene) int index1 = 0; int index2 = 0; string[] txts = null; - switch (scene) + switch(scene) { case Scenes.File: txts = new[] { AppString.ToolBar.Home, AppString.SideBar.File }; @@ -746,7 +746,7 @@ public JumpItem(Scenes scene) break; case Scenes.ExeFile: txts = new[] { AppString.ToolBar.Type, AppString.SideBar.ExeFile }; - using (Icon icon = ResourceIcon.GetExtensionIcon(TargetPath)) image = icon.ToBitmap(); + using(Icon icon = ResourceIcon.GetExtensionIcon(TargetPath)) image = icon.ToBitmap(); index1 = 1; index2 = 2; //MainForm.TypeShellScenes break; @@ -758,7 +758,7 @@ public JumpItem(Scenes scene) break; case Scenes.CustomExtension: txts = new[] { AppString.ToolBar.Type, AppString.SideBar.CustomExtension, Extension }; - using (Icon icon = ResourceIcon.GetExtensionIcon(Extension)) image = icon.ToBitmap(); + using(Icon icon = ResourceIcon.GetExtensionIcon(Extension)) image = icon.ToBitmap(); index1 = 1; index2 = 5; //MainForm.TypeShellScenes break; @@ -779,7 +779,7 @@ public JumpItem(Scenes scene) Image = image; void SwitchTab() { - switch (scene) + switch(scene) { case Scenes.CustomExtension: CurrentExtension = Extension; break; @@ -787,8 +787,7 @@ void SwitchTab() CurrentPerceivedType = PerceivedType; break; } ((MainForm)FindForm()).JumpItem(index1, index2);// - } - ; + }; btnJump.MouseDown += (sender, e) => SwitchTab(); DoubleClick += (sender, e) => SwitchTab(); } diff --git a/ContextMenuManager/Controls/ShellNewItem.cs b/ContextMenuManager/Controls/ShellNewItem.cs index abd6c6cc..223923b1 100644 --- a/ContextMenuManager/Controls/ShellNewItem.cs +++ b/ContextMenuManager/Controls/ShellNewItem.cs @@ -83,21 +83,21 @@ public string ItemFilePath get { string filePath = FileExtension.GetExtentionInfo(FileExtension.AssocStr.Executable, Extension); - if (File.Exists(filePath)) return filePath; - using (RegistryKey oKey = RegistryEx.GetRegistryKey(OpenModePath)) + if(File.Exists(filePath)) return filePath; + using(RegistryKey oKey = RegistryEx.GetRegistryKey(OpenModePath)) { - using (RegistryKey aKey = oKey.OpenSubKey("Application")) + using(RegistryKey aKey = oKey.OpenSubKey("Application")) { string uwp = aKey?.GetValue("AppUserModelID")?.ToString(); - if (uwp != null) return "shell:AppsFolder\\" + uwp; + if(uwp != null) return "shell:AppsFolder\\" + uwp; } - using (RegistryKey cKey = oKey.OpenSubKey("CLSID")) + using(RegistryKey cKey = oKey.OpenSubKey("CLSID")) { string value = cKey?.GetValue("")?.ToString(); - if (GuidEx.TryParse(value, out Guid guid)) + if(GuidEx.TryParse(value, out Guid guid)) { filePath = GuidInfo.GetFilePath(guid); - if (filePath != null) return filePath; + if(filePath != null) return filePath; } } } @@ -120,16 +120,16 @@ public string ItemText get { string name = Registry.GetValue(RegPath, "MenuText", null)?.ToString(); - if (name != null && name.StartsWith("@")) + if(name!=null&&name.StartsWith("@")) { name = ResourceString.GetDirectString(name); - if (!string.IsNullOrEmpty(name)) return name; + if(!string.IsNullOrEmpty(name)) return name; } name = Registry.GetValue(DefaultOpenModePath, "FriendlyTypeName", null)?.ToString(); name = ResourceString.GetDirectString(name); - if (!string.IsNullOrEmpty(name)) return name; + if(!string.IsNullOrEmpty(name)) return name; name = Registry.GetValue(DefaultOpenModePath, "", null)?.ToString(); - if (!string.IsNullOrEmpty(name)) return name; + if(!string.IsNullOrEmpty(name)) return name; return null; } set @@ -145,9 +145,9 @@ public string IconLocation get { string value = Registry.GetValue(RegPath, "IconPath", null)?.ToString(); - if (!value.IsNullOrWhiteSpace()) return value; + if(!value.IsNullOrWhiteSpace()) return value; value = Registry.GetValue($@"{OpenModePath}\DefaultIcon", "", null)?.ToString(); - if (!value.IsNullOrWhiteSpace()) return value; + if(!value.IsNullOrWhiteSpace()) return value; return ItemFilePath; } set => Registry.SetValue(RegPath, "IconPath", value); @@ -158,12 +158,12 @@ public Icon ItemIcon get { string location = IconLocation; - if (location == null || location.StartsWith("@")) + if(location == null || location.StartsWith("@")) { return ResourceIcon.GetExtensionIcon(Extension); - } + } Icon icon = ResourceIcon.GetIcon(location, out string path, out int index); - if (icon == null) icon = ResourceIcon.GetIcon(path = "imageres.dll", index = -2); + if(icon == null) icon = ResourceIcon.GetIcon(path = "imageres.dll", index = -2); IconPath = path; IconIndex = index; return icon; } @@ -183,9 +183,9 @@ public string ItemCommand get => Registry.GetValue(RegPath, "Command", null)?.ToString(); set { - if (value.IsNullOrWhiteSpace()) + if(value.IsNullOrWhiteSpace()) { - if (Registry.GetValue(RegPath, "NullFile", null) != null) + if(Registry.GetValue(RegPath, "NullFile", null) != null) { RegistryEx.DeleteValue(RegPath, "Command"); } @@ -201,22 +201,22 @@ public bool BeforeSeparator { get { - if (DefaultBeforeSeparator) return true; + if(DefaultBeforeSeparator) return true; else return Registry.GetValue($@"{RegPath}\Config", "BeforeSeparator", null) != null; } set { - if (value) + if(value) { Registry.SetValue($@"{RegPath}\Config", "BeforeSeparator", ""); } else { - using (RegistryKey snkey = RegistryEx.GetRegistryKey(RegPath, true)) - using (RegistryKey ckey = snkey.OpenSubKey("Config", true)) + using(RegistryKey snkey = RegistryEx.GetRegistryKey(RegPath, true)) + using(RegistryKey ckey = snkey.OpenSubKey("Config", true)) { ckey.DeleteValue("BeforeSeparator"); - if (ckey.GetValueNames().Length == 0 && ckey.GetSubKeyNames().Length == 0) + if(ckey.GetValueNames().Length == 0 && ckey.GetSubKeyNames().Length == 0) { snkey.DeleteSubKey("Config"); } @@ -287,15 +287,15 @@ private void InitializeComponents() private void EditInitialData() { - if (AppMessageBox.Show(AppString.Message.EditInitialData, + if(AppMessageBox.Show(AppString.Message.EditInitialData, MessageBoxButtons.YesNo) != DialogResult.Yes) return; - using (InputDialog dlg = new InputDialog + using(InputDialog dlg = new InputDialog { Title = AppString.Menu.InitialData, Text = InitialData?.ToString() }) { - if (dlg.ShowDialog() == DialogResult.OK) InitialData = dlg.Text; + if(dlg.ShowDialog() == DialogResult.OK) InitialData = dlg.Text; } } @@ -310,7 +310,7 @@ private void MoveWithSeparator(bool isBefore) ShellNewList list = (ShellNewList)Parent; int index = list.GetItemIndex(list.Separator); list.SetItemIndex(this, index); - if (ShellNewList.ShellNewLockItem.IsLocked) list.SaveSorting(); + if(ShellNewList.ShellNewLockItem.IsLocked) list.SaveSorting(); } public void DeleteMe() @@ -318,7 +318,7 @@ public void DeleteMe() RegistryEx.DeleteKeyTree(RegPath); RegistryEx.DeleteKeyTree(BackupPath); Parent.Controls.Remove(this); - if (ShellNewList.ShellNewLockItem.IsLocked) Owner?.SaveSorting(); + if(ShellNewList.ShellNewLockItem.IsLocked) Owner?.SaveSorting(); } } } \ No newline at end of file diff --git a/ContextMenuManager/Controls/ShellNewList.cs b/ContextMenuManager/Controls/ShellNewList.cs index e23cc2b8..37cdfa8b 100644 --- a/ContextMenuManager/Controls/ShellNewList.cs +++ b/ContextMenuManager/Controls/ShellNewList.cs @@ -53,7 +53,7 @@ public void LoadItems() #endif Separator = new ShellNewSeparator(); AddItem(Separator); - if (ShellNewLockItem.IsLocked) LoadLockItems(); + if(ShellNewLockItem.IsLocked) LoadLockItems(); else LoadUnlockItems(); } @@ -70,10 +70,10 @@ private void LoadUnlockItems() } #endif List extensions = new List { "Folder" };//文件夹 - using (RegistryKey root = Registry.ClassesRoot) + using(RegistryKey root = Registry.ClassesRoot) { extensions.AddRange(Array.FindAll(root.GetSubKeyNames(), keyName => keyName.StartsWith("."))); - if (WinOsVersion.Current < WinOsVersion.Win10) extensions.Add("Briefcase");//公文包(Win10没有) + if(WinOsVersion.Current < WinOsVersion.Win10) extensions.Add("Briefcase");//公文包(Win10没有) LoadItems(extensions); } } @@ -101,37 +101,37 @@ private void LoadItems(List extensions) #endif foreach (string extension in ShellNewItem.UnableSortExtensions) { - if (extensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) + if(extensions.Contains(extension, StringComparer.OrdinalIgnoreCase)) { extensions.Remove(extension); extensions.Insert(0, extension); } } - using (RegistryKey root = Registry.ClassesRoot) + using(RegistryKey root = Registry.ClassesRoot) { foreach (string extension in extensions) { - using (RegistryKey extKey = root.OpenSubKey(extension)) + using(RegistryKey extKey = root.OpenSubKey(extension)) { string defalutOpenMode = extKey?.GetValue("")?.ToString(); - if (string.IsNullOrEmpty(defalutOpenMode) || defalutOpenMode.Length > 255) continue; - using (RegistryKey openModeKey = root.OpenSubKey(defalutOpenMode)) + if(string.IsNullOrEmpty(defalutOpenMode) || defalutOpenMode.Length > 255) continue; + using(RegistryKey openModeKey = root.OpenSubKey(defalutOpenMode)) { - if (openModeKey == null) continue; + if(openModeKey == null) continue; string value1 = openModeKey.GetValue("FriendlyTypeName")?.ToString(); string value2 = openModeKey.GetValue("")?.ToString(); value1 = ResourceString.GetDirectString(value1); - if (value1.IsNullOrWhiteSpace() && value2.IsNullOrWhiteSpace()) continue; + if(value1.IsNullOrWhiteSpace() && value2.IsNullOrWhiteSpace()) continue; } - using (RegistryKey tKey = extKey.OpenSubKey(defalutOpenMode)) + using(RegistryKey tKey = extKey.OpenSubKey(defalutOpenMode)) { - foreach (string part in ShellNewItem.SnParts) + foreach(string part in ShellNewItem.SnParts) { string snPart = part; - if (tKey != null) snPart = $@"{defalutOpenMode}\{snPart}"; - using (RegistryKey snKey = extKey.OpenSubKey(snPart)) + if(tKey != null) snPart = $@"{defalutOpenMode}\{snPart}"; + using(RegistryKey snKey = extKey.OpenSubKey(snPart)) { - if (ShellNewItem.EffectValueNames.Any(valueName => snKey?.GetValue(valueName) != null)) + if(ShellNewItem.EffectValueNames.Any(valueName => snKey?.GetValue(valueName) != null)) { ShellNewItem item = new ShellNewItem(snKey.Name, this); #if DEBUG @@ -171,9 +171,9 @@ public void MoveItem(ShellNewItem shellNewItem, bool isUp) { int index = GetItemIndex(shellNewItem); index += isUp ? -1 : 1; - if (index == Controls.Count) return; + if(index == Controls.Count) return; Control ctr = Controls[index]; - if (ctr is ShellNewItem item && item.CanSort) + if(ctr is ShellNewItem item && item.CanSort) { SetItemIndex(shellNewItem, index); SaveSorting(); @@ -183,9 +183,9 @@ public void MoveItem(ShellNewItem shellNewItem, bool isUp) public void SaveSorting() { List extensions = new List(); - for (int i = 2; i < Controls.Count; i++) + for(int i = 2; i < Controls.Count; i++) { - if (Controls[i] is ShellNewItem item) + if(Controls[i] is ShellNewItem item) { extensions.Add(item.Extension); } @@ -201,26 +201,26 @@ private void AddNewItem() AddItem(newItem); newItem.AddNewItem += () => { - using (FileExtensionDialog dlg = new FileExtensionDialog()) + using(FileExtensionDialog dlg = new FileExtensionDialog()) { - if (dlg.ShowDialog() != DialogResult.OK) return; + if(dlg.ShowDialog() != DialogResult.OK) return; string extension = dlg.Extension; - if (extension == ".") return; + if(extension == ".") return; string openMode = FileExtension.GetOpenMode(extension); - if (string.IsNullOrEmpty(openMode)) + if(string.IsNullOrEmpty(openMode)) { - if (AppMessageBox.Show(AppString.Message.NoOpenModeExtension, + if(AppMessageBox.Show(AppString.Message.NoOpenModeExtension, MessageBoxButtons.OKCancel) == DialogResult.OK) { ExternalProgram.ShowOpenWithDialog(extension); } return; } - foreach (Control ctr in Controls) + foreach(Control ctr in Controls) { - if (ctr is ShellNewItem item) + if(ctr is ShellNewItem item) { - if (item.Extension.Equals(extension, StringComparison.OrdinalIgnoreCase)) + if(item.Extension.Equals(extension, StringComparison.OrdinalIgnoreCase)) { AppMessageBox.Show(AppString.Message.HasBeenAdded); return; @@ -228,25 +228,25 @@ private void AddNewItem() } } - using (RegistryKey root = Registry.ClassesRoot) - using (RegistryKey exKey = root.OpenSubKey(extension, true)) - using (RegistryKey snKey = exKey.CreateSubKey("ShellNew", true)) + using(RegistryKey root = Registry.ClassesRoot) + using(RegistryKey exKey = root.OpenSubKey(extension, true)) + using(RegistryKey snKey = exKey.CreateSubKey("ShellNew", true)) { string defaultOpenMode = exKey.GetValue("")?.ToString(); - if (string.IsNullOrEmpty(defaultOpenMode)) exKey.SetValue("", openMode); + if(string.IsNullOrEmpty(defaultOpenMode)) exKey.SetValue("", openMode); byte[] bytes = GetWebShellNewData(extension); - if (bytes != null) snKey.SetValue("Data", bytes, RegistryValueKind.Binary); + if(bytes != null) snKey.SetValue("Data", bytes, RegistryValueKind.Binary); else snKey.SetValue("NullFile", "", RegistryValueKind.String); ShellNewItem item = new ShellNewItem(snKey.Name, this); AddItem(item); item.Focus(); - if (item.ItemText.IsNullOrWhiteSpace()) + if(item.ItemText.IsNullOrWhiteSpace()) { item.ItemText = FileExtension.GetExtentionInfo(FileExtension.AssocStr.FriendlyDocName, extension); } - if (ShellNewLockItem.IsLocked) SaveSorting(); + if(ShellNewLockItem.IsLocked) SaveSorting(); } } }; @@ -255,15 +255,15 @@ private void AddNewItem() private static byte[] GetWebShellNewData(string extension) { string apiUrl = AppConfig.RequestUseGithub ? AppConfig.GithubShellNewApi : AppConfig.GiteeShellNewApi; - using (UAWebClient client = new UAWebClient()) + using(UAWebClient client = new UAWebClient()) { XmlDocument doc = client.GetWebJsonToXml(apiUrl); - if (doc == null) return null; - foreach (XmlNode node in doc.FirstChild.ChildNodes) + if(doc == null) return null; + foreach(XmlNode node in doc.FirstChild.ChildNodes) { XmlNode nameXN = node.SelectSingleNode("name"); string str = Path.GetExtension(nameXN.InnerText); - if (string.Equals(str, extension, StringComparison.OrdinalIgnoreCase)) + if(string.Equals(str, extension, StringComparison.OrdinalIgnoreCase)) { try { @@ -305,11 +305,11 @@ public bool ItemVisible // 锁定新建菜单是否锁定 get => IsLocked; set { - if (value) Owner.SaveSorting(); + if(value) Owner.SaveSorting(); else UnLock(); - foreach (Control ctr in Owner.Controls) + foreach(Control ctr in Owner.Controls) { - if (ctr is ShellNewItem item) + if(ctr is ShellNewItem item) { item.SetSortabled(value); } @@ -325,14 +325,14 @@ public static bool IsLocked { get { - using (RegistryKey key = RegistryEx.GetRegistryKey(ShellNewPath)) + using(RegistryKey key = RegistryEx.GetRegistryKey(ShellNewPath)) { RegistrySecurity rs = key.GetAccessControl(); - foreach (RegistryAccessRule rar in rs.GetAccessRules(true, true, typeof(NTAccount))) + foreach(RegistryAccessRule rar in rs.GetAccessRules(true, true, typeof(NTAccount))) { - if (rar.AccessControlType.ToString().Equals("Deny", StringComparison.OrdinalIgnoreCase)) + if(rar.AccessControlType.ToString().Equals("Deny", StringComparison.OrdinalIgnoreCase)) { - if (rar.IdentityReference.ToString().Equals("Everyone", StringComparison.OrdinalIgnoreCase)) return true; + if(rar.IdentityReference.ToString().Equals("Everyone", StringComparison.OrdinalIgnoreCase)) return true; } } } @@ -342,7 +342,7 @@ public static bool IsLocked public static void Lock() { - using (RegistryKey key = RegistryEx.GetRegistryKey(ShellNewPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions)) + using(RegistryKey key = RegistryEx.GetRegistryKey(ShellNewPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions)) { RegistrySecurity rs = new RegistrySecurity(); RegistryAccessRule rar = new RegistryAccessRule("Everyone", RegistryRights.Delete | RegistryRights.WriteKey, AccessControlType.Deny); @@ -353,14 +353,14 @@ public static void Lock() public static void UnLock() { - using (RegistryKey key = RegistryEx.GetRegistryKey(ShellNewPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions)) + using(RegistryKey key = RegistryEx.GetRegistryKey(ShellNewPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions)) { RegistrySecurity rs = key.GetAccessControl(); - foreach (RegistryAccessRule rar in rs.GetAccessRules(true, true, typeof(NTAccount))) + foreach(RegistryAccessRule rar in rs.GetAccessRules(true, true, typeof(NTAccount))) { - if (rar.AccessControlType.ToString().Equals("Deny", StringComparison.OrdinalIgnoreCase)) + if(rar.AccessControlType.ToString().Equals("Deny", StringComparison.OrdinalIgnoreCase)) { - if (rar.IdentityReference.ToString().Equals("Everyone", StringComparison.OrdinalIgnoreCase)) + if(rar.IdentityReference.ToString().Equals("Everyone", StringComparison.OrdinalIgnoreCase)) { rs.RemoveAccessRule(rar); } diff --git a/ContextMenuManager/Controls/ShellStoreDialog.cs b/ContextMenuManager/Controls/ShellStoreDialog.cs index 5c6e1685..777806bb 100644 --- a/ContextMenuManager/Controls/ShellStoreDialog.cs +++ b/ContextMenuManager/Controls/ShellStoreDialog.cs @@ -19,11 +19,11 @@ public override void Reset() { } protected override bool RunDialog(IntPtr hwndOwner) { - using (ShellStoreForm frm = new ShellStoreForm(ShellPath, Filter, IsReference)) + using(ShellStoreForm frm = new ShellStoreForm(ShellPath, Filter, IsReference)) { frm.TopMost = true; bool flag = frm.ShowDialog() == DialogResult.OK; - if (flag) SelectedKeyNames = frm.SelectedKeyNames; + if(flag) SelectedKeyNames = frm.SelectedKeyNames; return flag; } } @@ -52,7 +52,7 @@ public ShellStoreForm(string shellPath, Func filter, bool isRefere chkSelectAll.Click += (sender, e) => { bool flag = chkSelectAll.Checked; - foreach (StoreShellItem item in list.Controls) + foreach(StoreShellItem item in list.Controls) { item.IsSelected = flag; } @@ -68,7 +68,7 @@ public ShellStoreForm(string shellPath, Func filter, bool isRefere readonly MyListBox listBox = new MyListBox(); readonly Panel pnlBorder = new Panel { - BackColor = MyMainForm.FormFore + BackColor = DarkModeHelper.FormFore // 修改这里 }; readonly Button btnOK = new Button { @@ -116,18 +116,18 @@ protected override void OnResize(EventArgs e) private void LoadItems(bool isReference) { - using (var shellKey = RegistryEx.GetRegistryKey(ShellPath)) + using(var shellKey = RegistryEx.GetRegistryKey(ShellPath)) { - foreach (string itemName in shellKey.GetSubKeyNames()) + foreach(string itemName in shellKey.GetSubKeyNames()) { - if (Filter != null && !Filter(itemName)) continue; + if(Filter != null && !Filter(itemName)) continue; string regPath = $@"{ShellPath}\{itemName}"; StoreShellItem item = new StoreShellItem(regPath, isReference); item.SelectedChanged += () => { - foreach (StoreShellItem shellItem in list.Controls) + foreach(StoreShellItem shellItem in list.Controls) { - if (!shellItem.IsSelected) + if(!shellItem.IsSelected) { chkSelectAll.Checked = false; return; @@ -143,8 +143,8 @@ private void LoadItems(bool isReference) private void GetSelectedItems() { List names = new List(); - foreach (StoreShellItem item in list.Controls) - if (item.IsSelected) names.Add(item.KeyName); + foreach(StoreShellItem item in list.Controls) + if(item.IsSelected) names.Add(item.KeyName); SelectedKeyNames = names.ToArray(); } } @@ -155,7 +155,7 @@ sealed class StoreShellItem : ShellItem public StoreShellItem(string regPath, bool isPublic, bool isSelect = true) : base(regPath) { IsPublic = isPublic; - if (isSelect) + if(isSelect) { ContextMenuStrip = null; AddCtr(chkSelected); @@ -183,7 +183,7 @@ public bool IsSelected public override void DeleteMe() { - if (IsPublic && AppMessageBox.Show(AppString.Message.ConfirmDeleteReferenced, + if(IsPublic && AppMessageBox.Show(AppString.Message.ConfirmDeleteReferenced, MessageBoxButtons.YesNo) != DialogResult.Yes) return; base.DeleteMe(); } diff --git a/ContextMenuManager/Controls/ShellSubMenuDialog.cs b/ContextMenuManager/Controls/ShellSubMenuDialog.cs index acad9aa2..afc6fd0b 100644 --- a/ContextMenuManager/Controls/ShellSubMenuDialog.cs +++ b/ContextMenuManager/Controls/ShellSubMenuDialog.cs @@ -22,31 +22,31 @@ protected override bool RunDialog(IntPtr hwndOwner) { bool isPublic = true; string value = Microsoft.Win32.Registry.GetValue(ParentPath, "SubCommands", null)?.ToString(); - if (value == null) isPublic = false; - else if (value.IsNullOrWhiteSpace()) + if(value == null) isPublic = false; + else if(value.IsNullOrWhiteSpace()) { - using (var shellKey = RegistryEx.GetRegistryKey($@"{ParentPath}\shell")) + using(var shellKey = RegistryEx.GetRegistryKey($@"{ParentPath}\shell")) { - if (shellKey != null && shellKey.GetSubKeyNames().Length > 0) isPublic = false; + if(shellKey != null && shellKey.GetSubKeyNames().Length > 0) isPublic = false; else { string[] modes = new[] { ResourceString.Cancel, AppString.Dialog.Private, AppString.Dialog.Public }; string mode = MessageBoxEx.Show(AppString.Message.SelectSubMenuMode, AppString.General.AppName, modes, MessageBoxImage.Question, null, modes[1]); - if (mode == modes[2]) isPublic = true; - else if (mode == modes[1]) isPublic = false; + if(mode == modes[2]) isPublic = true; + else if(mode == modes[1]) isPublic = false; else return false; } } } - using (SubItemsForm frm = new SubItemsForm()) + using(SubItemsForm frm = new SubItemsForm()) { frm.Text = Text; frm.Icon = Icon; frm.TopMost = true; - if (isPublic) + if(isPublic) { frm.Text += $"({AppString.Dialog.Public})"; PulicMultiItemsList list = new PulicMultiItemsList(); @@ -90,15 +90,15 @@ public void LoadItems() Array.ForEach(value.Split(';'), cmd => SubKeyNames.Add(cmd.TrimStart())); SubKeyNames.RemoveAll(string.IsNullOrEmpty); - using (var shellKey = RegistryEx.GetRegistryKey(ShellItem.CommandStorePath, false, true)) + using(var shellKey = RegistryEx.GetRegistryKey(ShellItem.CommandStorePath, false, true)) { - foreach (string keyName in SubKeyNames) + foreach(string keyName in SubKeyNames) { - using (var key = shellKey.OpenSubKey(keyName)) + using(var key = shellKey.OpenSubKey(keyName)) { MyListItem item; - if (key != null) item = new SubShellItem(this, keyName); - else if (keyName == "|") item = new SeparatorItem(this); + if(key != null) item = new SubShellItem(this, keyName); + else if(keyName == "|") item = new SeparatorItem(this); else item = new InvalidItem(this, keyName); AddItem(item); } @@ -108,12 +108,12 @@ public void LoadItems() private void AddNewItem() { - if (!SubShellTypeItem.CanAddMore(this)) return; - using (NewShellDialog dlg = new NewShellDialog()) + if(!SubShellTypeItem.CanAddMore(this)) return; + using(NewShellDialog dlg = new NewShellDialog()) { dlg.ScenePath = ScenePath; dlg.ShellPath = ShellItem.CommandStorePath; - if (dlg.ShowDialog() != DialogResult.OK) return; + if(dlg.ShowDialog() != DialogResult.OK) return; SubKeyNames.Add(dlg.NewItemKeyName); SaveSorting(); AddItem(new SubShellItem(this, dlg.NewItemKeyName)); @@ -122,17 +122,17 @@ private void AddNewItem() private void AddReference() { - if (!SubShellTypeItem.CanAddMore(this)) return; - using (ShellStoreDialog dlg = new ShellStoreDialog()) + if(!SubShellTypeItem.CanAddMore(this)) return; + using(ShellStoreDialog dlg = new ShellStoreDialog()) { dlg.IsReference = true; dlg.ShellPath = ShellItem.CommandStorePath; dlg.Filter = new Func(itemName => !(AppConfig.HideSysStoreItems && itemName.StartsWith("Windows.", StringComparison.OrdinalIgnoreCase))); - if (dlg.ShowDialog() != DialogResult.OK) return; - foreach (string keyName in dlg.SelectedKeyNames) + if(dlg.ShowDialog() != DialogResult.OK) return; + foreach(string keyName in dlg.SelectedKeyNames) { - if (!SubShellTypeItem.CanAddMore(this)) return; + if(!SubShellTypeItem.CanAddMore(this)) return; AddItem(new SubShellItem(this, keyName)); SubKeyNames.Add(keyName); SaveSorting(); @@ -142,7 +142,7 @@ private void AddReference() private void AddSeparator() { - if (Controls[Controls.Count - 1] is SeparatorItem) return; + if(Controls[Controls.Count - 1] is SeparatorItem) return; SubKeyNames.Add("|"); SaveSorting(); AddItem(new SeparatorItem(this)); @@ -156,9 +156,9 @@ private void SaveSorting() private void MoveItem(MyListItem item, bool isUp) { int index = GetItemIndex(item); - if (isUp) + if(isUp) { - if (index > 1) + if(index > 1) { SetItemIndex(item, index - 1); SubKeyNames.Reverse(index - 2, 2); @@ -166,7 +166,7 @@ private void MoveItem(MyListItem item, bool isUp) } else { - if (index < Controls.Count - 1) + if(index < Controls.Count - 1) { SetItemIndex(item, index + 1); SubKeyNames.Reverse(index - 1, 2); @@ -179,7 +179,7 @@ private void DeleteItem(MyListItem item) { int index = GetItemIndex(item); SubKeyNames.RemoveAt(index - 1); - if (index == Controls.Count - 1) index--; + if(index == Controls.Count - 1) index--; Controls.Remove(item); Controls[index].Focus(); SaveSorting(); @@ -203,7 +203,7 @@ public SubShellItem(PulicMultiItemsList list, string keyName) : base($@"{Command private void DeleteReference() { - if (AppMessageBox.Show(AppString.Message.ConfirmDeleteReference, MessageBoxButtons.YesNo) == DialogResult.Yes) + if(AppMessageBox.Show(AppString.Message.ConfirmDeleteReference, MessageBoxButtons.YesNo) == DialogResult.Yes) { Owner.DeleteItem(this); } @@ -278,7 +278,7 @@ public void LoadItems() subNewItem.AddExisting += () => AddFromParentMenu(); string sckValue = Microsoft.Win32.Registry.GetValue(ParentPath, "ExtendedSubCommandsKey", null)?.ToString(); - if (!sckValue.IsNullOrWhiteSpace()) + if(!sckValue.IsNullOrWhiteSpace()) { ShellPath = $@"{RegistryEx.CLASSES_ROOT}\{sckValue}\shell"; } @@ -286,15 +286,15 @@ public void LoadItems() { ShellPath = $@"{ParentPath}\shell"; } - using (var shellKey = RegistryEx.GetRegistryKey(ShellPath)) + using(var shellKey = RegistryEx.GetRegistryKey(ShellPath)) { - if (shellKey == null) return; + if(shellKey == null) return; RegTrustedInstaller.TakeRegTreeOwnerShip(shellKey.Name); - foreach (string keyName in shellKey.GetSubKeyNames()) + foreach(string keyName in shellKey.GetSubKeyNames()) { string regPath = $@"{ShellPath}\{keyName}"; int value = Convert.ToInt32(Microsoft.Win32.Registry.GetValue(regPath, "CommandFlags", 0)); - if (value % 16 >= 8) + if(value % 16 >= 8) { AddItem(new SeparatorItem(this, regPath)); } @@ -308,23 +308,23 @@ public void LoadItems() private void AddNewItem() { - if (!SubShellTypeItem.CanAddMore(this)) return; - using (NewShellDialog dlg = new NewShellDialog + if(!SubShellTypeItem.CanAddMore(this)) return; + using(NewShellDialog dlg = new NewShellDialog { ScenePath = ScenePath, ShellPath = ShellPath }) { - if (dlg.ShowDialog() != DialogResult.OK) return; + if(dlg.ShowDialog() != DialogResult.OK) return; AddItem(new SubShellItem(this, dlg.NewItemRegPath)); } } private void AddSeparator() { - if (Controls[Controls.Count - 1] is SeparatorItem) return; + if(Controls[Controls.Count - 1] is SeparatorItem) return; string regPath; - if (Controls.Count > 1) + if(Controls.Count > 1) { regPath = GetItemRegPath((MyListItem)Controls[Controls.Count - 1]); } @@ -339,16 +339,16 @@ private void AddSeparator() private void AddFromParentMenu() { - if (!SubShellTypeItem.CanAddMore(this)) return; - using (ShellStoreDialog dlg = new ShellStoreDialog()) + if(!SubShellTypeItem.CanAddMore(this)) return; + using(ShellStoreDialog dlg = new ShellStoreDialog()) { dlg.IsReference = false; dlg.ShellPath = ParentShellPath; dlg.Filter = new Func(itemName => !itemName.Equals(ParentKeyName, StringComparison.OrdinalIgnoreCase)); - if (dlg.ShowDialog() != DialogResult.OK) return; - foreach (string keyName in dlg.SelectedKeyNames) + if(dlg.ShowDialog() != DialogResult.OK) return; + foreach(string keyName in dlg.SelectedKeyNames) { - if (!SubShellTypeItem.CanAddMore(this)) return; + if(!SubShellTypeItem.CanAddMore(this)) return; string srcPath = $@"{dlg.ShellPath}\{keyName}"; string dstPath = ObjectPath.GetNewPathWithIndex($@"{ShellPath}\{keyName}", ObjectPath.PathType.Registry); @@ -362,9 +362,9 @@ public void MoveItem(MyListItem item, bool isUp) { int index = GetItemIndex(item); MyListItem otherItem = null; - if (isUp) + if(isUp) { - if (index > 1) + if(index > 1) { otherItem = (MyListItem)Controls[index - 1]; SetItemIndex(item, index - 1); @@ -372,13 +372,13 @@ public void MoveItem(MyListItem item, bool isUp) } else { - if (index < Controls.Count - 1) + if(index < Controls.Count - 1) { otherItem = (MyListItem)Controls[index + 1]; SetItemIndex(item, index + 1); } } - if (otherItem != null) + if(otherItem != null) { string path1 = GetItemRegPath(item); string path2 = GetItemRegPath(otherItem); @@ -417,17 +417,17 @@ public SubShellItem(PrivateMultiItemsList list, string regPath) : base(regPath) private void SetItemTextValue() { - using (var key = RegistryEx.GetRegistryKey(RegPath, true)) + using(var key = RegistryEx.GetRegistryKey(RegPath, true)) { bool hasValue = false; - foreach (string valueName in new[] { "MUIVerb", "" }) + foreach(string valueName in new[] { "MUIVerb", "" }) { - if (key.GetValue(valueName) != null) + if(key.GetValue(valueName) != null) { hasValue = true; break; } } - if (!hasValue) key.SetValue("MUIVerb", ItemText); + if(!hasValue) key.SetValue("MUIVerb", ItemText); } } @@ -450,7 +450,7 @@ public override void DeleteMe() { RegistryEx.DeleteKeyTree(RegPath); int index = Parent.Controls.GetChildIndex(this); - if (index == Parent.Controls.Count - 1) index--; + if(index == Parent.Controls.Count - 1) index--; Parent.Controls[index].Focus(); Parent.Controls.Remove(this); Dispose(); @@ -495,12 +495,12 @@ public SubShellTypeItem(string regPath) : base(regPath) public static bool CanAddMore(MyList list) { int count = 0; - foreach (Control item in list.Controls) + foreach(Control item in list.Controls) { - if (item.GetType().BaseType == typeof(SubShellTypeItem)) count++; + if(item.GetType().BaseType == typeof(SubShellTypeItem)) count++; } bool flag = count < 16; - if (!flag) AppMessageBox.Show(AppString.Message.CannotAddNewItem); + if(!flag) AppMessageBox.Show(AppString.Message.CannotAddNewItem); return flag; } } diff --git a/ContextMenuManager/Controls/SubItemsForm.cs b/ContextMenuManager/Controls/SubItemsForm.cs index d682d68a..d2a53c16 100644 --- a/ContextMenuManager/Controls/SubItemsForm.cs +++ b/ContextMenuManager/Controls/SubItemsForm.cs @@ -1,43 +1,43 @@ -using BluePointLilac.Controls; -using BluePointLilac.Methods; -using ContextMenuManager.Methods; -using System.Drawing; -using System.Windows.Forms; - -namespace ContextMenuManager.Controls -{ - sealed class SubItemsForm : RForm - { - public SubItemsForm() - { - SuspendLayout(); - StartPosition = FormStartPosition.CenterParent; - ShowInTaskbar = MaximizeBox = MinimizeBox = false; - MinimumSize = Size = new Size(646, 419).DpiZoom(); - Controls.AddRange(new Control[] { listBox, statusBar }); - statusBar.CanMoveForm(); - this.AddEscapeButton(); - ResumeLayout(); - InitTheme(); - } - - readonly MyListBox listBox = new MyListBox { Dock = DockStyle.Fill }; - readonly MyStatusBar statusBar = new MyStatusBar(); - - public void AddList(MyList myList) - { - myList.Owner = listBox; - myList.HoveredItemChanged += (sender, e) => - { - if (!AppConfig.ShowFilePath) return; - MyListItem item = myList.HoveredItem; - foreach (string prop in new[] { "ItemFilePath", "RegPath", "GroupPath" }) - { - string path = item.GetType().GetProperty(prop)?.GetValue(item, null)?.ToString(); - if (!path.IsNullOrWhiteSpace()) { statusBar.Text = path; return; } - } - statusBar.Text = item.Text; - }; - } - } +using BluePointLilac.Controls; +using BluePointLilac.Methods; +using ContextMenuManager.Methods; +using System.Drawing; +using System.Windows.Forms; + +namespace ContextMenuManager.Controls +{ + sealed class SubItemsForm : RForm + { + public SubItemsForm() + { + SuspendLayout(); + StartPosition = FormStartPosition.CenterParent; + ShowInTaskbar = MaximizeBox = MinimizeBox = false; + MinimumSize = Size = new Size(646, 419).DpiZoom(); + Controls.AddRange(new Control[] { listBox, statusBar }); + statusBar.CanMoveForm(); + this.AddEscapeButton(); + ResumeLayout(); + InitTheme(); + } + + readonly MyListBox listBox = new MyListBox { Dock = DockStyle.Fill }; + readonly MyStatusBar statusBar = new MyStatusBar(); + + public void AddList(MyList myList) + { + myList.Owner = listBox; + myList.HoveredItemChanged += (sender, e) => + { + if(!AppConfig.ShowFilePath) return; + MyListItem item = myList.HoveredItem; + foreach(string prop in new[] { "ItemFilePath", "RegPath", "GroupPath" }) + { + string path = item.GetType().GetProperty(prop)?.GetValue(item, null)?.ToString(); + if(!path.IsNullOrWhiteSpace()) { statusBar.Text = path; return; } + } + statusBar.Text = item.Text; + }; + } + } } \ No newline at end of file diff --git a/ContextMenuManager/Controls/SwitchDicList.cs b/ContextMenuManager/Controls/SwitchDicList.cs index 70bdc08f..18923398 100644 --- a/ContextMenuManager/Controls/SwitchDicList.cs +++ b/ContextMenuManager/Controls/SwitchDicList.cs @@ -51,12 +51,12 @@ public bool UseUserDic get => useUserDic == true; set { - if (useUserDic == value) return; + if(useUserDic == value) return; bool flag = useUserDic == null; useUserDic = value; Image = UseUserDic ? AppImage.User : AppImage.Web; cmbDic.SelectedIndex = value ? 1 : 0; - if (!flag) UseDicChanged?.Invoke(); + if(!flag) UseDicChanged?.Invoke(); } } diff --git a/ContextMenuManager/Controls/UwpModeItem.cs b/ContextMenuManager/Controls/UwpModeItem.cs index 2af142c2..53fb453b 100644 --- a/ContextMenuManager/Controls/UwpModeItem.cs +++ b/ContextMenuManager/Controls/UwpModeItem.cs @@ -28,21 +28,21 @@ public bool ItemVisible // 是否显示于右键菜单中 { get { - foreach (string path in GuidBlockedList.BlockedPaths) + foreach(string path in GuidBlockedList.BlockedPaths) { - using (RegistryKey key = RegistryEx.GetRegistryKey(path)) + using(RegistryKey key = RegistryEx.GetRegistryKey(path)) { - if (key == null) continue; - if (key.GetValue(Guid.ToString("B")) != null) return false; + if(key == null) continue; + if(key.GetValue(Guid.ToString("B")) != null) return false; } } return true; } set { - foreach (string path in GuidBlockedList.BlockedPaths) + foreach(string path in GuidBlockedList.BlockedPaths) { - if (value) + if(value) { RegistryEx.DeleteValue(path, Guid.ToString("B")); } diff --git a/ContextMenuManager/Controls/WinXGroupItem.cs b/ContextMenuManager/Controls/WinXGroupItem.cs index 17a51e09..65f82854 100644 --- a/ContextMenuManager/Controls/WinXGroupItem.cs +++ b/ContextMenuManager/Controls/WinXGroupItem.cs @@ -116,7 +116,7 @@ void MoveDirectory(string oldPath, string newPath) } private readonly List winXItems = new List { }; - + public void AddWinXItem(WinXItem item) { winXItems.Add(item); @@ -195,7 +195,7 @@ void RestoreDefaultFolder(bool isWinX) public void DeleteMe() { bool flag = Directory.GetFiles(GroupPath, "*.lnk").Length > 0; - if (flag && AppMessageBox.Show(AppString.Message.DeleteGroup, MessageBoxButtons.OKCancel) != DialogResult.OK) return; + if(flag && AppMessageBox.Show(AppString.Message.DeleteGroup, MessageBoxButtons.OKCancel) != DialogResult.OK) return; DeletePath(new string[] { GroupPath, BackupGroupPath, DefaultGroupPath }); if (flag) { diff --git a/ContextMenuManager/Controls/WinXItem.cs b/ContextMenuManager/Controls/WinXItem.cs index 8461ed5d..fe3dc79d 100644 --- a/ContextMenuManager/Controls/WinXItem.cs +++ b/ContextMenuManager/Controls/WinXItem.cs @@ -54,15 +54,15 @@ public string ItemText get { string name = ShellLink.Description?.Trim(); - if (name.IsNullOrWhiteSpace()) name = DesktopIni.GetLocalizedFileNames(FilePath, true); - if (name == string.Empty) name = Path.GetFileNameWithoutExtension(FilePath); + if(name.IsNullOrWhiteSpace()) name = DesktopIni.GetLocalizedFileNames(FilePath, true); + if(name == string.Empty) name = Path.GetFileNameWithoutExtension(FilePath); return name; } set { ShellLink.Description = value; ShellLink.Save(); - + if (WinOsVersion.Current >= WinOsVersion.Win11) { DesktopIni.SetLocalizedFileNames(FilePath, value); @@ -86,8 +86,8 @@ public bool ItemVisible { get { - return (WinOsVersion.Current >= WinOsVersion.Win11) ? - FilePath.Substring(0, WinXList.WinXPath.Length).Equals(WinXList.WinXPath, StringComparison.OrdinalIgnoreCase) : + return (WinOsVersion.Current >= WinOsVersion.Win11) ? + FilePath.Substring(0, WinXList.WinXPath.Length).Equals(WinXList.WinXPath, StringComparison.OrdinalIgnoreCase) : (File.GetAttributes(FilePath) & FileAttributes.Hidden) != FileAttributes.Hidden; } set @@ -166,13 +166,13 @@ public Icon ItemIcon ShellLink.ICONLOCATION iconLocation = ShellLink.IconLocation; string iconPath = iconLocation.IconPath; int iconIndex = iconLocation.IconIndex; - if (string.IsNullOrEmpty(iconPath)) iconPath = FilePath; + if(string.IsNullOrEmpty(iconPath)) iconPath = FilePath; Icon icon = ResourceIcon.GetIcon(iconPath, iconIndex); - if (icon == null) + if(icon == null) { string path = ItemFilePath; - if (File.Exists(path)) icon = ResourceIcon.GetExtensionIcon(path); - else if (Directory.Exists(path)) icon = ResourceIcon.GetFolderIcon(path); + if(File.Exists(path)) icon = ResourceIcon.GetExtensionIcon(path); + else if(Directory.Exists(path)) icon = ResourceIcon.GetFolderIcon(path); } return icon; } @@ -183,7 +183,7 @@ public string ItemFilePath get { string path = ShellLink.TargetPath; - if (!File.Exists(path) && !Directory.Exists(path)) path = FilePath; + if(!File.Exists(path) && !Directory.Exists(path)) path = FilePath; return path; } } @@ -240,7 +240,7 @@ private void InitializeComponents() BtnMoveUp.MouseDown += (sender, e) => MoveItem(true); TsiChangeCommand.Click += (sender, e) => { - if (TsiChangeCommand.ChangeCommand(ShellLink)) + if(TsiChangeCommand.ChangeCommand(ShellLink)) { Image = ItemImage; WinXHasher.HashLnk(FilePath); @@ -274,8 +274,8 @@ void ChangeFileGroup(string selectText, bool isWinX, out string lnkPath) dlg.Title = AppString.Dialog.SelectGroup; dlg.Items = WinXList.GetGroupNames(); dlg.Selected = FoldGroupItem.Text; - if (dlg.ShowDialog() != DialogResult.OK) return; - if (dlg.Selected == FoldGroupItem.Text) return; + if(dlg.ShowDialog() != DialogResult.OK) return; + if(dlg.Selected == FoldGroupItem.Text) return; ChangeFileGroup(dlg.Selected, true, out string lnkPath); if (WinOsVersion.Current >= WinOsVersion.Win11) @@ -287,9 +287,9 @@ void ChangeFileGroup(string selectText, bool isWinX, out string lnkPath) WinXList list = (WinXList)Parent; list.Controls.Remove(this); - for (int i = 0; i < list.Controls.Count; i++) + for(int i = 0; i < list.Controls.Count; i++) { - if (list.Controls[i] is WinXGroupItem groupItem && groupItem.Text == dlg.Selected) + if(list.Controls[i] is WinXGroupItem groupItem && groupItem.Text == dlg.Selected) { list.Controls.Add(this); list.SetItemIndex(this, i + 1); @@ -308,10 +308,10 @@ private void MoveItem(bool isUp) { WinXList list = (WinXList)Parent; int index = list.Controls.GetChildIndex(this); - if (index == list.Controls.Count - 1) return; + if(index == list.Controls.Count - 1) return; index += isUp ? -1 : 1; Control ctr = list.Controls[index]; - if (ctr is WinXGroupItem) return; + if(ctr is WinXGroupItem) return; WinXItem item = (WinXItem)ctr; MoveFileItem(item, true, out string path1, out string path2); diff --git a/ContextMenuManager/Controls/WinXList.cs b/ContextMenuManager/Controls/WinXList.cs index b1c724a6..1d21bf14 100644 --- a/ContextMenuManager/Controls/WinXList.cs +++ b/ContextMenuManager/Controls/WinXList.cs @@ -19,7 +19,7 @@ sealed class WinXList : MyList // 主页 Win+X public void LoadItems() { - if (WinOsVersion.Current >= WinOsVersion.Win8) + if(WinOsVersion.Current >= WinOsVersion.Win8) { AppConfig.BackupWinX(); AddItem(new WinXSortableItem(this)); @@ -50,7 +50,7 @@ private void LoadWinXItems() // 检查WinX项目是否排序并初始化界面 bool sorted = false; - foreach (string dirKeyPath in dirKeyPaths) + foreach(string dirKeyPath in dirKeyPaths) { string dirPath1 = $@"{WinXPath}\{dirKeyPath}"; string dirPath2 = $@"{BackupWinXPath}\{dirKeyPath}"; @@ -59,17 +59,17 @@ private void LoadWinXItems() AddItem(groupItem); List lnkPaths; - if (AppConfig.WinXSortable) + if(AppConfig.WinXSortable) { lnkPaths = GetSortedPaths(dirKeyPath, out bool flag); - if (flag) sorted = true; + if(flag) sorted = true; } else { lnkPaths = GetInkFiles(dirKeyPath); } - foreach (string path in lnkPaths) + foreach(string path in lnkPaths) { WinXItem winXItem = new WinXItem(path, groupItem); winXItem.BtnMoveDown.Visible = winXItem.BtnMoveUp.Visible = AppConfig.WinXSortable; @@ -77,7 +77,7 @@ private void LoadWinXItems() groupItem.AddWinXItem(winXItem); } } - if (sorted) + if(sorted) { ExplorerRestarter.Show(); AppMessageBox.Show(AppString.Message.WinXSorted); @@ -175,7 +175,7 @@ void ResortPaths(int index, string name, string path, string lnkFilePath, bool i // 序号正确且为两位以上数字无需进行重新编号 if (index >= 2 && int.TryParse(name.Substring(0, index), out int num) && num == i + 1) { - sortedPaths.Add(lnkFilePath); i--; continue; + sortedPaths.Add(lnkFilePath); i--; continue; } // 序号不正确或数字位数不足则进行重新编号 @@ -190,7 +190,7 @@ void ResortPaths(int index, string name, string path, string lnkFilePath, bool i resorted = true; i--; } - + return sortedPaths; } @@ -204,7 +204,7 @@ private void AddNewItem() btnCreateDir.MouseDown += (sender, e) => CreateNewGroup(); newItem.AddNewItem += () => { - using (NewLnkFileDialog dlg1 = new NewLnkFileDialog()) + using(NewLnkFileDialog dlg1 = new NewLnkFileDialog()) { void AddNewLnkFile(string dirName, string itemText, string targetPath, string arguments, bool isWinX) { @@ -249,18 +249,18 @@ void AddNewLnkFile(string dirName, string itemText, string targetPath, string ar } if (dlg1.ShowDialog() != DialogResult.OK) return; - using (SelectDialog dlg2 = new SelectDialog()) + using(SelectDialog dlg2 = new SelectDialog()) { dlg2.Title = AppString.Dialog.SelectGroup; dlg2.Items = GetGroupNames(); - if (dlg2.ShowDialog() != DialogResult.OK) return; + if(dlg2.ShowDialog() != DialogResult.OK) return; AddNewLnkFile(dlg2.Selected, dlg1.ItemText, dlg1.ItemFilePath, dlg1.Arguments, true); if (WinOsVersion.Current >= WinOsVersion.Win11) { AddNewLnkFile(dlg2.Selected, dlg1.ItemText, dlg1.ItemFilePath, dlg1.Arguments, false); } - + ExplorerRestarter.Show(); } } @@ -295,7 +295,7 @@ public static string[] GetGroupNames() { List items = new List(); DirectoryInfo winxDi = new DirectoryInfo(WinXPath); - foreach (DirectoryInfo di in winxDi.GetDirectories()) items.Add(di.Name); + foreach(DirectoryInfo di in winxDi.GetDirectories()) items.Add(di.Name); items.Reverse(); return items.ToArray(); } @@ -310,9 +310,7 @@ public WinXSortableItem(WinXList list) Image = AppImage.Sort; AddCtr(chkWinXSortable); chkWinXSortable.Checked = AppConfig.WinXSortable; - chkWinXSortable.CheckChanged += () => - { - AppConfig.WinXSortable = chkWinXSortable.Checked; list.ClearItems(); list.LoadItems(); + chkWinXSortable.CheckChanged += () => { AppConfig.WinXSortable = chkWinXSortable.Checked; list.ClearItems(); list.LoadItems(); }; } } diff --git a/ContextMenuManager/MainForm.cs b/ContextMenuManager/MainForm.cs index aa638966..320c0c66 100644 --- a/ContextMenuManager/MainForm.cs +++ b/ContextMenuManager/MainForm.cs @@ -1,789 +1,730 @@ -using BluePointLilac.Controls; -using BluePointLilac.Methods; -using ContextMenuManager.Controls; -using ContextMenuManager.Methods; -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Windows.Forms; - -namespace ContextMenuManager -{ - sealed class MainForm : MyMainForm - { - public MainForm() - { - TopMost = AppConfig.TopMost; - StartPosition = FormStartPosition.CenterScreen; - Size = AppConfig.MainFormSize; - Text = AppString.General.AppName; - Controls.Add(explorerRestarter); - ToolBar.AddButtons(ToolBarButtons); - MainBody.Controls.AddRange(MainControls); - ToolBarButtons[3].CanBeSelected = false; - ToolBarButtons[3].MouseDown += (sender, e) => RefreshApp(); - ToolBar.SelectedButtonChanged += (sender, e) => SwitchTab(); - SideBar.HoverIndexChanged += (sender, e) => ShowItemInfo(); - SideBar.SelectIndexChanged += (sender, e) => SwitchItem(); - Shown += (sender, e) => FirstRunDownloadLanguage(); - FormClosing += (sender, e) => CloseMainForm(); - DragDropToAnalysis(); - AddContextMenus(); - ResizeSideBar(); - JumpItem(0, 0); - InitTheme(true); - - // 初始化搜索功能 - InitializeSearch(); - } - - readonly MyToolBarButton[] ToolBarButtons = - { - new MyToolBarButton(AppImage.Home, AppString.ToolBar.Home), - new MyToolBarButton(AppImage.Type, AppString.ToolBar.Type), - new MyToolBarButton(AppImage.Star, AppString.ToolBar.Rule), - new MyToolBarButton(AppImage.Refresh, AppString.ToolBar.Refresh), - new MyToolBarButton(AppImage.About, AppString.ToolBar.About) - }; - - private Control[] MainControls => new Control[] - { - shellList, shellNewList, sendToList, openWithList, winXList, - enhanceMenusList, detailedEditList, guidBlockedList, iEList, - appSettingBox, languagesBox, dictionariesBox, aboutMeBox, - donateBox, backupListBox - }; - - readonly ShellList shellList = new ShellList(); - readonly ShellNewList shellNewList = new ShellNewList(); - readonly SendToList sendToList = new SendToList(); - readonly OpenWithList openWithList = new OpenWithList(); - readonly WinXList winXList = new WinXList(); - - readonly EnhanceMenuList enhanceMenusList = new EnhanceMenuList(); - readonly DetailedEditList detailedEditList = new DetailedEditList(); - readonly GuidBlockedList guidBlockedList = new GuidBlockedList(); - readonly IEList iEList = new IEList(); - - readonly AppSettingBox appSettingBox = new AppSettingBox(); - readonly LanguagesBox languagesBox = new LanguagesBox(); - readonly DictionariesBox dictionariesBox = new DictionariesBox(); - readonly ReadOnlyRichTextBox aboutMeBox = new ReadOnlyRichTextBox(); - readonly DonateBox donateBox = new DonateBox(); - readonly BackupListBox backupListBox = new BackupListBox(); - readonly ExplorerRestarter explorerRestarter = new ExplorerRestarter(); - - // 主页 - static readonly string[] GeneralItems = - { - AppString.SideBar.File, - AppString.SideBar.Folder, - AppString.SideBar.Directory, - AppString.SideBar.Background, - AppString.SideBar.Desktop, - AppString.SideBar.Drive, - AppString.SideBar.AllObjects, - AppString.SideBar.Computer, - AppString.SideBar.RecycleBin, - AppString.SideBar.Library, - null, - AppString.SideBar.New, - AppString.SideBar.SendTo, - AppString.SideBar.OpenWith, - null, - AppString.SideBar.WinX - }; - static readonly string[] GeneralItemInfos = - { - AppString.StatusBar.File, - AppString.StatusBar.Folder, - AppString.StatusBar.Directory, - AppString.StatusBar.Background, - AppString.StatusBar.Desktop, - AppString.StatusBar.Drive, - AppString.StatusBar.AllObjects, - AppString.StatusBar.Computer, - AppString.StatusBar.RecycleBin, - AppString.StatusBar.Library, - null, - AppString.StatusBar.New, - AppString.StatusBar.SendTo, - AppString.StatusBar.OpenWith, - null, - AppString.StatusBar.WinX - }; - - // 文件类型 - static readonly string[] TypeItems = - { - AppString.SideBar.LnkFile, - AppString.SideBar.UwpLnk, - AppString.SideBar.ExeFile, - AppString.SideBar.UnknownType, - null, - AppString.SideBar.CustomExtension, - AppString.SideBar.PerceivedType, - AppString.SideBar.DirectoryType, - null, - AppString.SideBar.MenuAnalysis - }; - static readonly string[] TypeItemInfos = - { - AppString.StatusBar.LnkFile, - AppString.StatusBar.UwpLnk, - AppString.StatusBar.ExeFile, - AppString.StatusBar.UnknownType, - null, - AppString.StatusBar.CustomExtension, - AppString.StatusBar.PerceivedType, - AppString.StatusBar.DirectoryType, - null, - AppString.StatusBar.MenuAnalysis - }; - - // 其他规则 - static readonly string[] OtherRuleItems = - { - AppString.SideBar.EnhanceMenu, - AppString.SideBar.DetailedEdit, - null, - AppString.SideBar.DragDrop, - AppString.SideBar.PublicReferences, - AppString.SideBar.IEMenu, - null, - AppString.SideBar.GuidBlocked, - AppString.SideBar.CustomRegPath, - }; - static readonly string[] OtherRuleItemInfos = - { - AppString.StatusBar.EnhanceMenu, - AppString.StatusBar.DetailedEdit, - null, - AppString.StatusBar.DragDrop, - AppString.StatusBar.PublicReferences, - AppString.StatusBar.IEMenu, - null, - AppString.StatusBar.GuidBlocked, - AppString.StatusBar.CustomRegPath, - }; - - // 关于 - static readonly string[] AboutItems = - { - AppString.SideBar.AppSetting, - AppString.SideBar.AppLanguage, - AppString.SideBar.BackupRestore, - AppString.SideBar.Dictionaries, - AppString.SideBar.AboutApp, - AppString.SideBar.Donate, - }; - - static readonly string[] SettingItems = - { - AppString.Other.TopMost, - null, - AppString.Other.ShowFilePath, - AppString.Other.HideDisabledItems, - null, - AppString.Other.OpenMoreRegedit, - AppString.Other.OpenMoreExplorer, - }; - - static readonly Scenes[] GeneralShellScenes = - { - Scenes.File, - Scenes.Folder, - Scenes.Directory, - Scenes.Background, - Scenes.Desktop, - Scenes.Drive, - Scenes.AllObjects, - Scenes.Computer, - Scenes.RecycleBin, - Scenes.Library - }; - - static readonly Scenes?[] TypeShellScenes = - { - Scenes.LnkFile, - Scenes.UwpLnk, - Scenes.ExeFile, - Scenes.UnknownType, - null, - Scenes.CustomExtension, - Scenes.PerceivedType, - Scenes.DirectoryType, - null, - Scenes.MenuAnalysis - }; - - readonly int[] lastItemIndex = new int[5]; - - // 搜索相关变量 - private string lastSearchText = string.Empty; - private bool isSearching = false; - - public void JumpItem(int toolBarIndex, int sideBarIndex) - { - bool flag1 = ToolBar.SelectedIndex == toolBarIndex; - bool flag2 = SideBar.SelectedIndex == sideBarIndex; - lastItemIndex[toolBarIndex] = sideBarIndex; - ToolBar.SelectedIndex = toolBarIndex; - if (flag1 || flag2) - { - SideBar.SelectedIndex = sideBarIndex; - SwitchItem(); - } - } - - private void RefreshApp() - { - Cursor = Cursors.WaitCursor; - ObjectPath.FilePathDic.Clear(); - AppConfig.ReloadConfig(); - GuidInfo.ReloadDics(); - XmlDicHelper.ReloadDics(); - SwitchItem(); - Cursor = Cursors.Default; - } - - private void SwitchTab() - { - switch (ToolBar.SelectedIndex) - { - case 0: - SideBar.ItemNames = GeneralItems; break; - case 1: - SideBar.ItemNames = TypeItems; break; - case 2: - SideBar.ItemNames = OtherRuleItems; break; - case 4: - SideBar.ItemNames = AboutItems; break; - } - SideBar.SelectedIndex = lastItemIndex[ToolBar.SelectedIndex]; - } - - private void SwitchItem() - { - // 切换项目时清除搜索状态 - if (isSearching) - { - ClearSearch(); - } - - foreach (Control ctr in MainControls) - { - ctr.Visible = false; - if (ctr is MyList list) list.ClearItems(); - } - if (SideBar.SelectedIndex == -1) return; - switch (ToolBar.SelectedIndex) - { - case 0: - SwitchGeneralItem(); break; - case 1: - SwitchTypeItem(); break; - case 2: - SwitchOtherRuleItem(); break; - case 4: - SwitchAboutItem(); break; - } - lastItemIndex[ToolBar.SelectedIndex] = SideBar.SelectedIndex; - SuspendMainBodyWhenMove = MainControls.ToList().Any(ctr => ctr.Controls.Count > 50); - } - - private void ShowItemInfo() - { - if (SideBar.HoveredIndex >= 0) - { - int i = SideBar.HoveredIndex; - switch (ToolBar.SelectedIndex) - { - case 0: - StatusBar.Text = GeneralItemInfos[i]; return; - case 1: - StatusBar.Text = TypeItemInfos[i]; return; - case 2: - StatusBar.Text = OtherRuleItemInfos[i]; return; - } - } - StatusBar.Text = MyStatusBar.DefaultText; - } - - private void DragDropToAnalysis() - { - var droper = new ElevatedFileDroper(this); - droper.DragDrop += (sender, e) => - { - ShellList.CurrentFileObjectPath = droper.DropFilePaths[0]; - JumpItem(1, 9); - }; - } - - private void SwitchGeneralItem() - { - switch (SideBar.SelectedIndex) - { - case 11: - shellNewList.LoadItems(); shellNewList.Visible = true; break; - case 12: - sendToList.LoadItems(); sendToList.Visible = true; break; - case 13: - openWithList.LoadItems(); openWithList.Visible = true; break; - case 15: - winXList.LoadItems(); winXList.Visible = true; break; - default: - shellList.Scene = GeneralShellScenes[SideBar.SelectedIndex]; - shellList.LoadItems(); shellList.Visible = true; break; - } - } - - private void SwitchTypeItem() - { - shellList.Scene = (Scenes)TypeShellScenes[SideBar.SelectedIndex]; - shellList.LoadItems(); - shellList.Visible = true; - } - - private void SwitchOtherRuleItem() - { - switch (SideBar.SelectedIndex) - { - case 0: - enhanceMenusList.ScenePath = null; enhanceMenusList.LoadItems(); enhanceMenusList.Visible = true; break; - case 1: - detailedEditList.GroupGuid = Guid.Empty; detailedEditList.LoadItems(); detailedEditList.Visible = true; break; - case 3: - shellList.Scene = Scenes.DragDrop; shellList.LoadItems(); shellList.Visible = true; break; - case 4: - shellList.Scene = Scenes.PublicReferences; shellList.LoadItems(); shellList.Visible = true; break; - case 5: - iEList.LoadItems(); iEList.Visible = true; break; - case 7: - guidBlockedList.LoadItems(); guidBlockedList.Visible = true; break; - case 8: - shellList.Scene = Scenes.CustomRegPath; shellList.LoadItems(); shellList.Visible = true; break; - } - } - - private void SwitchAboutItem() - { - switch (SideBar.SelectedIndex) - { - case 0: - appSettingBox.LoadItems(); appSettingBox.Visible = true; - break; - case 1: - languagesBox.LoadLanguages(); languagesBox.Visible = true; - break; - case 2: - backupListBox.LoadItems(); backupListBox.Visible = true; - break; - case 3: - dictionariesBox.LoadText(); dictionariesBox.Visible = true; - break; - case 4: - if (aboutMeBox.TextLength == 0) aboutMeBox.LoadIni(AppString.Other.AboutApp); - aboutMeBox.Visible = true; - break; - case 5: - donateBox.Visible = true; - break; - } - } - - private void ResizeSideBar() - { - SideBar.Width = 0; - string[] strs = GeneralItems.Concat(TypeItems).Concat(OtherRuleItems).Concat(AboutItems).ToArray(); - Array.ForEach(strs, str => SideBar.Width = Math.Max(SideBar.Width, SideBar.GetItemWidth(str))); - } - - private void AddContextMenus() - { - var dic = new Dictionary - { - { ToolBarButtons[0], GeneralItems }, - { ToolBarButtons[1], TypeItems }, - { ToolBarButtons[2], OtherRuleItems }, - { ToolBarButtons[4], SettingItems } - }; - - // 创建工具栏按钮到索引的映射 - var buttonToIndex = new Dictionary - { - { ToolBarButtons[0], 0 }, - { ToolBarButtons[1], 1 }, - { ToolBarButtons[2], 2 }, - { ToolBarButtons[3], 3 }, - { ToolBarButtons[4], 4 } - }; - - foreach (var item in dic) - { - ContextMenuStrip cms = new ContextMenuStrip(); - cms.MouseEnter += (sender, e) => - { - if (item.Key != ToolBar.SelectedButton) item.Key.Opacity = MyToolBar.HoveredOpacity; - }; - cms.Closed += (sender, e) => - { - if (item.Key != ToolBar.SelectedButton) item.Key.Opacity = MyToolBar.UnSelctedOpacity; - }; - item.Key.MouseDown += (sender, e) => - { - if (e.Button != MouseButtons.Right) return; - if (sender == ToolBar.SelectedButton) return; - cms.Show(item.Key, e.Location); - }; - for (int i = 0; i < item.Value.Length; i++) - { - if (item.Value[i] == null) cms.Items.Add(new RToolStripSeparator()); - else - { - var tsi = new RToolStripMenuItem(item.Value[i]); - cms.Items.Add(tsi); - - // 使用预定义的索引映射而不是动态获取 - int toolBarIndex = buttonToIndex[item.Key]; - int index = i; - - if (toolBarIndex != 4) - { - tsi.Click += (sender, e) => JumpItem(toolBarIndex, index); - cms.Opening += (sender, e) => tsi.Checked = lastItemIndex[toolBarIndex] == index; - } - else - { - tsi.Click += (sender, e) => - { - switch (index) - { - case 0: - AppConfig.TopMost = TopMost = !tsi.Checked; break; - case 2: - AppConfig.ShowFilePath = !tsi.Checked; break; - case 3: - AppConfig.HideDisabledItems = !tsi.Checked; SwitchItem(); break; - case 5: - AppConfig.OpenMoreRegedit = !tsi.Checked; break; - case 6: - AppConfig.OpenMoreExplorer = !tsi.Checked; break; - } - }; - cms.Opening += (sender, e) => - { - switch (index) - { - case 0: - tsi.Checked = TopMost; break; - case 2: - tsi.Checked = AppConfig.ShowFilePath; break; - case 3: - tsi.Checked = AppConfig.HideDisabledItems; break; - case 5: - tsi.Checked = AppConfig.OpenMoreRegedit; break; - case 6: - tsi.Checked = AppConfig.OpenMoreExplorer; break; - } - }; - } - } - } - } - } - - private void FirstRunDownloadLanguage() - { - if (AppConfig.IsFirstRun && CultureInfo.CurrentUICulture.Name != "zh-CN") - { - if (AppMessageBox.Show("It is detected that you may be running this program for the first time,\n" + - "and your system display language is not simplified Chinese (zh-CN),\n" + - "do you need to download another language?", - MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) - { - JumpItem(4, 1); - languagesBox.ShowLanguageDialog(); - } - } - } - - private void CloseMainForm() - { - if (explorerRestarter.Visible && AppMessageBox.Show(explorerRestarter.Text, - MessageBoxButtons.OKCancel) == DialogResult.OK) ExternalProgram.RestartExplorer(); - Opacity = 0; - WindowState = FormWindowState.Normal; - explorerRestarter.Visible = false; - AppConfig.MainFormSize = Size; - } - - // ==================== 搜索功能实现 ==================== - - private void InitializeSearch() - { - // 订阅搜索事件 - ToolBar.SearchPerformed += (s, e) => PerformSearch(); - ToolBar.SearchTextChanged += (s, e) => - { - // 实时搜索(可选) - if (string.IsNullOrEmpty(ToolBar.SearchText)) - { - ClearSearch(); - } - else - { - PerformSearch(); - } - }; - } - - private void PerformSearch() - { - string searchText = ToolBar.SearchText; - if (string.IsNullOrWhiteSpace(searchText)) - { - ClearSearch(); - return; - } - - // 防止重复搜索相同内容 - if (searchText == lastSearchText && isSearching) return; - - lastSearchText = searchText; - isSearching = true; - - Cursor = Cursors.WaitCursor; - - try - { - // 在当前显示的 MainBody 中搜索 - SearchCurrentList(searchText); - - // 更新状态栏显示搜索结果 - UpdateSearchStatus(searchText); - } - finally - { - Cursor = Cursors.Default; - } - } - - private void SearchCurrentList(string searchText) - { - // 根据当前选中的工具栏和侧边栏项目确定要搜索的列表 - switch (ToolBar.SelectedIndex) - { - case 0: // 主页 - SearchGeneralList(searchText); - break; - case 1: // 文件类型 - SearchTypeList(searchText); - break; - case 2: // 其他规则 - SearchOtherRuleList(searchText); - break; - case 4: // 关于 - SearchAboutList(searchText); - break; - } - } - - private void SearchGeneralList(string searchText) - { - switch (SideBar.SelectedIndex) - { - case 11: - SafeSearchItems(shellNewList, searchText); - break; - case 12: - SafeSearchItems(sendToList, searchText); - break; - case 13: - SafeSearchItems(openWithList, searchText); - break; - case 15: - SafeSearchItems(winXList, searchText); - break; - default: - SafeSearchItems(shellList, searchText); - break; - } - } - - private void SearchTypeList(string searchText) - { - SafeSearchItems(shellList, searchText); - } - - private void SearchOtherRuleList(string searchText) - { - switch (SideBar.SelectedIndex) - { - case 0: - SafeSearchItems(enhanceMenusList, searchText); - break; - case 1: - SafeSearchItems(detailedEditList, searchText); - break; - case 3: - case 4: - case 8: - SafeSearchItems(shellList, searchText); - break; - case 5: - SafeSearchItems(iEList, searchText); - break; - case 7: - SafeSearchItems(guidBlockedList, searchText); - break; - } - } - - private void SearchAboutList(string searchText) - { - switch (SideBar.SelectedIndex) - { - case 2: - SafeSearchItems(backupListBox, searchText); - break; - case 3: - SafeSearchItems(dictionariesBox, searchText); - break; - // 其他关于页面不支持搜索 - } - } - - // 安全的搜索方法,避免编译错误 - private void SafeSearchItems(Control control, string searchText) - { - try - { - // 方法1:使用反射调用 SearchItems 方法 - var method = control.GetType().GetMethod("SearchItems"); - if (method != null) - { - method.Invoke(control, new object[] { searchText }); - return; - } - - // 方法2:如果是 MyListBox 或 MyList,直接调用 - if (control is BluePointLilac.Controls.MyListBox listBox) - { - listBox.SearchItems(searchText); - } - else if (control is BluePointLilac.Controls.MyList list) - { - list.SearchItems(searchText); - } - } - catch (Exception ex) - { - // 忽略搜索错误,这个控件可能不支持搜索 - System.Diagnostics.Debug.WriteLine($"搜索错误 {control.GetType().Name}: {ex.Message}"); - } - } - - private void UpdateSearchStatus(string searchText) - { - int visibleCount = 0; - int totalCount = 0; - - // 计算可见项和总项数 - foreach (Control ctr in MainControls) - { - if (ctr.Visible) - { - var items = SafeGetAllItems(ctr); - totalCount += items.Count(); - visibleCount += items.Count(item => item.Visible); - } - } - - if (string.IsNullOrWhiteSpace(searchText)) - { - StatusBar.Text = MyStatusBar.DefaultText; - } - else - { - StatusBar.Text = AppString.Other.StatusSearch.Replace("%searchText", searchText).Replace("%visibleCount", visibleCount.ToString()).Replace("%totalCount", totalCount.ToString()); - } - } - - // 安全获取所有项目的方法 - private IEnumerable SafeGetAllItems(Control control) - { - try - { - // 方法1:使用反射调用 GetAllItems 方法 - var method = control.GetType().GetMethod("GetAllItems"); - if (method != null) - { - var result = method.Invoke(control, null); - if (result is IEnumerable items) - { - return items; - } - } - - // 方法2:如果是 MyListBox 或 MyList,直接调用 - if (control is BluePointLilac.Controls.MyListBox listBox) - { - return listBox.GetAllItems().Cast(); - } - else if (control is BluePointLilac.Controls.MyList list) - { - return list.GetAllItems().Cast(); - } - - // 方法3:默认返回所有子控件 - return control.Controls.Cast(); - } - catch (Exception ex) - { - // 忽略错误,返回空集合 - System.Diagnostics.Debug.WriteLine($"获取项目错误 {control.GetType().Name}: {ex.Message}"); - return Enumerable.Empty(); - } - } - - private void ClearSearch() - { - if (!isSearching) return; - - // 清除所有列表的搜索状态 - foreach (Control ctr in MainControls) - { - SafeSearchItems(ctr, string.Empty); - } - - // 重置搜索状态 - isSearching = false; - lastSearchText = string.Empty; - ToolBar.ClearSearch(); - - // 恢复状态栏显示 - ShowItemInfo(); - } - - // 添加键盘快捷键(Ctrl+F 聚焦搜索框) - protected override bool ProcessCmdKey(ref Message msg, Keys keyData) - { - if (keyData == (Keys.Control | Keys.F)) - { - ToolBar.FocusSearchBox(); - return true; - } - - // ESC 键清除搜索 - if (keyData == Keys.Escape && isSearching) - { - ClearSearch(); - return true; - } - - return base.ProcessCmdKey(ref msg, keyData); - } - } +using BluePointLilac.Controls; +using BluePointLilac.Methods; +using ContextMenuManager.Controls; +using ContextMenuManager.Methods; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Reflection; +using System.Windows.Forms; + +namespace ContextMenuManager +{ + sealed class MainForm : MyMainForm + { + private SearchBox searchBox; // 添加搜索框成员变量 + private Control currentListControl; // 当前显示的列表控件 + private List originalListItems = new List(); // 保存原始列表项 + + public MainForm() + { + TopMost = AppConfig.TopMost; + StartPosition = FormStartPosition.CenterScreen; + Size = AppConfig.MainFormSize; + Text = AppString.General.AppName; + Controls.Add(explorerRestarter); + ToolBar.AddButtons(ToolBarButtons); + + // 创建并添加搜索框到工具栏 + searchBox = new SearchBox(); + searchBox.PlaceholderText = AppString.General.Search ?? "搜索..."; + ToolBar.AddSearchBox(searchBox); + + MainBody.Controls.AddRange(MainControls); + ToolBarButtons[3].CanBeSelected = false; + ToolBarButtons[3].MouseDown += (sender, e) => RefreshApp(); + ToolBar.SelectedButtonChanged += (sender, e) => + { + searchBox.Clear(); // 切换标签页时清空搜索框 + originalListItems.Clear(); // 清除保存的原始列表项 + SwitchTab(); + }; + SideBar.HoverIndexChanged += (sender, e) => ShowItemInfo(); + SideBar.SelectIndexChanged += (sender, e) => + { + searchBox.Clear(); // 切换侧边栏项时清空搜索框 + originalListItems.Clear(); // 清除保存的原始列表项 + SwitchItem(); + }; + Shown += (sender, e) => FirstRunDownloadLanguage(); + FormClosing += (sender, e) => CloseMainForm(); + + // 监听搜索框文本变化事件 + searchBox.TextChanged += (sender, e) => FilterItems(searchBox.Text); + + HoveredToShowItemPath(); + DragDropToAnalysis(); + AddContextMenus(); + ResizeSideBar(); + JumpItem(0, 0); + } + + readonly MyToolBarButton[] ToolBarButtons = + { + new MyToolBarButton(AppImage.Home, AppString.ToolBar.Home), + new MyToolBarButton(AppImage.Type, AppString.ToolBar.Type), + new MyToolBarButton(AppImage.Star, AppString.ToolBar.Rule), + new MyToolBarButton(AppImage.Refresh, AppString.ToolBar.Refresh), + new MyToolBarButton(AppImage.About, AppString.ToolBar.About) + }; + + private Control[] MainControls => new Control[] + { + shellList, shellNewList, sendToList, openWithList, winXList, + enhanceMenusList, detailedEditList, guidBlockedList, iEList, + appSettingBox, languagesBox, dictionariesBox, aboutMeBox, + donateBox, backupListBox + }; + + readonly ShellList shellList = new ShellList(); + readonly ShellNewList shellNewList = new ShellNewList(); + readonly SendToList sendToList = new SendToList(); + readonly OpenWithList openWithList = new OpenWithList(); + readonly WinXList winXList = new WinXList(); + + readonly EnhanceMenuList enhanceMenusList = new EnhanceMenuList(); + readonly DetailedEditList detailedEditList = new DetailedEditList(); + readonly GuidBlockedList guidBlockedList = new GuidBlockedList(); + readonly IEList iEList = new IEList(); + + readonly AppSettingBox appSettingBox = new AppSettingBox(); + readonly LanguagesBox languagesBox = new LanguagesBox(); + readonly DictionariesBox dictionariesBox = new DictionariesBox(); + readonly ReadOnlyRichTextBox aboutMeBox = new ReadOnlyRichTextBox(); + readonly DonateBox donateBox = new DonateBox(); + readonly BackupListBox backupListBox = new BackupListBox(); + readonly ExplorerRestarter explorerRestarter = new ExplorerRestarter(); + + // 主页 + static readonly string[] GeneralItems = + { + AppString.SideBar.File, + AppString.SideBar.Folder, + AppString.SideBar.Directory, + AppString.SideBar.Background, + AppString.SideBar.Desktop, + AppString.SideBar.Drive, + AppString.SideBar.AllObjects, + AppString.SideBar.Computer, + AppString.SideBar.RecycleBin, + AppString.SideBar.Library, + null, + AppString.SideBar.New, + AppString.SideBar.SendTo, + AppString.SideBar.OpenWith, + null, + AppString.SideBar.WinX + }; + static readonly string[] GeneralItemInfos = + { + AppString.StatusBar.File, + AppString.StatusBar.Folder, + AppString.StatusBar.Directory, + AppString.StatusBar.Background, + AppString.StatusBar.Desktop, + AppString.StatusBar.Drive, + AppString.StatusBar.AllObjects, + AppString.StatusBar.Computer, + AppString.StatusBar.RecycleBin, + AppString.StatusBar.Library, + null, + AppString.StatusBar.New, + AppString.StatusBar.SendTo, + AppString.StatusBar.OpenWith, + null, + AppString.StatusBar.WinX + }; + + // 文件类型 + static readonly string[] TypeItems = + { + AppString.SideBar.LnkFile, + AppString.SideBar.UwpLnk, + AppString.SideBar.ExeFile, + AppString.SideBar.UnknownType, + null, + AppString.SideBar.CustomExtension, + AppString.SideBar.PerceivedType, + AppString.SideBar.DirectoryType, + null, + AppString.SideBar.MenuAnalysis + }; + static readonly string[] TypeItemInfos = + { + AppString.StatusBar.LnkFile, + AppString.StatusBar.UwpLnk, + AppString.StatusBar.ExeFile, + AppString.StatusBar.UnknownType, + null, + AppString.StatusBar.CustomExtension, + AppString.StatusBar.PerceivedType, + AppString.StatusBar.DirectoryType, + null, + AppString.StatusBar.MenuAnalysis + }; + + // 其他规则 + static readonly string[] OtherRuleItems = + { + AppString.SideBar.EnhanceMenu, + AppString.SideBar.DetailedEdit, + null, + AppString.SideBar.DragDrop, + AppString.SideBar.PublicReferences, + AppString.SideBar.IEMenu, + null, + AppString.SideBar.GuidBlocked, + AppString.SideBar.CustomRegPath, + }; + static readonly string[] OtherRuleItemInfos = + { + AppString.StatusBar.EnhanceMenu, + AppString.StatusBar.DetailedEdit, + null, + AppString.StatusBar.DragDrop, + AppString.StatusBar.PublicReferences, + AppString.StatusBar.IEMenu, + null, + AppString.StatusBar.GuidBlocked, + AppString.StatusBar.CustomRegPath, + }; + + // 关于 + static readonly string[] AboutItems = + { + AppString.SideBar.AppSetting, + AppString.SideBar.AppLanguage, + AppString.SideBar.BackupRestore, + AppString.SideBar.Dictionaries, + AppString.SideBar.AboutApp, + AppString.SideBar.Donate, + }; + + static readonly string[] SettingItems = + { + AppString.Other.TopMost, + null, + AppString.Other.ShowFilePath, + AppString.Other.HideDisabledItems, + null, + AppString.Other.OpenMoreRegedit, + AppString.Other.OpenMoreExplorer, + }; + + static readonly Scenes[] GeneralShellScenes = + { + Scenes.File, + Scenes.Folder, + Scenes.Directory, + Scenes.Background, + Scenes.Desktop, + Scenes.Drive, + Scenes.AllObjects, + Scenes.Computer, + Scenes.RecycleBin, + Scenes.Library + }; + + static readonly Scenes?[] TypeShellScenes = + { + Scenes.LnkFile, + Scenes.UwpLnk, + Scenes.ExeFile, + Scenes.UnknownType, + null, + Scenes.CustomExtension, + Scenes.PerceivedType, + Scenes.DirectoryType, + null, + Scenes.MenuAnalysis + }; + + readonly int[] lastItemIndex = new int[5]; + + public void JumpItem(int toolBarIndex, int sideBarIndex) + { + bool flag1 = ToolBar.SelectedIndex == toolBarIndex; + bool flag2 = SideBar.SelectedIndex == sideBarIndex; + lastItemIndex[toolBarIndex] = sideBarIndex; + ToolBar.SelectedIndex = toolBarIndex; + if(flag1 || flag2) + { + SideBar.SelectedIndex = sideBarIndex; + SwitchItem(); + } + } + + private void RefreshApp() + { + Cursor = Cursors.WaitCursor; + ObjectPath.FilePathDic.Clear(); + AppConfig.ReloadConfig(); + GuidInfo.ReloadDics(); + XmlDicHelper.ReloadDics(); + SwitchItem(); + Cursor = Cursors.Default; + } + + private void SwitchTab() + { + switch(ToolBar.SelectedIndex) + { + case 0: + SideBar.ItemNames = GeneralItems; break; + case 1: + SideBar.ItemNames = TypeItems; break; + case 2: + SideBar.ItemNames = OtherRuleItems; break; + case 4: + SideBar.ItemNames = AboutItems; break; + } + SideBar.SelectedIndex = lastItemIndex[ToolBar.SelectedIndex]; + } + + private void SwitchItem() + { + // 清空原始列表项缓存 + originalListItems.Clear(); + + foreach(Control ctr in MainControls) + { + ctr.Visible = false; + if(ctr is MyList list) list.ClearItems(); + } + if(SideBar.SelectedIndex == -1) return; + switch(ToolBar.SelectedIndex) + { + case 0: + SwitchGeneralItem(); break; + case 1: + SwitchTypeItem(); break; + case 2: + SwitchOtherRuleItem(); break; + case 4: + SwitchAboutItem(); break; + } + lastItemIndex[ToolBar.SelectedIndex] = SideBar.SelectedIndex; + SuspendMainBodyWhenMove = MainControls.ToList().Any(ctr => ctr.Controls.Count > 50); + } + + private void ShowItemInfo() + { + if(SideBar.HoveredIndex >= 0) + { + int i = SideBar.HoveredIndex; + switch(ToolBar.SelectedIndex) + { + case 0: + StatusBar.Text = GeneralItemInfos[i]; return; + case 1: + StatusBar.Text = TypeItemInfos[i]; return; + case 2: + StatusBar.Text = OtherRuleItemInfos[i]; return; + } + } + StatusBar.Text = MyStatusBar.DefaultText; + } + + private void HoveredToShowItemPath() + { + foreach(Control ctr in MainBody.Controls) + { + if(ctr is MyList list && list != appSettingBox) + { + list.HoveredItemChanged += (sender, e) => + { + if(!AppConfig.ShowFilePath) return; + MyListItem item = list.HoveredItem; + foreach(string prop in new[] { "ItemFilePath", "RegPath", "GroupPath", "SelectedPath" }) + { + string path = item.GetType().GetProperty(prop)?.GetValue(item, null)?.ToString(); + if(!path.IsNullOrWhiteSpace()) { StatusBar.Text = path; return; } + } + StatusBar.Text = item.Text; + }; + } + } + } + + private void DragDropToAnalysis() + { + var droper = new ElevatedFileDroper(this); + droper.DragDrop += (sender, e) => + { + ShellList.CurrentFileObjectPath = droper.DropFilePaths[0]; + JumpItem(1, 9); + }; + } + + private void SwitchGeneralItem() + { + switch(SideBar.SelectedIndex) + { + case 11: + shellNewList.LoadItems(); shellNewList.Visible = true; + currentListControl = shellNewList; + SaveOriginalListItems(); + break; + case 12: + sendToList.LoadItems(); sendToList.Visible = true; + currentListControl = sendToList; + SaveOriginalListItems(); + break; + case 13: + openWithList.LoadItems(); openWithList.Visible = true; + currentListControl = openWithList; + SaveOriginalListItems(); + break; + case 15: + winXList.LoadItems(); winXList.Visible = true; + currentListControl = winXList; + SaveOriginalListItems(); + break; + default: + shellList.Scene = GeneralShellScenes[SideBar.SelectedIndex]; + shellList.LoadItems(); shellList.Visible = true; + currentListControl = shellList; + SaveOriginalListItems(); + break; + } + } + + private void SwitchTypeItem() + { + shellList.Scene = (Scenes)TypeShellScenes[SideBar.SelectedIndex]; + shellList.LoadItems(); + shellList.Visible = true; + currentListControl = shellList; + SaveOriginalListItems(); + } + + private void SwitchOtherRuleItem() + { + switch(SideBar.SelectedIndex) + { + case 0: + enhanceMenusList.ScenePath = null; enhanceMenusList.LoadItems(); enhanceMenusList.Visible = true; + currentListControl = enhanceMenusList; + SaveOriginalListItems(); + break; + case 1: + detailedEditList.GroupGuid = Guid.Empty; detailedEditList.LoadItems(); detailedEditList.Visible = true; + currentListControl = detailedEditList; + SaveOriginalListItems(); + break; + case 3: + shellList.Scene = Scenes.DragDrop; shellList.LoadItems(); shellList.Visible = true; + currentListControl = shellList; + SaveOriginalListItems(); + break; + case 4: + shellList.Scene = Scenes.PublicReferences; shellList.LoadItems(); shellList.Visible = true; + currentListControl = shellList; + SaveOriginalListItems(); + break; + case 5: + iEList.LoadItems(); iEList.Visible = true; + currentListControl = iEList; + SaveOriginalListItems(); + break; + case 7: + guidBlockedList.LoadItems(); guidBlockedList.Visible = true; + currentListControl = guidBlockedList; + SaveOriginalListItems(); + break; + case 8: + shellList.Scene = Scenes.CustomRegPath; shellList.LoadItems(); shellList.Visible = true; + currentListControl = shellList; + SaveOriginalListItems(); + break; + } + } + + private void SwitchAboutItem() + { + switch(SideBar.SelectedIndex) + { + case 0: + appSettingBox.LoadItems(); appSettingBox.Visible = true; + break; + case 1: + languagesBox.LoadLanguages(); languagesBox.Visible = true; + break; + case 2: + backupListBox.LoadItems(); backupListBox.Visible = true; + break; + case 3: + dictionariesBox.LoadText(); dictionariesBox.Visible = true; + break; + case 4: + if(aboutMeBox.TextLength == 0) aboutMeBox.LoadIni(AppString.Other.AboutApp); + aboutMeBox.Visible = true; + break; + case 5: + donateBox.Visible = true; + break; + } + currentListControl = null; + } + + // 保存原始列表项 + private void SaveOriginalListItems() + { + originalListItems.Clear(); + + if (currentListControl != null && currentListControl is MyList myList) + { + foreach (Control control in myList.Controls) + { + originalListItems.Add(control); + } + } + } + + // 过滤项目 + private void FilterItems(string filterText) + { + if (string.IsNullOrWhiteSpace(filterText)) + { + // 如果搜索框为空,恢复显示所有原始项 + RestoreOriginalListItems(); + return; + } + + string searchText = filterText.ToLower(); + + // 根据当前列表控件进行过滤 + if (currentListControl != null && currentListControl is MyList myList) + { + FilterListItems(myList, searchText); + } + } + + // 恢复原始列表项 + private void RestoreOriginalListItems() + { + if (currentListControl != null && currentListControl is MyList myList) + { + // 先清空当前列表 + myList.Controls.Clear(); + + // 恢复所有原始项 + foreach (var item in originalListItems) + { + myList.Controls.Add(item); + } + + // 恢复状态栏文本 + StatusBar.Text = MyStatusBar.DefaultText; + } + } + + private void FilterListItems(MyList listControl, string searchText) + { + // 遍历列表项并过滤 + var itemsToShow = new List(); + + foreach (Control control in listControl.Controls) + { + if (control is MyListItem item) + { + bool matches = false; + + // 检查主文本 + if (item.Text != null && item.Text.ToLower().Contains(searchText)) + { + matches = true; + } + + // 检查SubText + if (!matches && !string.IsNullOrEmpty(item.SubText) && item.SubText.ToLower().Contains(searchText)) + { + matches = true; + } + + // 检查其他可能包含文本的属性 + if (!matches) + { + // 可以通过反射检查其他文本属性 + var properties = item.GetType().GetProperties(); + foreach (var prop in properties) + { + if (prop.PropertyType == typeof(string)) + { + // 排除 Text 属性,因为已经检查过了 + if (prop.Name != "Text" && prop.Name != "SubText") + { + var value = prop.GetValue(item) as string; + if (value != null && value.ToLower().Contains(searchText)) + { + matches = true; + break; + } + } + } + } + } + + if (matches) + { + itemsToShow.Add(item); + } + } + } + + // 清除当前列表并添加匹配的项 + listControl.Controls.Clear(); + foreach (var item in itemsToShow) + { + listControl.Controls.Add(item); + } + + // 如果没有匹配项,显示提示 + if (itemsToShow.Count == 0 && !string.IsNullOrWhiteSpace(searchText)) + { + StatusBar.Text = $"{AppString.General.NoResultsFor ?? "没有找到匹配"} \"{searchText}\""; + } + else if (itemsToShow.Count > 0) + { + StatusBar.Text = $"找到 {itemsToShow.Count} 个匹配项"; + } + } + + // 添加快捷键支持 + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { + // 全局搜索快捷键 Ctrl+F + if (keyData == (Keys.Control | Keys.F)) + { + searchBox?.FocusTextBox(); + return true; + } + + // ESC 清除搜索框 + if (keyData == Keys.Escape && searchBox != null && !string.IsNullOrEmpty(searchBox.Text)) + { + searchBox.Clear(); + return true; + } + + return base.ProcessCmdKey(ref msg, keyData); + } + + private void ResizeSideBar() + { + SideBar.Width = 0; + string[] strs = GeneralItems.Concat(TypeItems).Concat(OtherRuleItems).Concat(AboutItems).ToArray(); + Array.ForEach(strs, str => SideBar.Width = Math.Max(SideBar.Width, SideBar.GetItemWidth(str))); + } + + private void AddContextMenus() + { + var dic = new Dictionary + { + { ToolBarButtons[0], GeneralItems }, + { ToolBarButtons[1], TypeItems }, + { ToolBarButtons[2], OtherRuleItems }, + { ToolBarButtons[4], SettingItems } + }; + + foreach(var item in dic) + { + ContextMenuStrip cms = new ContextMenuStrip(); + cms.MouseEnter += (sender, e) => + { + if(item.Key != ToolBar.SelectedButton) item.Key.Opacity = MyToolBar.HoveredOpacity; + }; + cms.Closed += (sender, e) => + { + if(item.Key != ToolBar.SelectedButton) item.Key.Opacity = MyToolBar.UnSelctedOpacity; + }; + item.Key.MouseDown += (sender, e) => + { + if(e.Button != MouseButtons.Right) return; + if(sender == ToolBar.SelectedButton) return; + cms.Show(item.Key, e.Location); + }; + for(int i = 0; i < item.Value.Length; i++) + { + if(item.Value[i] == null) cms.Items.Add(new RToolStripSeparator()); + else + { + var tsi = new RToolStripMenuItem(item.Value[i]); + cms.Items.Add(tsi); + + // 修复:使用 ButtonControls 而不是 Controls + int toolBarIndex = ToolBar.ButtonControls.GetChildIndex(item.Key); + int index = i; + + if(toolBarIndex != 4) + { + tsi.Click += (sender, e) => JumpItem(toolBarIndex, index); + cms.Opening += (sender, e) => tsi.Checked = lastItemIndex[toolBarIndex] == index; + } + else + { + tsi.Click += (sender, e) => + { + switch(index) + { + case 0: + AppConfig.TopMost = TopMost = !tsi.Checked; break; + case 2: + AppConfig.ShowFilePath = !tsi.Checked; break; + case 3: + AppConfig.HideDisabledItems = !tsi.Checked; SwitchItem(); break; + case 5: + AppConfig.OpenMoreRegedit = !tsi.Checked; break; + case 6: + AppConfig.OpenMoreExplorer = !tsi.Checked; break; + } + }; + cms.Opening += (sender, e) => + { + switch(index) + { + case 0: + tsi.Checked = TopMost; break; + case 2: + tsi.Checked = AppConfig.ShowFilePath; break; + case 3: + tsi.Checked = AppConfig.HideDisabledItems; break; + case 5: + tsi.Checked = AppConfig.OpenMoreRegedit; break; + case 6: + tsi.Checked = AppConfig.OpenMoreExplorer; break; + } + }; + } + } + } + } + } + + private void FirstRunDownloadLanguage() + { + if(AppConfig.IsFirstRun && CultureInfo.CurrentUICulture.Name != "zh-CN") + { + if(AppMessageBox.Show("It is detected that you may be running this program for the first time,\n" + + "and your system display language is not simplified Chinese (zh-CN),\n" + + "do you need to download another language?", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + JumpItem(4, 1); + languagesBox.ShowLanguageDialog(); + } + } + } + + private void CloseMainForm() + { + if(explorerRestarter.Visible && AppMessageBox.Show(explorerRestarter.Text, + MessageBoxButtons.OKCancel) == DialogResult.OK) ExternalProgram.RestartExplorer(); + Opacity = 0; + WindowState = FormWindowState.Normal; + explorerRestarter.Visible = false; + AppConfig.MainFormSize = Size; + } + } } \ No newline at end of file diff --git a/ContextMenuManager/Methods/AppConfig.cs b/ContextMenuManager/Methods/AppConfig.cs index 5351da6f..f92905b7 100644 --- a/ContextMenuManager/Methods/AppConfig.cs +++ b/ContextMenuManager/Methods/AppConfig.cs @@ -142,12 +142,12 @@ public static void ReloadConfig() private static void CreateDirectory() { - foreach (string dirPath in new[] { AppDataDir, ConfigDir, ProgramsDir, RegBackupDir, MenuBackupDir, LangsDir, DicsDir, WebDicsDir, UserDicsDir }) + foreach(string dirPath in new[] { AppDataDir, ConfigDir, ProgramsDir, RegBackupDir, MenuBackupDir, LangsDir, DicsDir, WebDicsDir, UserDicsDir }) { Directory.CreateDirectory(dirPath); Application.ApplicationExit += (sender, e) => { - if (Directory.Exists(dirPath) && Directory.GetFileSystemEntries(dirPath).Length == 0) + if(Directory.Exists(dirPath) && Directory.GetFileSystemEntries(dirPath).Length == 0) { try { @@ -165,14 +165,14 @@ private static void CreateDirectory() private static void LoadLanguage() { language = GetGeneralValue("Language"); - if (language.ToLower() == "default") + if(language.ToLower() == "default") { LanguageIniPath = ""; return; } - if (language == "") language = CultureInfo.CurrentUICulture.Name; + if(language == "") language = CultureInfo.CurrentUICulture.Name; LanguageIniPath = $@"{LangsDir}\{language}.ini"; - if (!File.Exists(LanguageIniPath)) + if(!File.Exists(LanguageIniPath)) { LanguageIniPath = ""; Language = ""; @@ -225,7 +225,7 @@ public static string EngineUrl get { string url = GetGeneralValue("EngineUrl"); - if (string.IsNullOrEmpty(url)) url = EngineUrlsDic.Values.ToArray()[0]; + if(string.IsNullOrEmpty(url)) url = EngineUrlsDic.Values.ToArray()[0]; return url; } set => SetGeneralValue("EngineUrl", value); @@ -272,8 +272,8 @@ public static bool RequestUseGithub get { string value = GetGeneralValue("RequestUseGithub"); - if (!string.IsNullOrEmpty(value)) return value == "1"; - if (CultureInfo.CurrentCulture.Name == "zh-CN") return false; + if(!string.IsNullOrEmpty(value)) return value == "1"; + if(CultureInfo.CurrentCulture.Name == "zh-CN") return false; return true; } set => SetGeneralValue("RequestUseGithub", value ? 1 : 0); @@ -284,9 +284,9 @@ public static int UpdateFrequency get { string value = GetGeneralValue("UpdateFrequency"); - if (int.TryParse(value, out int day)) + if(int.TryParse(value, out int day)) { - if (day == -1 || day == 7 || day == 90) return day; + if(day == -1 || day == 7 || day == 90) return day; } return 30; } @@ -305,9 +305,9 @@ public static Size MainFormSize { string str = GetWindowValue("MainFormSize"); int index = str.IndexOf(','); - if (index == -1) return Size.Empty; - if (int.TryParse(str.Substring(0, index), out int x)) - if (int.TryParse(str.Substring(index + 1), out int y)) + if(index == -1) return Size.Empty; + if(int.TryParse(str.Substring(0, index), out int x)) + if(int.TryParse(str.Substring(index + 1), out int y)) return new Size(x, y); return Size.Empty; } diff --git a/ContextMenuManager/Methods/AppImage.cs b/ContextMenuManager/Methods/AppImage.cs index fafbde66..38019cbd 100644 --- a/ContextMenuManager/Methods/AppImage.cs +++ b/ContextMenuManager/Methods/AppImage.cs @@ -1,6 +1,7 @@ -using BluePointLilac.Methods; +using BluePointLilac.Methods; using ContextMenuManager.Properties; using System.Drawing; +using System.Windows.Forms; namespace ContextMenuManager.Methods { @@ -95,10 +96,12 @@ static class AppImage public static readonly Image Lock = GetIconImage("imageres.dll", -59); ///快捷方式图标 public static readonly Image LnkFile = GetIconImage("shell32.dll", -16769); + ///搜索 + public static readonly Image Search = GetIconImage("shell32.dll", -23); private static Image GetIconImage(string dllName, int iconIndex) { - using (Icon icon = ResourceIcon.GetIcon(dllName, iconIndex)) return icon?.ToBitmap(); + using(Icon icon = ResourceIcon.GetIcon(dllName, iconIndex)) return icon?.ToBitmap(); } } } \ No newline at end of file diff --git a/ContextMenuManager/Methods/AppString.cs b/ContextMenuManager/Methods/AppString.cs index 331bc125..eaea1cc8 100644 --- a/ContextMenuManager/Methods/AppString.cs +++ b/ContextMenuManager/Methods/AppString.cs @@ -13,16 +13,16 @@ static class AppString private static string GetValue(string section, string key) { string value = UserLangReader.GetValue(section, key); - if (string.IsNullOrEmpty(value)) value = DefLangReader.GetValue(section, key); + if(string.IsNullOrEmpty(value)) value = DefLangReader.GetValue(section, key); return value.Replace("\\r", "\r").Replace("\\n", "\n"); } /// 加载语言 public static void LoadStrings() { - foreach (Type type in typeof(AppString).GetNestedTypes()) + foreach(Type type in typeof(AppString).GetNestedTypes()) { - foreach (PropertyInfo pi in type.GetProperties()) + foreach(PropertyInfo pi in type.GetProperties()) { pi.SetValue(type, GetValue(type.Name, pi.Name), null); } @@ -33,6 +33,8 @@ public static void LoadStrings() public static class General { public static string AppName { get; set; } + public static string Search { get; set; } // 添加搜索文本 + public static string NoResultsFor { get; set; } // 添加无结果文本 } /// 工具栏 @@ -213,6 +215,7 @@ public static class Dialog public static string CopyDropEffect { get; set; } public static string MoveDropEffect { get; set; } public static string CreateLinkDropEffect { get; set; } + public static string Search { get; set; } public static string DownloadLanguages { get; set; } public static string TranslateTool { get; set; } public static string DefaultText { get; set; } @@ -361,8 +364,6 @@ public static class Other public static string TopMost { get; set; } public static string Unknown { get; set; } public static string RestoreItemText { get; set; } - public static string SearchContent { get; set; } - public static string StatusSearch { get; set; } } } -} +} \ No newline at end of file diff --git a/ContextMenuManager/Methods/BackupHelper.cs b/ContextMenuManager/Methods/BackupHelper.cs index e9036491..fc8c9ce8 100644 --- a/ContextMenuManager/Methods/BackupHelper.cs +++ b/ContextMenuManager/Methods/BackupHelper.cs @@ -1,17 +1,17 @@ -using BluePointLilac.Controls; -using BluePointLilac.Methods; +using BluePointLilac.Methods; using ContextMenuManager.Controls; using Microsoft.Win32; using System; using System.Collections.Generic; -using System.Drawing; using System.IO; using System.Linq; +using static ContextMenuManager.Controls.ShellList; using System.Xml; +using System.Drawing; +using static ContextMenuManager.Methods.BackupList; using System.Xml.Serialization; -using static ContextMenuManager.Controls.ShellList; using static ContextMenuManager.Controls.ShellNewList; -using static ContextMenuManager.Methods.BackupList; +using BluePointLilac.Controls; namespace ContextMenuManager.Methods { @@ -131,7 +131,7 @@ public BackupHelper() public string[] GetBackupRestoreScenesText(List scenes) { List scenesTextList = new List(); - foreach (Scenes scene in scenes) + foreach(Scenes scene in scenes) { scenesTextList.Add(BackupScenesText[(int)scene]); } @@ -248,7 +248,7 @@ private int GetBackupRestoreScenes(List sceneTexts) // 按照目前处理场景逐个备份或恢复 private void BackupRestoreItems(LoadingDialogInterface dialogInterface) { - foreach (Scenes scene in currentScenes) + foreach(Scenes scene in currentScenes) { currentScene = scene; // 加载某个Scene的恢复列表 @@ -374,7 +374,7 @@ private bool CheckItemNeedChange(string itemName, string keyName, BackupItemType } } } - if ((restoreMode == RestoreMode.DisableNotOnList && currentItemData) || + if ((restoreMode == RestoreMode.DisableNotOnList && currentItemData) || (restoreMode == RestoreMode.EnableNotOnList && !currentItemData)) { restoreList.Add(new RestoreChangedItem(currentScene, itemName, (!currentItemData).ToString())); @@ -848,7 +848,7 @@ private void GetBackupShellExItems(string shellExPath) { BackupRestoreItem(item, itemName, keyName, BackupItemType.ShellExItem, ifItemInMenu, currentScene); } - + names.Add(keyName); #if DEBUG i++; @@ -1393,8 +1393,7 @@ string GetRuleFullRegPath(string regPath) if (string.IsNullOrEmpty(regPath)) regPath = groupItem.GroupPath; else if (regPath.StartsWith("\\")) regPath = groupItem.GroupPath + regPath; return regPath; - } - ; + }; // 遍历groupItem内所有Item节点 foreach (XmlElement itemXE in groupXN.SelectNodes("Item")) @@ -1739,7 +1738,7 @@ private void GetEnhanceMenuListShellExItems(XmlNode shellExXN, FoldGroupItem gro public sealed class BackupList { // 元数据缓存区 - public static MetaData metaData = new MetaData(); + public static MetaData metaData = new MetaData(); // 备份列表/恢复列表缓存区 private static List backupRestoreList = new List(); @@ -1748,7 +1747,7 @@ public sealed class BackupList public static List sceneRestoreList = new List(); // 创建一个XmlSerializer实例并设置根节点 - private static readonly XmlSerializer backupDataSerializer = new XmlSerializer(typeof(BackupData), + private static readonly XmlSerializer backupDataSerializer = new XmlSerializer(typeof(BackupData), new XmlRootAttribute("ContextMenuManager")); // 自定义命名空间 private static readonly XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(); diff --git a/ContextMenuManager/Methods/DesktopIni.cs b/ContextMenuManager/Methods/DesktopIni.cs index fecb546e..8a09e350 100644 --- a/ContextMenuManager/Methods/DesktopIni.cs +++ b/ContextMenuManager/Methods/DesktopIni.cs @@ -28,7 +28,7 @@ public static string GetLocalizedFileNames(string filePath, bool translate = fal IniWriter writer = new IniWriter(GetDesktopIniPath(filePath)); string fileName = Path.GetFileName(filePath); string name = writer.GetValue(LocalizedFileNames, fileName); - if (translate) name = ResourceString.GetDirectString(name); + if(translate) name = ResourceString.GetDirectString(name); return name; } } diff --git a/ContextMenuManager/Methods/GuidInfo.cs b/ContextMenuManager/Methods/GuidInfo.cs index 3af68793..7bc4e482 100644 --- a/ContextMenuManager/Methods/GuidInfo.cs +++ b/ContextMenuManager/Methods/GuidInfo.cs @@ -63,52 +63,52 @@ private static bool TryGetValue(Guid guid, string key, out string value) //用户自定义字典优先 string section = guid.ToString(); value = UserDic.GetValue(section, key); - if (value != string.Empty) return true; - if (WebDic.TryGetValue(section, key, out value)) return true; - if (AppDic.TryGetValue(section, key, out value)) return true; + if(value != string.Empty) return true; + if(WebDic.TryGetValue(section, key, out value)) return true; + if(AppDic.TryGetValue(section, key, out value)) return true; return false; } public static string GetFilePath(Guid guid) { string filePath = null; - if (guid.Equals(Guid.Empty)) return filePath; - if (FilePathDic.ContainsKey(guid)) filePath = FilePathDic[guid]; + if(guid.Equals(Guid.Empty)) return filePath; + if(FilePathDic.ContainsKey(guid)) filePath = FilePathDic[guid]; else { string uwpName = GetUwpName(guid); - if (!string.IsNullOrEmpty(uwpName)) + if(!string.IsNullOrEmpty(uwpName)) { filePath = UwpHelper.GetFilePath(uwpName, guid); } else { - foreach (string clsidPath in ClsidPaths) + foreach(string clsidPath in ClsidPaths) { - using (RegistryKey guidKey = RegistryEx.GetRegistryKey($@"{clsidPath}\{guid:B}")) + using(RegistryKey guidKey = RegistryEx.GetRegistryKey($@"{clsidPath}\{guid:B}")) { - if (guidKey == null) continue; - foreach (string keyName in new[] { "InprocServer32", "LocalServer32" }) + if(guidKey == null) continue; + foreach(string keyName in new[] { "InprocServer32", "LocalServer32" }) { - using (RegistryKey key = guidKey.OpenSubKey(keyName)) + using(RegistryKey key = guidKey.OpenSubKey(keyName)) { - if (key == null) continue; + if(key == null) continue; string value1 = key.GetValue("CodeBase")?.ToString().Replace("file:///", "").Replace('/', '\\'); - if (File.Exists(value1)) + if(File.Exists(value1)) { filePath = value1; break; } string value2 = key.GetValue("")?.ToString(); value2 = ObjectPath.ExtractFilePath(value2); - if (File.Exists(value2)) + if(File.Exists(value2)) { filePath = value2; break; } } } - if (File.Exists(filePath)) + if(File.Exists(filePath)) { - if (ClsidPathDic.ContainsKey(guid)) ClsidPathDic[guid] = guidKey.Name; + if(ClsidPathDic.ContainsKey(guid)) ClsidPathDic[guid] = guidKey.Name; else ClsidPathDic.Add(guid, guidKey.Name); break; } @@ -122,12 +122,12 @@ public static string GetFilePath(Guid guid) public static string GetClsidPath(Guid guid) { - if (ClsidPathDic.ContainsKey(guid)) return ClsidPathDic[guid]; - foreach (string path in ClsidPaths) + if(ClsidPathDic.ContainsKey(guid)) return ClsidPathDic[guid]; + foreach(string path in ClsidPaths) { - using (RegistryKey key = RegistryEx.GetRegistryKey($@"{path}\{guid:B}")) + using(RegistryKey key = RegistryEx.GetRegistryKey($@"{path}\{guid:B}")) { - if (key != null) return key.Name; + if(key != null) return key.Name; } } return null; @@ -136,45 +136,45 @@ public static string GetClsidPath(Guid guid) public static string GetText(Guid guid) { string itemText = null; - if (guid.Equals(Guid.Empty)) return itemText; - if (ItemTextDic.ContainsKey(guid)) itemText = ItemTextDic[guid]; + if(guid.Equals(Guid.Empty)) return itemText; + if(ItemTextDic.ContainsKey(guid)) itemText = ItemTextDic[guid]; else { - if (TryGetValue(guid, "ResText", out itemText)) + if(TryGetValue(guid, "ResText", out itemText)) { itemText = GetAbsStr(guid, itemText, true); itemText = ResourceString.GetDirectString(itemText); } - if (itemText.IsNullOrWhiteSpace()) + if(itemText.IsNullOrWhiteSpace()) { string uiText = CultureInfo.CurrentUICulture.Name + "-Text"; TryGetValue(guid, uiText, out itemText); - if (itemText.IsNullOrWhiteSpace()) + if(itemText.IsNullOrWhiteSpace()) { TryGetValue(guid, "Text", out itemText); itemText = ResourceString.GetDirectString(itemText); } } - if (itemText.IsNullOrWhiteSpace()) + if(itemText.IsNullOrWhiteSpace()) { - foreach (string clsidPath in ClsidPaths) + foreach(string clsidPath in ClsidPaths) { - foreach (string value in new[] { "LocalizedString", "InfoTip", "" }) + foreach(string value in new[] { "LocalizedString", "InfoTip", "" }) { itemText = Registry.GetValue($@"{clsidPath}\{guid:B}", value, null)?.ToString(); itemText = ResourceString.GetDirectString(itemText); - if (!itemText.IsNullOrWhiteSpace()) break; + if(!itemText.IsNullOrWhiteSpace()) break; } - if (!itemText.IsNullOrWhiteSpace()) break; + if(!itemText.IsNullOrWhiteSpace()) break; } } - if (itemText.IsNullOrWhiteSpace()) + if(itemText.IsNullOrWhiteSpace()) { string filePath = GetFilePath(guid); - if (File.Exists(filePath)) + if(File.Exists(filePath)) { itemText = FileVersionInfo.GetVersionInfo(filePath).FileDescription; - if (itemText.IsNullOrWhiteSpace()) + if(itemText.IsNullOrWhiteSpace()) { itemText = Path.GetFileName(filePath); } @@ -188,12 +188,12 @@ public static string GetText(Guid guid) public static Image GetImage(Guid guid) { - if (ItemImageDic.TryGetValue(guid, out Image image)) return image; + if(ItemImageDic.TryGetValue(guid, out Image image)) return image; IconLocation location = GetIconLocation(guid); string iconPath = location.IconPath; int iconIndex = location.IconIndex; - if (iconPath == null && iconIndex == 0) image = AppImage.SystemFile; - else if (Path.GetFileName(iconPath).ToLower() == "shell32.dll" && iconIndex == 0) image = AppImage.SystemFile; + if(iconPath == null && iconIndex == 0) image = AppImage.SystemFile; + else if(Path.GetFileName(iconPath).ToLower() == "shell32.dll" && iconIndex == 0) image = AppImage.SystemFile; else image = ResourceIcon.GetIcon(iconPath, iconIndex)?.ToBitmap() ?? AppImage.SystemFile; ItemImageDic.Add(guid, image); return image; @@ -202,15 +202,15 @@ public static Image GetImage(Guid guid) public static IconLocation GetIconLocation(Guid guid) { IconLocation location = new IconLocation(); - if (guid.Equals(Guid.Empty)) return location; - if (IconLocationDic.ContainsKey(guid)) location = IconLocationDic[guid]; + if(guid.Equals(Guid.Empty)) return location; + if(IconLocationDic.ContainsKey(guid)) location = IconLocationDic[guid]; else { - if (TryGetValue(guid, "Icon", out string value)) + if(TryGetValue(guid, "Icon", out string value)) { value = GetAbsStr(guid, value, false); int index = value.LastIndexOf(','); - if (int.TryParse(value.Substring(index + 1), out int iconIndex)) + if(int.TryParse(value.Substring(index + 1), out int iconIndex)) { location.IconPath = value.Substring(0, index); location.IconIndex = iconIndex; @@ -226,8 +226,8 @@ public static IconLocation GetIconLocation(Guid guid) public static string GetUwpName(Guid guid) { string uwpName = null; - if (guid.Equals(Guid.Empty)) return uwpName; - if (UwpNameDic.ContainsKey(guid)) uwpName = UwpNameDic[guid]; + if(guid.Equals(Guid.Empty)) return uwpName; + if(UwpNameDic.ContainsKey(guid)) uwpName = UwpNameDic[guid]; else { TryGetValue(guid, "UwpName", out uwpName); @@ -239,11 +239,11 @@ public static string GetUwpName(Guid guid) private static string GetAbsStr(Guid guid, string relStr, bool isName) { string absStr = relStr; - if (isName) + if(isName) { - if (!absStr.StartsWith("@")) return absStr; + if(!absStr.StartsWith("@")) return absStr; else absStr = absStr.Substring(1); - if (absStr.StartsWith("{*?ms-resource://") && absStr.EndsWith("}")) + if(absStr.StartsWith("{*?ms-resource://") && absStr.EndsWith("}")) { absStr = "@{" + UwpHelper.GetPackageName(GetUwpName(guid)) + absStr.Substring(2); return absStr; @@ -251,26 +251,26 @@ private static string GetAbsStr(Guid guid, string relStr, bool isName) } string filePath = GetFilePath(guid); - if (filePath == null) return relStr; + if(filePath == null) return relStr; string dirPath = Path.GetDirectoryName(filePath); - if (absStr.StartsWith("*")) + if(absStr.StartsWith("*")) { absStr = filePath + absStr.Substring(1); } - else if (absStr.StartsWith(".\\")) + else if(absStr.StartsWith(".\\")) { absStr = dirPath + absStr.Substring(1); } - else if (absStr.StartsWith("..\\")) + else if(absStr.StartsWith("..\\")) { do { dirPath = Path.GetDirectoryName(dirPath); absStr = absStr.Substring(3); - } while (absStr.StartsWith("..\\")); + } while(absStr.StartsWith("..\\")); absStr = dirPath + "\\" + absStr; } - if (isName) absStr = "@" + absStr; + if(isName) absStr = "@" + absStr; return absStr; } } diff --git a/ContextMenuManager/Methods/ObjectPath.cs b/ContextMenuManager/Methods/ObjectPath.cs index 2c66442a..2cbb4fa4 100644 --- a/ContextMenuManager/Methods/ObjectPath.cs +++ b/ContextMenuManager/Methods/ObjectPath.cs @@ -24,20 +24,20 @@ public enum PathType { File, Directory, Registry } public static bool GetFullFilePath(string fileName, out string fullPath) { fullPath = null; - if (fileName.IsNullOrWhiteSpace()) return false; + if(fileName.IsNullOrWhiteSpace()) return false; - foreach (string name in new[] { fileName, $"{fileName}.exe" }) + foreach(string name in new[] { fileName, $"{fileName}.exe" }) { //右键菜单仅支持%SystemRoot%\System32和%SystemRoot%两个环境变量,不考虑其他系统环境变量和用户环境变量,和Win+R命令有区别 - foreach (string dir in new[] { "", @"%SystemRoot%\System32\", @"%SystemRoot%\" }) + foreach(string dir in new[] { "", @"%SystemRoot%\System32\", @"%SystemRoot%\" }) { - if (dir != "" && (name.Contains('\\') || name.Contains(':'))) return false; + if(dir != "" && (name.Contains('\\') || name.Contains(':'))) return false; fullPath = Environment.ExpandEnvironmentVariables($@"{dir}{name}"); - if (File.Exists(fullPath)) return true; + if(File.Exists(fullPath)) return true; } fullPath = Registry.GetValue($@"{RegAppPath}\{name}", "", null)?.ToString(); - if (File.Exists(fullPath)) return true; + if(File.Exists(fullPath)) return true; } fullPath = null; return false; @@ -50,29 +50,29 @@ public static bool GetFullFilePath(string fileName, out string fullPath) /// 成功提取返回现有文件路径,否则返回值为null public static string ExtractFilePath(string command) { - if (command.IsNullOrWhiteSpace()) return null; - if (FilePathDic.ContainsKey(command)) return FilePathDic[command]; + if(command.IsNullOrWhiteSpace()) return null; + if(FilePathDic.ContainsKey(command)) return FilePathDic[command]; else { string filePath = null; string partCmd = Environment.ExpandEnvironmentVariables(command).Replace(@"\\", @"\"); - if (partCmd.StartsWith(ShellExecuteCommand, StringComparison.OrdinalIgnoreCase)) + if(partCmd.StartsWith(ShellExecuteCommand, StringComparison.OrdinalIgnoreCase)) { partCmd = partCmd.Substring(ShellExecuteCommand.Length); string[] arr = partCmd.Split(new[] { "\",\"" }, StringSplitOptions.None); - if (arr.Length > 0) + if(arr.Length > 0) { string fileName = arr[0]; - if (GetFullFilePath(fileName, out filePath)) + if(GetFullFilePath(fileName, out filePath)) { FilePathDic.Add(command, filePath); return filePath; } - if (arr.Length > 1) + if(arr.Length > 1) { string arguments = arr[1]; filePath = ExtractFilePath(arguments); - if (filePath != null) return filePath; + if(filePath != null) return filePath; } } } @@ -80,7 +80,7 @@ public static string ExtractFilePath(string command) string[] strs = Array.FindAll(partCmd.Split(IllegalChars), str => IgnoreCommandParts.Any(part => !part.Equals(str.Trim()))).Reverse().ToArray(); - foreach (string str1 in strs) + foreach(string str1 in strs) { string str2 = str1; int index = -1; @@ -89,22 +89,22 @@ public static string ExtractFilePath(string command) List paths = new List(); string path1 = str2.Substring(index + 1); paths.Add(path1); - if (index > 0) + if(index > 0) { string path2 = str2.Substring(0, index); paths.Add(path2); } int count = paths.Count; - for (int i = 0; i < count; i++) + for(int i = 0; i < count; i++) { - foreach (char c in new[] { ',', '-' }) + foreach(char c in new[] { ',', '-' }) { - if (paths[i].Contains(c)) paths.AddRange(paths[i].Split(c)); + if(paths[i].Contains(c)) paths.AddRange(paths[i].Split(c)); } } - foreach (string path in paths) + foreach(string path in paths) { - if (GetFullFilePath(path, out filePath)) + if(GetFullFilePath(path, out filePath)) { FilePathDic.Add(command, filePath); return filePath; @@ -113,7 +113,7 @@ public static string ExtractFilePath(string command) str2 = path1; index = str2.IndexOf(' '); } - while (index != -1); + while(index != -1); } FilePathDic.Add(command, null); return null; @@ -135,7 +135,7 @@ public static string RemoveIllegalChars(string fileName) /// 目标路径存在返回true,否则返回false public static bool ObjectPathExist(string path, PathType type) { - switch (type) + switch(type) { case PathType.File: return File.Exists(path); @@ -162,10 +162,10 @@ public static string GetNewPathWithIndex(string oldPath, PathType type, int star do { newPath = $@"{dirPath}\{name}"; - if (startIndex > -1) newPath += startIndex; + if(startIndex > -1) newPath += startIndex; newPath += extension; startIndex++; - } while (ObjectPathExist(newPath, type)); + } while(ObjectPathExist(newPath, type)); return newPath; } } diff --git a/ContextMenuManager/Methods/Updater.cs b/ContextMenuManager/Methods/Updater.cs index fef0f8fe..bfbc2aa3 100644 --- a/ContextMenuManager/Methods/Updater.cs +++ b/ContextMenuManager/Methods/Updater.cs @@ -14,11 +14,11 @@ sealed class Updater public static void PeriodicUpdate() { int day = AppConfig.UpdateFrequency; - if (day == -1) return;//自动检测更新频率为-1则从不自动检查更新 + if(day == -1) return;//自动检测更新频率为-1则从不自动检查更新 //如果上次检测更新时间加上时间间隔早于或等于今天以前就进行更新操作 DateTime time = AppConfig.LastCheckUpdateTime.AddDays(day); //time = DateTime.Today;//测试用 - if (time <= DateTime.Today) _ = Task.Run(() => Update(false)); + if(time <= DateTime.Today) _ = Task.Run(() => Update(false)); } /// 更新程序以及程序字典 @@ -34,15 +34,15 @@ public static void Update(bool isManual) /// 是否为手动点击更新 private static void UpdateApp(bool isManual) { - using (UAWebClient client = new UAWebClient()) + using(UAWebClient client = new UAWebClient()) { string url = AppConfig.RequestUseGithub ? AppConfig.GithubLatestApi : AppConfig.GiteeLatestApi; XmlDocument doc = client.GetWebJsonToXml(url); - if (doc == null) + if(doc == null) { - if (isManual) + if(isManual) { - if (AppMessageBox.Show(AppString.Message.WebDataReadFailed + "\r\n" + if(AppMessageBox.Show(AppString.Message.WebDataReadFailed + "\r\n" + AppString.Message.OpenWebUrl, MessageBoxButtons.OKCancel) != DialogResult.OK) return; url = AppConfig.RequestUseGithub ? AppConfig.GithubLatest : AppConfig.GiteeReleases; ExternalProgram.OpenWebUrl(url); @@ -54,11 +54,11 @@ private static void UpdateApp(bool isManual) Version webVer = new Version(tagNameXN.InnerText); Version appVer = new Version(Application.ProductVersion); #if DEBUG - appVer = new Version(0, 0, 0, 0);//测试用 + appVer = new Version(0, 0, 0, 0);//测试用 #endif - if (appVer >= webVer) + if(appVer >= webVer) { - if (isManual) AppMessageBox.Show(AppString.Message.VersionIsLatest, + if(isManual) AppMessageBox.Show(AppString.Message.VersionIsLatest, MessageBoxButtons.OK, MessageBoxIcon.Information); } else @@ -66,22 +66,22 @@ private static void UpdateApp(bool isManual) XmlNode bodyXN = root.SelectSingleNode("body"); string info = AppString.Message.UpdateInfo.Replace("%v1", appVer.ToString()).Replace("%v2", webVer.ToString()); info += "\r\n\r\n" + MachinedInfo(bodyXN.InnerText); - if (MessageBox.Show(info, AppString.General.AppName, + if(MessageBox.Show(info, AppString.General.AppName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { XmlNode assetsXN = root.SelectSingleNode("assets"); - foreach (XmlNode itemXN in assetsXN.SelectNodes("item")) + foreach(XmlNode itemXN in assetsXN.SelectNodes("item")) { XmlNode nameXN = itemXN.SelectSingleNode("name"); - if (nameXN != null && nameXN.InnerText.Contains(".exe")) + if(nameXN != null && nameXN.InnerText.Contains(".exe")) { XmlNode urlXN = itemXN.SelectSingleNode("browser_download_url"); - using (DownloadDialog dlg = new DownloadDialog()) + using(DownloadDialog dlg = new DownloadDialog()) { dlg.Url = urlXN?.InnerText; dlg.FilePath = $@"{AppConfig.AppDataDir}\{webVer}.exe"; dlg.Text = AppString.General.AppName; - if (dlg.ShowDialog() == DialogResult.OK) + if(dlg.ShowDialog() == DialogResult.OK) { AppMessageBox.Show(AppString.Message.UpdateSucceeded, MessageBoxButtons.OK, MessageBoxIcon.Information); @@ -104,20 +104,20 @@ private static void UpdateText(bool isManual) void WriteFiles(string dirName, out string succeeded, out string failed) { succeeded = failed = ""; - foreach (string filePath in filePaths) + foreach(string filePath in filePaths) { - using (UAWebClient client = new UAWebClient()) + using(UAWebClient client = new UAWebClient()) { string fileUrl = $"{dirUrl}/{Path.GetFileName(filePath)}"; bool flag = client.WebStringToFile(filePath, fileUrl); string item = "\r\n ● " + Path.GetFileName(filePath); - if (flag) succeeded += item; + if(flag) succeeded += item; else failed += item; } } dirName = "\r\n\r\n" + dirName + ":"; - if (succeeded != "") succeeded = dirName + succeeded; - if (failed != "") failed = dirName + failed; + if(succeeded != "") succeeded = dirName + succeeded; + if(failed != "") failed = dirName + failed; } dirUrl = AppConfig.RequestUseGithub ? AppConfig.GithubTexts : AppConfig.GiteeTexts; @@ -132,12 +132,12 @@ void WriteFiles(string dirName, out string succeeded, out string failed) filePaths = Directory.GetFiles(AppConfig.LangsDir, "*.ini"); WriteFiles("Languages", out string succeeded2, out string failed2); - if (isManual) + if(isManual) { string failed = failed1 + failed2; string succeeded = succeeded1 + succeeded2; - if (failed != "") AppMessageBox.Show(AppString.Message.WebDataReadFailed + failed); - if (succeeded != "") AppMessageBox.Show(AppString.Message.DicUpdateSucceeded + succeeded, + if(failed != "") AppMessageBox.Show(AppString.Message.WebDataReadFailed + failed); + if(succeeded != "") AppMessageBox.Show(AppString.Message.DicUpdateSucceeded + succeeded, MessageBoxButtons.OK, MessageBoxIcon.Information); } } @@ -147,12 +147,12 @@ private static string MachinedInfo(string info) { string str = string.Empty; string[] lines = info.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None); - for (int m = 0; m < lines.Length; m++) + for(int m = 0; m < lines.Length; m++) { string line = lines[m]; - for (int n = 1; n <= 6; n++) + for(int n = 1; n <= 6; n++) { - if (line.StartsWith(new string('#', n) + ' ')) + if(line.StartsWith(new string('#', n) + ' ')) { line = line.Substring(n + 1); break; diff --git a/ContextMenuManager/Methods/UwpHelper.cs b/ContextMenuManager/Methods/UwpHelper.cs index 57289675..52067c2e 100644 --- a/ContextMenuManager/Methods/UwpHelper.cs +++ b/ContextMenuManager/Methods/UwpHelper.cs @@ -12,13 +12,13 @@ static class UwpHelper public static string GetPackageName(string uwpName) { - if (string.IsNullOrEmpty(uwpName)) return null; - using (RegistryKey packageKey = RegistryEx.GetRegistryKey(PackageRegPath)) + if(string.IsNullOrEmpty(uwpName)) return null; + using(RegistryKey packageKey = RegistryEx.GetRegistryKey(PackageRegPath)) { - if (packageKey == null) return null; - foreach (string packageName in packageKey.GetSubKeyNames()) + if(packageKey == null) return null; + foreach(string packageName in packageKey.GetSubKeyNames()) { - if (packageName.StartsWith(uwpName, StringComparison.OrdinalIgnoreCase)) + if(packageName.StartsWith(uwpName, StringComparison.OrdinalIgnoreCase)) { return packageName; } @@ -30,29 +30,29 @@ public static string GetPackageName(string uwpName) public static string GetRegPath(string uwpName, Guid guid) { string packageName = GetPackageName(uwpName); - if (packageName == null) return null; + if(packageName == null) return null; else return $@"{PackageRegPath}\{packageName}\Class\{guid:B}"; } public static string GetFilePath(string uwpName, Guid guid) { string regPath = GetRegPath(uwpName, guid); - if (regPath == null) return null; + if(regPath == null) return null; string packageName = GetPackageName(uwpName); - using (RegistryKey pKey = RegistryEx.GetRegistryKey($@"{PackagesRegPath}\{packageName}")) + using(RegistryKey pKey = RegistryEx.GetRegistryKey($@"{PackagesRegPath}\{packageName}")) { - if (pKey == null) return null; + if(pKey == null) return null; string dirPath = pKey.GetValue("Path")?.ToString(); string dllPath = Registry.GetValue(regPath, "DllPath", null)?.ToString(); string filePath = $@"{dirPath}\{dllPath}"; - if (File.Exists(filePath)) return filePath; + if(File.Exists(filePath)) return filePath; string[] names = pKey.GetSubKeyNames(); - if (names.Length == 1) + if(names.Length == 1) { filePath = "shell:AppsFolder\\" + names[0]; return filePath; } - if (Directory.Exists(dirPath)) return dirPath; + if(Directory.Exists(dirPath)) return dirPath; return null; } } diff --git a/ContextMenuManager/Methods/WinXHasher.cs b/ContextMenuManager/Methods/WinXHasher.cs index a51f5bd1..4bb07de5 100644 --- a/ContextMenuManager/Methods/WinXHasher.cs +++ b/ContextMenuManager/Methods/WinXHasher.cs @@ -209,11 +209,11 @@ public static void HashLnk(string lnkPath) private static string GetGeneralizePath(string filePath) { - if (string.IsNullOrEmpty(filePath)) return filePath; - foreach (var kv in GeneralizePathDic) + if(string.IsNullOrEmpty(filePath)) return filePath; + foreach(var kv in GeneralizePathDic) { string dirPath = Environment.ExpandEnvironmentVariables(kv.Key); - if (filePath.StartsWith(dirPath + "\\", StringComparison.OrdinalIgnoreCase)) + if(filePath.StartsWith(dirPath + "\\", StringComparison.OrdinalIgnoreCase)) { filePath = filePath.Replace(dirPath, kv.Value); break; } diff --git a/ContextMenuManager/Methods/XmlDicHelper.cs b/ContextMenuManager/Methods/XmlDicHelper.cs index 9379df78..ccb97da6 100644 --- a/ContextMenuManager/Methods/XmlDicHelper.cs +++ b/ContextMenuManager/Methods/XmlDicHelper.cs @@ -23,7 +23,7 @@ public static void ReloadDics() { XmlDocument LoadXml(string xmlPath) { - if (!File.Exists(xmlPath)) return null; + if(!File.Exists(xmlPath)) return null; try { XmlDocument doc = new XmlDocument(); @@ -32,7 +32,7 @@ XmlDocument LoadXml(string xmlPath) doc.LoadXml(xml); return doc; } - catch (Exception e) + catch(Exception e) { AppMessageBox.Show(e.Message + "\n" + xmlPath); return null; @@ -41,7 +41,7 @@ XmlDocument LoadXml(string xmlPath) void LoadDic(List dic, string webPath, string userPath, string defaultContent) { - if (!File.Exists(webPath)) File.WriteAllText(webPath, defaultContent, Encoding.Unicode); + if(!File.Exists(webPath)) File.WriteAllText(webPath, defaultContent, Encoding.Unicode); dic.Clear(); dic.Add(LoadXml(webPath)); dic.Add(LoadXml(userPath)); @@ -55,27 +55,27 @@ void LoadDic(List dic, string webPath, string userPath, string defa AppConfig.UserDetailedEditDic, Properties.Resources.DetailedEditDic); EnhanceMenuPathDic.Clear(); - for (int i = 0; i < 2; i++) + for(int i = 0; i < 2; i++) { XmlDocument doc = EnhanceMenusDic[i]; - if (doc?.DocumentElement == null) continue; - foreach (XmlNode pathXN in doc.SelectNodes("Data/Group/RegPath")) + if(doc?.DocumentElement == null) continue; + foreach(XmlNode pathXN in doc.SelectNodes("Data/Group/RegPath")) { - if (EnhanceMenuPathDic.ContainsKey(pathXN.InnerText)) continue; + if(EnhanceMenuPathDic.ContainsKey(pathXN.InnerText)) continue; EnhanceMenuPathDic.Add(pathXN.InnerText, i == 1); } } DetailedEditGuidDic.Clear(); - for (int i = 0; i < 2; i++) + for(int i = 0; i < 2; i++) { XmlDocument doc = DetailedEditDic[i]; - if (doc?.DocumentElement == null) continue; - foreach (XmlNode guidXN in doc.SelectNodes("Data/Group/Guid")) + if(doc?.DocumentElement == null) continue; + foreach(XmlNode guidXN in doc.SelectNodes("Data/Group/Guid")) { - if (GuidEx.TryParse(guidXN.InnerText, out Guid guid)) + if(GuidEx.TryParse(guidXN.InnerText, out Guid guid)) { - if (DetailedEditGuidDic.ContainsKey(guid)) continue; + if(DetailedEditGuidDic.ContainsKey(guid)) continue; DetailedEditGuidDic.Add(guid, i == 1); } } @@ -91,7 +91,7 @@ bool JudgeOne(XmlNode osXN) Version osVer = Environment.OSVersion.Version; int compare = osVer.CompareTo(ver); string symbol = ((XmlElement)osXN).GetAttribute("Compare"); - switch (symbol) + switch(symbol) { case ">": return compare > 0; @@ -108,9 +108,9 @@ bool JudgeOne(XmlNode osXN) } } - foreach (XmlNode osXN in itemXN.SelectNodes("OSVersion")) + foreach(XmlNode osXN in itemXN.SelectNodes("OSVersion")) { - if (!JudgeOne(osXN)) return false; + if(!JudgeOne(osXN)) return false; } return true; } @@ -118,10 +118,10 @@ bool JudgeOne(XmlNode osXN) public static bool FileExists(XmlNode itemXN) { //return true;//测试用 - foreach (XmlNode feXN in itemXN.SelectNodes("FileExists")) + foreach(XmlNode feXN in itemXN.SelectNodes("FileExists")) { string path = Environment.ExpandEnvironmentVariables(feXN.InnerText); - if (!File.Exists(path)) return false; + if(!File.Exists(path)) return false; } return true; } @@ -130,9 +130,9 @@ public static bool JudgeCulture(XmlNode itemXN) { //return true;//测试用 string culture = itemXN.SelectSingleNode("Culture")?.InnerText; - if (string.IsNullOrEmpty(culture)) return true; - if (culture.Equals(AppConfig.Language, StringComparison.OrdinalIgnoreCase)) return true; - if (culture.Equals(CultureInfo.CurrentUICulture.Name, StringComparison.OrdinalIgnoreCase)) return true; + if(string.IsNullOrEmpty(culture)) return true; + if(culture.Equals(AppConfig.Language, StringComparison.OrdinalIgnoreCase)) return true; + if(culture.Equals(CultureInfo.CurrentUICulture.Name, StringComparison.OrdinalIgnoreCase)) return true; return false; } @@ -142,7 +142,7 @@ public static byte[] ConvertToBinary(string value) { string[] strs = value.Split(' '); byte[] bs = new byte[strs.Length]; - for (int i = 0; i < strs.Length; i++) + for(int i = 0; i < strs.Length; i++) { bs[i] = Convert.ToByte(strs[i], 16); } @@ -153,7 +153,7 @@ public static byte[] ConvertToBinary(string value) public static RegistryValueKind GetValueKind(string type, RegistryValueKind defaultKind) { - switch (type.ToUpper()) + switch(type.ToUpper()) { case "REG_SZ": return RegistryValueKind.String; diff --git a/ContextMenuManager/Program.cs b/ContextMenuManager/Program.cs index b47096ac..a1a6dbdd 100644 --- a/ContextMenuManager/Program.cs +++ b/ContextMenuManager/Program.cs @@ -3,6 +3,7 @@ using ContextMenuManager.Methods; using System; using System.IO; +using System.Threading; using System.Windows.Forms; namespace ContextMenuManager @@ -22,10 +23,20 @@ static void Main() } } #endif - MyMainForm.InitColors(); + // 首先设置应用程序属性 Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); - if (SingleInstance.IsRunning()) return; + + // 然后设置Windows Forms同步上下文 + if (SynchronizationContext.Current == null) + { + SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext()); + } + + // 最后初始化DarkModeHelper(这时可能会有控件创建) + DarkModeHelper.Initialize(); + + if(SingleInstance.IsRunning()) return; AppString.LoadStrings(); Updater.PeriodicUpdate(); XmlDicHelper.ReloadDics(); diff --git a/ContextMenuManager/Properties/AssemblyInfo.cs b/ContextMenuManager/Properties/AssemblyInfo.cs index 295ae871..0476c266 100644 --- a/ContextMenuManager/Properties/AssemblyInfo.cs +++ b/ContextMenuManager/Properties/AssemblyInfo.cs @@ -11,5 +11,5 @@ [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("35190ec1-2515-488d-a2e9-825d6ff67aa2")] -[assembly: AssemblyVersion("3.6.0.0")] -[assembly: AssemblyFileVersion("3.6.0.0")] \ No newline at end of file +[assembly: AssemblyVersion("3.5.1.0")] +[assembly: AssemblyFileVersion("3.5.1.0")] \ No newline at end of file diff --git a/ContextMenuManager/Properties/PublishProfiles/Net9.0-AnyCPU.pubxml b/ContextMenuManager/Properties/PublishProfiles/Net9.0-AnyCPU.pubxml deleted file mode 100644 index 06efddf2..00000000 --- a/ContextMenuManager/Properties/PublishProfiles/Net9.0-AnyCPU.pubxml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - FileSystem - Release - Any CPU - net9.0-windows - ..\Output - win-x64 - false - true - false - false - none - - \ No newline at end of file diff --git a/ContextMenuManager/Properties/PublishProfiles/Net9.0-Win64.pubxml b/ContextMenuManager/Properties/PublishProfiles/Net9.0-Win64.pubxml new file mode 100644 index 00000000..369dfa92 --- /dev/null +++ b/ContextMenuManager/Properties/PublishProfiles/Net9.0-Win64.pubxml @@ -0,0 +1,18 @@ + + + + + FileSystem + Release + Any CPU + net9.0-windows + bin\Publish\ + win-x64 + false + true + false + none + + \ No newline at end of file