diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..23f9037 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +################################################################################ +# 此 .gitignore 文件已由 Microsoft(R) Visual Studio 自动创建。 +################################################################################ + +/.vs +/obj \ No newline at end of file diff --git a/ClassDiagram1.cd b/ClassDiagram1.cd new file mode 100644 index 0000000..9179d9b --- /dev/null +++ b/ClassDiagram1.cd @@ -0,0 +1,1719 @@ + + + + + + AAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAA= + RdcMan\About.cs + + + + + + EAQQAAAAAAACAAAAAIAAAAAAAAAAAAAAIAAAAAAAEAA= + RdcMan\AddCredentialsDialog.cs + + + + + + QgAgAAAACBAAAAAAIAAAAAAAAIAQAAAAAAAAAAACAAA= + RdcMan\AddNodeDialogHelper.cs + + + + + + AAAgAAAAAAAAGAAAAIQAAAAAAAQAAAAAAAAAAAAABAA= + RdcMan\ArgumentParser.cs + + + + + + ABAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAA= + RdcMan\CheckedMenuItem.cs + + + + + + EAAAAAwAAQRECYSACTAEAIAIAKAICixAAYIIEAgCCAA= + RdcMan\ClientPanel.cs + + + + + + ABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAA= + RdcMan\ClientSizeCheckedMenuItem.cs + + + + + + AAAAAAAAAAAAAAAEAAAAAAACAgAAAAAAAAAggAAAAAA= + RdcMan\ConfigForm\BaseSetting.cs + + + + + + + AAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAA= + RdcMan\ConfigForm\BoolSetting.cs + + + + + + AAAAAGACQAIAAgEIEAIAACCCAAAAAJAAAECAgABKDAA= + RdcMan\ConfigForm\BuiltInVirtualGroup.cs + + + + + + + ABQAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAA= + RdcMan\ConfigForm\BuiltInVirtualGroupCheckedMenuItem.cs + + + + + + BAAAAAAAAAAIAAAAAAAAAAAAAkAAAAAAAAAAAAAACAA= + RdcMan\ConfigForm\CommonDisplaySettings.cs + + + + + + AAAAAAAEAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAE= + RdcMan\ConfigForm\CommonNodeSettings.cs + + + + + + BAAAAAAAAQgAAAIAAAAAIAAAKgAAAAAAAAAAAACACAA= + RdcMan\ConfigForm\ConnectionSettings.cs + + + + + + AAAAAggIAAAAgAAAAAAAAEAAAAAAAAAAAAAAAAAAAAA= + RdcMan\ConfigForm\ConnectionSettingsTabPage.cs + + + + + + UAQAAIAAgAAAAAAUAgAAEAAIAgAAAAACAQIAAAAAAAA= + RdcMan\ConfigForm\CredentialsProfile.cs + + + + + + + CAAAAAAAAACAAgAACAAABAACAACAAACAAAAAgAAQAAA= + RdcMan\ConfigForm\CredentialsStore.cs + + + + + + AAAAAhAIAAAQAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAA= + RdcMan\ConfigForm\CredentialsTabPage.cs + + + + + + + AAAAAhAEAAIQIAAEAQSEhBAgAABQAAgIABEABRAREBA= + RdcMan\ConfigForm\CredentialsUI.cs + + + + + + ABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAABAA= + RdcMan\ConfigForm\CustomClientSizeCheckedMenuItem.cs + + + + + + AAAAAAAAAYEAAAEAACAgAAAAQAAAAAEAAAAiAAAgAAA= + RdcMan\ConfigForm\CustomSizeDialog.cs + + + + + + AAAAAAAAAAAAAAAIAAQAAAQCAAAAAAACQAAAgAAAAAA= + RdcMan\ConfigForm\DefaultSettingsGroup.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAA= + RdcMan\ConfigForm\DisplaySettingsTabPage.cs + + + + + + GAAAAgAIAAAAAAAAAAAAUAAAAAAAIEAAAAAQAAJAAAA= + RdcMan\ConfigForm\EncryptionSettingsTabPage.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAEAAAAAAAA= + RdcMan\ConfigForm\FileGroupPropertiesDialog.cs + + + + + + AAAAAAAIAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAA= + RdcMan\ConfigForm\FileGroupPropertiesTabPage.cs + + + + + + gAABAAAAAAAAAAIAAAAAIEAAIgAAAAAAAQAAEEAACAA= + RdcMan\ConfigForm\GatewaySettings.cs + + + + + + CAAAABAIAAABQAACAAAICAAAACAAAAAAQAAAAAAAAAA= + RdcMan\ConfigForm\GatewaySettingsTabPage.cs + + + + + + gIRAgCCAIFEEACoAQlIAgiATAYEAQAkAAABAQiAAAJg= + RdcMan\ConfigForm\GlobalOptionsDialog.cs + + + + + + BgCAAEEUMQSBAgYKAEIAcqCgIwiCYAFIQCBMKAggGAQ= + RdcMan\ConfigForm\GlobalSettings.cs + + + + + + AAAAAAAAAAIAAgAIAAAAAAAAAAAAAEAAAEAAgABAAAA= + RdcMan\ConfigForm\Group.cs + + + + + + BESEgiBAAgIEAgJQECQAAIADAAhNAJAAIADggCRCBAA= + RdcMan\ConfigForm\GroupBase.cs + + + + + + AAAACIADAQAAQAAAIAAAAQAECAAAACAAAEAAAICCAAA= + RdcMan\ConfigForm\GroupBasePropertiesDialog.cs + + + + + + AAAAAAgAAAAAAAAAAAAAAACAAAAAAAAAAAAAAABAAAA= + RdcMan\ConfigForm\GroupBasePropertiesTabPage.cs + + + + + + EgAAAACQAAAAQQIAAAAAIgAAIhAAAAACAQAAgBQACAA= + RdcMan\ConfigForm\LogonCredentials.cs + + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA= + RdcMan\ConfigForm\LogonCredentialsTabPage.cs + + + + + + EAQAAAAAAAAEAAAEAAAAAAAAAgAAAAICAQCAAAAAEAA= + RdcMan\ConfigForm\LogonSettingsDialog.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAACAAAAAAAA= + RdcMan\ConfigForm\PluginContext.cs + + + + + + + AAAgAAAAAAAAAAIAAAAAAAAAAAAAABAAAAAAAAAAAAA= + RdcMan\ConfigForm\PointHelper.cs + + + + + + AAAAAAAAAAAAAAAEAAAAAAACAAAAAAAAAAAAgAAAAAA= + RdcMan\ConfigForm\PointSetting.cs + + + + + + AAAAAAAABAAAAAAIAAAAAAAgAAAAAAAAAAAAAAAAAAA= + RdcMan\ConfigForm\Policies.cs + + + + + + AADAgMEUEQXBAAQICEYAUqCgAQiCYAFYgCBEKAxAECQ= + RdcMan\ConfigForm\Preferences.cs + + + + + + CAAAAAAAAAAADCAEAAAAAAACAgAAAAAAAAAAgAAAAAA= + RdcMan\ConfigForm\ProfileSetting.cs + + + + + + IABAAAAAAAAEAQAAAAAAAgAAAABAAAAAACAAAAAAAAA= + RdcMan\ConfigForm\RdcSettingsProvider.cs + + + + + + AgAAAIAAAAAAAAIAAAAwIAAAIgAAAAAAAAQAAAAACAA= + RdcMan\ConfigForm\RemoteDesktopSettings.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAA= + RdcMan\ConfigForm\Setting.cs + + + + + + CAAAAgAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAA= + RdcMan\ConfigForm\SettingAttribute.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgA= + RdcMan\ConfigForm\SettingExtensions.cs + + + + + + AgAAAAAAAAAAAgAEAAAAIAQCIgAABAAAEAAAgAAAAAA= + RdcMan\ConfigForm\SettingsGroup.cs + + + + + + AAAAAgAKAAAAgAAACAgAAAAAAAAAACAAABAAAAAAgBA= + RdcMan\ConfigForm\SettingsTabPage.cs + + + + + + + AAAAAgAIAAAAAAAAAAAAIAAAAAAAAAIAkBAAAAAAgBA= + RdcMan\ConfigForm\SettingsTabPage.cs + + + + + + + AAAgAAAAgAAAAAIAEAAAAAAAAAAAABAAAAAAAAAAAgA= + RdcMan\ConfigForm\SizeHelper.cs + + + + + + AAAAAAAAAAAAAAAEAAAAAAACAAAAAAAAAAAAgAAAAAA= + RdcMan\ConfigForm\SizeSetting.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAgAAAAAA= + RdcMan\ConfigForm\XmlSetting.cs + + + + + + AAAAAAAAAAAAAAIAAAAEIgAAIgAAAAAAEAAAAAAACAA= + RdcMan\Configuration\EncryptionSettings.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAgAAAAAA= + RdcMan\Configuration\EnumSetting.cs + + + + + + AAAAAAAAAAQAAAAAAAAAAAAAAAgAAAAAAAAAAACAAAA= + RdcMan\ConnectAsDialog.cs + + + + + + AAQAAAAAABAAAgAAAAYAAAAAAABAAEAAQAAAAAAIAAA= + RdcMan\ConnectedGroup.cs + + + + + + + AAAAACAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAA= + RdcMan\ConnectedServerRef.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAA= + RdcMan\ConnectServersDialog.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAgAAAAA= + RdcMan\ConnectToDialog.cs + + + + + + AAAAAEAAAAAAAAAAEAAAAAAAAAAAAEAAQACAAAAAAAA= + RdcMan\ConnectToGroup.cs + + + + + + + AAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\ControlExtensions.cs + + + + + + AACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\Ctrl\RdpCtrl.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAEAAAAAAAA= + RdcMan\DefaultGroupPropertiesDialog.cs + + + + + + ABQAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAA= + RdcMan\DelegateCheckedMenuItem.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\DelegateMenuItem.cs + + + + + + CAABAAAAAAACAgAEIAAAAAAAIAAgQAQEACAIIAAAAAA= + RdcMan\Encryption.cs + + + + + + AAQAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAgAAAAAAA= + RdcMan\EnumMenuItem.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAA= + RdcMan\FavoriteServerRef.cs + + + + + + AAAAAEAAAAAAAgAQAAAAAAAAAAAAAEAAQAAAAAAIBAA= + RdcMan\FavoritesGroup.cs + + + + + + + AACACCAAAQIAAgAIACAAAAACAAgAAIACEAAAiAAAQBA= + RdcMan\FileGroup.cs + + + + + + AgAAAAAAAAAAAAIAAAAAIAAAIgAAAAAAAAAAAAAACAA= + RdcMan\FileGroupSettings.cs + + + + + + AAQAAAAAAAAAAAAAAAAAAAACAAAAAAEAAAAAAAAAAAA= + RdcMan\FileRequiredMenuItem.cs + + + + + + AAAABCAAAAAFAAAAAIAAIAggAAAAAAAAgAAAAAAAAAA= + RdcMan\FindServersDialog.cs + + + + + + AAQEBBAgAAQMAABKMAQEEAEKg4IVLYABmAEgAERCIAA= + RdcMan\FormTools.cs + + + + + + AAAAAEAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\GroupChangedEventArgs.cs + + + + + + CAAAAAAAAAAAAAIAAAAAIBAAIAAAAAAAAAAAAAAgAAA= + RdcMan\GroupDisplaySettings.cs + + + + + + AAAAAAAIAAABAAAAAAABAAIAAAAAAAAAAAAAAAAAAAA= + RdcMan\GroupDisplaySettingsTabPage.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAEAAAAQAAA= + RdcMan\GroupPropertiesDialog.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\GroupPropertiesTabPage.cs + + + + + + AgAAAAAAAAAAAAIAAAAAIAAAIgAAAAAAAACAAAAACAE= + RdcMan\GroupSettings.cs + + + + + + AAAAAAAAACAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\HeaderColumnClickEventArgs.cs + + + + + + AAIQDAAAAAAAECAAAAAAAAACAAAAAAAAQAQAMAAEDAE= + RdcMan\Helpers.cs + + + + + + ACAAAAAAAAQAQAAAAAAAAAAKAgAAAAAAAAAAAABAABA= + RdcMan\HotKeyBox.cs + + + + + + + AAAAAAAAAAAAAAAAAAkAAAAAAAAAAAAAAAACAABIEAA= + RdcMan\ImportServersPropertiesPage.cs + + + + + + AAIAIAAkCEAgABAAAAQACAoAEAAgAEAQAAAAAwAAAAA= + RdcMan\Interface\InheritanceControl.cs + + + + + + AAAAAAAAAIAAAAAAAAAAAAAAAAACAAAAAAAAgAAAAAA= + RdcMan\Interface\InheritSettingsType.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAA= + RdcMan\Interface\IntSetting.cs + + + + + + AAEACQAAACADBCBEAKCAEAACgABAEgEQIAhBAQABAAA= + RdcMan\ListSessionsForm.cs + + + + + + AAAAAAAAAAAAAgAAAAAAAAACAAAAAAAAAAAAgAAAAAA= + RdcMan\ListSetting.cs + + + + + + AAAgAAAABAAABAIAAABAoCAAIgAAABAAAEABAGAACAA= + RdcMan\LocalResourcesSettings.cs + + + + + + AAIQAgA4AAAAAAAAAAAAQIAAAAAgAAAAAAEAAAAAAAA= + RdcMan\LocalResourcesTabPage.cs + + + + + + AAAAAAAAAAAEAIAAAAACAAACAAAAAAAAAAACABEAAAA= + RdcMan\Log.cs + + + + + + AABEAAAFIAACAAAAAAABAAAABAAAAQAAQAIQAAAAAAA= + RdcMan\LongRunningActionForm.cs + + + + + + AoG2sQg0CYQZoS8QCDGB0SYQRAAsE0ogISKEWggkmgA= + RdcMan\MainForm.cs + + + + + + + AAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\MenuExtensions.cs + + + + + + gAAAAAAAAQkAAAAAACAQAAAAgCAAAAAAAAAQAAAAAAA= + RdcMan\MenuHelper.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAA= + RdcMan\Models\ConnectionStateChangedEventArgs.cs + + + + + + AAAAAAAQAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAEAAAA= + RdcMan\Models\DeferDecryptionItem.cs + + + + + + AAAAAAAAAAAAAIIAAAAAAAAAAAAAAAAAAAAAAQAAAAA= + RdcMan\Models\EnableTabsEventArgs.cs + + + + + + AAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAgAAAAA= + RdcMan\Models\ServerChangedEventArgs.cs + + + + + + AAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAA= + RdcMan\Models\SettingProperty.cs + + + + + + AAAAAABAAQAAAACAgAQACAgAAAAAADIAAQAAAABAAEA= + RdcMan\NodeHelper.cs + + + + + + AAAAAAAAIAAQAAAAAAEAAAAAACAAAAAQAAAAAAAAAAA= + RdcMan\NodePropertiesDialog.cs + + + + + + ACJAAAAIAAAAAAAAEAQAAAAAAAAAAQAAAAAAAABCAAA= + RdcMan\NodePropertiesPage.cs + + + + + + + ACAAAAAAAAQAQAAAAAAAAAAAAAAAAAAAEEBAAABAABA= + RdcMan\NumericTextBox.cs + + + + + + + QgQQAAQFZBhaCYgMQLoEmAIoADACAAAEeAYEiBAQuEA= + RdcMan\OcxClient\RdpClient.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAA= + RdcMan\OcxClient\RdpClient5.cs + + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAA= + RdcMan\OcxClient\RdpClient6.cs + + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAA= + RdcMan\OcxClient\RdpClient7.cs + + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\OcxClient\RdpClient8.cs + + + + + + + QAAAAAAAAAAAAAAQAAAAAAACEgAABAAAAAAAgAAAAAA= + RdcMan\PasswordSetting.cs + + + + + + + CCLAAAAAAAAAQQBAoBAAAAAOAAAihUAACgEEFAAABEA= + RdcMan\Program.cs + + + + + + AAAAAAAAAAAAAEAAAAAAAAAAACAAAAIAAAAAAAAAAAA= + RdcMan\QuickConnectDialog.cs + + + + + + AAAAAAABAAABAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA= + RdcMan\QuickConnectTabPage.cs + + + + + + AAACIAAAAAAAAAABGAAAQBAwAAAgAQAAAACCQAAAGAQ= + RdcMan\RdcBaseForm.cs + + + + + + ACAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAABAABA= + RdcMan\RdcCheckBox.cs + + + + + + + ABAAAAAAQAAQAIAAAAEQAgAAAIAABAIAAAABAACAAAA= + RdcMan\RdcDialog.cs + + + + + + ACAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQEAYAAA= + RdcMan\RdcListView.cs + + + + + + AAQAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAA= + RdcMan\RdcMenuItem.cs + + + + + + AAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\RdcMenuStrip.cs + + + + + + ACAAAAAAAACAQAAAAAAAAAAAAAAAAAAAAAAAAABAABA= + RdcMan\RdcNumericUpDown.cs + + + + + + + ACAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAABAABA= + RdcMan\RdcRadioButton.cs + + + + + + + ACAAAAAAAACAQAAAAAAAAAAAAAAAAAAAAAAAAABAABA= + RdcMan\RdcTextBox.cs + + + + + + + NQZIAiDABEYMAAAYEIAAIJACAgAGQVACEUCAoAbSAAA= + RdcMan\RdcTreeNode.cs + + + + + + + IIAEAAABAAAwAQAJAAAQAAAKAQIAAEAABBAAAAAQAAA= + RdcMan\RdgFile.cs + + + + + + QAAAAEAAABIAAgAIAAYAAAAAAABBAFAAQAAAAAAIBAA= + RdcMan\RecentlyUsedGroup.cs + + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\RecentlyUsedServerRef.cs + + + + + + AACAAAAAAAAAAAAQAAAAAAAAAAAAAEAAQAAAAAAIBAA= + RdcMan\ReconnectGroup.cs + + + + + + + BAQAIAIAACAAgAAAAAQAAAAAAAAQAAIAAEAAAAYAAAA= + RdcMan\ReconnectServerRef.cs + + + + + + AAQAAgAAAAAAAAAAAYAAAAACAAAgAAAAAAAAAAAAAAA= + RdcMan\RemoteDesktopsMenuItem.cs + + + + + + AAAAAgAIAAAgAAAAAAAAAEAAAAAAAAAAAAAAAAACAAg= + RdcMan\RemoteDesktopTabPage.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAQQAABAAAAAA= + RdcMan\RemoteSessionInfo.cs + + + + + + IAAAAAAQAAAAAABAQAACAAAAAAAAEAAAAAAAAAABAAA= + RdcMan\RemoteSessions.cs + + + + + + AAAAAAAAAAAAAgAEAAAAAgACAAAEAEAAAAKggQAAIAA= + RdcMan\Rule.cs + + + + + + AgAAAAAAAAAABgAAAAAAQgACAAAAAMAAAAAAgAAAIAA= + RdcMan\RuleGroup.cs + + + + + + AAAAAAAAIAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAA= + RdcMan\RuleProperty.cs + + + + + + EAQQAAAAAAACAAAAgAAAAAACAAAAAAAAAAAAAAAAEAA= + RdcMan\SaveCredentialsDialog.cs + + + + + + AAAAAAAAAAAAAAIAAAACIAAAIgAAAAAAAAAAAAAACAA= + RdcMan\SecuritySettings.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\SecuritySettingsTabPage.cs + + + + + + AAAAAAAAAACAAAAAAAAAAAEAAAAAAAAACAAAAYAAAAI= + RdcMan\SelectActiveServerForm.cs + + + + + + AAQAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAgAAAAAA= + RdcMan\SelectedNodeMenuItem.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\SelectedNodeMenuItem.cs + + + + + + AAAAAAACBACEEAAEAAEAAIACgAIAAAAAgAgKIAAAAAE= + RdcMan\SelectServersDialogBase.cs + + + + + + AAAAAAAAAAAEAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\SendKeys.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAA= + RdcMan\SendKeysMenuItem.cs + + + + + + hnQ8kiYJgYJG0kjNUsYAEJECWAAEecIkk2SsxqRSAoc= + RdcMan\Server.cs + + + + + + gjAAECBAAAAAwBDAAAIAABAAEAAAAAAgAQAIAiACAAA= + RdcMan\ServerBase.cs + + + + + + AAAAAAAAAAAAAAAAQIAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\ServerBox.cs + + + + + + AAAAAAAAAAAAAAIAAAAAIAAAIAAAAAAAAAAAAAAAAAA= + RdcMan\ServerDisplaySettings.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\ServerDisplaySettingsTabPage.cs + + + + + + ABEAIAAkgQQBARAAQCACAAxQhICAEAAAAACEAAAAEAQ= + RdcMan\ServerForm.cs + + + + + + + IABAAAIABAAAAAAgAAAAAAAAAABAAAAQIAAAAiAAAAA= + RdcMan\ServerLabel.cs + + + + + + AAQAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAA= + RdcMan\ServerMenuItem.cs + + + + + + AAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAQUAAA= + RdcMan\ServerPropertiesDialog.cs + + + + + + AAAAAgAJAAAAAAAAAAEQAAAAAVAACAQAQAIAAgBAAAg= + RdcMan\ServerPropertiesTabPage.cs + + + + + + hjQIEAAAAAIEwQBMUAIAAJAAEAAGQAAgAUAIgiRCAAA= + RdcMan\ServerRef.cs + + + + + + AgAAEAAAAAACAAKAAAAAIAAIIgAAAAAAAAAAAAAACAA= + RdcMan\ServerSettings.cs + + + + + + IMBQCiAQjQAAmQGAgipRAACAALAgMIAA8AGDEQAPGkA= + RdcMan\ServerTree.cs + + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAA= + RdcMan\ServerTreeLocationMenuItem.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAA= + RdcMan\ServerTreeVisibilityMenuItem.cs + + + + + + AAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAABAAAAAAAA= + RdcMan\SessionListSortComparer.cs + + + + + + + AAAAAQAAAQJAAgAIACAAAQACACJAAMAAAEgAgAECBAA= + RdcMan\SmartGroup.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAEAAAAQAAA= + RdcMan\SmartGroupPropertiesDialog.cs + + + + + + AABkCgBMEAAAAAAgAAgAAAAAAAAAAQAAAAAAAgAIACA= + RdcMan\SmartGroupPropertiesTabPage.cs + + + + + + AgAAAAAAAAAAAAIAAAAAIAAAIgAAAAAAAAAAAAAACAA= + RdcMan\SmartGroupSettings.cs + + + + + + AAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\SmartServerRef.cs + + + + + + AAAgAAAEAAAAAEAAAEAAAAAAAAgAAAAAAAMAAAAAAAA= + RdcMan\SortExtensions.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAA= + RdcMan\SortGroupsCheckedMenuItem.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAA= + RdcMan\SortServersCheckedMenuItem.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAA= + RdcMan\StringSetting.cs + + + + + + AAACAAAAAAAAAAAAAQAAAAAAAhAAAAAAIAIAAIQgSAA= + RdcMan\StringUtilities.cs + + + + + + AQAAAgBIAAAAAAAAAAAAAgAAAAAAAAIACAQAAABAAAA= + RdcMan\TabbedSettingsDialog.cs + + + + + + AAAAAAAAEAAAAAAAAAAAAAAAAAAAAEAAAAAAAABAAAA= + RdcMan\TemporaryServer.cs + + + + + + AAQAAAAAADAEACQAAAAAAAAAAAAAAHACgAABgAAAAAA= + RdcMan\ThrottledAction.cs + + + + + + + AAIAAAAAACAEAAQAAAAAAAQAAAAAAAAAAAAEABAAIAA= + RdcMan\ThrottledOperation.cs + + + + + + + AEAAAEg4ACAEAJIEpAAAAAAmAAQEACAgAAAAAEAAAAA= + RdcMan\ThumbnailLayout.cs + + + + + + + ACAAAAECAEAAXAAAAAAAAAAAwAAAAAAAAAAACABAABA= + RdcMan\ValueComboBox.cs + + + + + + + AAAAgAAAAAIAAAJAAgAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\VirtualGroup.cs + + + + + + AAAAAACABAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAA= + RdcMan\Configuration\Current.cs + + + + + + AAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\Configuration\DisplaySizeElement.cs + + + + + + AAACAAAAAAAAIAAAAAAAAAAAAAABAAAAAAAQAAAAAAA= + RdcMan\Configuration\DisplaySizeElementCollection.cs + + + + + + AAAAAAAAAAAAAIIAAQAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\Configuration\LoggingElement.cs + + + + + + AAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAACAAAA= + RdcMan\Configuration\ProgramUpdateElement.cs + + + + + + AAAAAAAAAAAAAAAAAQAAAAAAAAAAAQAAIAAIAAAAAAA= + RdcMan\Configuration\RdcManSection.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAA= + RdcMan\Configuration\WarningThresholdsElement.cs + + + + + + BAAAAEAAAAAAAgAQAAAAAAIAAAAAAEAAQAAQAAAIBAA= + RdcMan\Ctrl\InternalGroup.cs + + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\Ctrl\InternalServerRef.cs + + + + + + AAAADCQIAAAAggABgYAgAAAQAIAABAAAABACACAiAHA= + Win32\Constants.cs + + + + + + AAEAAAAAAAAABAAAAAAAAAACAAAAAAAAAAAAAAAAAAA= + Win32\Crypto.cs + + + + + + AAAAgAAAAAQAAAAAIAAAAAAAAEAAgAAAAAAAAAAAAAA= + Win32\Kernel.cs + + + + + + gABAAABAAAAAQBAAAAgACAAAAAAAiAAACCAABgAAAKA= + Win32\Messages.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Win32\Structs.cs + + + + + + AAAAAABAAAAAAAACKCAAAAAAAACAAAAAAQAAgASgiAA= + Win32\User.cs + + + + + + AAAAAAAAAAAAAAAAAAgAAAQAAAAAAAAAAAAAAAAAAAA= + Win32\Util.cs + + + + + + AAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAgAAAAAEAAQ= + Win32\WinTrust.cs + + + + + + AAAAAAAAAAAAAAACAAEQAAEAAIQAABEgQAAAEAAAABA= + Win32\WinTrustData.cs + + + + + + AgAAAAAAAAAAABAAAAAACAAAAAAAAAAAAAAAEAAAAAA= + Win32\WinTrustFileInfo.cs + + + + + + AAAACAAQAAgAAAAAAAACBAAAAAAAEAAAAgAAAAABAAA= + Win32\Wts.cs + + + + + + AAgAAAAAQAAAAgAAEAIAAAACAAAAAAAAAAAAiAAAAAA= + RdcMan\Interface\IBuiltInVirtualGroup.cs + + + + + + AAAAAAAAAAAQAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAA= + RdcMan\Interface\ICredentialsTabPage.cs + + + + + + QAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\Interface\IDeferDecryption.cs + + + + + + EAQAAAAAAAAAAAAAAAAAAAAAAgAAAAACAQAAAAAAAAA= + RdcMan\Interface\ILogonCredentials.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAQAAAAQAAAAAAAAAAAAAA= + RdcMan\Interface\IMainForm.cs + + + + + + ACBAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAACAAA= + RdcMan\Interface\INodePropertiesPage.cs + + + + + + AAQAACAAAAAAAAAgAAAAAQAAAAAAAAABAAAhAAAAAAA= + RdcMan\Interface\IPlugin.cs + + + + + + AAAAAAAAAACCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\Interface\IPluginContext.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\Interface\IRdpClient.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAA= + RdcMan\Interface\IServerRefFactory.cs + + + + + + AAAQAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAIAAA= + RdcMan\Interface\IServerTree.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAACAgAAAAAAAAAAgAAAAAA= + RdcMan\Interface\ISetting.cs + + + + + + AAAAAAAAAACAAEAAAAAAAAAAAAAAAAQAAAAAAAAAAAA= + RdcMan\Interface\ISettingControl.cs + + + + + + AAAAAgAIAACAAAAACAAAAAAAAAAAAAIAAAAAAAAAAAA= + RdcMan\Interface\ISettingsTabPage.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAgAAAAA= + RdcMan\Interface\IUndockedServerForm.cs + + + + + + AAAAAEAAAAAAAAIAAACAAAAAQAAECAAIABQAAAAAAAA= + RdcMan\Interface\ImageConstants.cs + + + + + + AAAAAAAAAAAAAAQAAACAAAAAAAAAAAAAAAAAAAEAAAA= + RdcMan\Interface\InheritanceMode.cs + + + + + + AIIgIBGAgBAZAUQaAEABCIpAQABlBkADwAQEAIEBIhA= + RdcMan\MenuNames.cs + + + + + + AAAAAAAAAAAACAAAAAAAAAAAgAAAAAAAQAAAAAAAAAA= + RdcMan\Models\ChangeType.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAQAAA= + RdcMan\Models\ConnectionType.cs + + + + + + AAAAEAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAEAAAA= + RdcMan\Models\ControlVisibility.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAECAAAA= + RdcMan\Models\EncryptionMethod.cs + + + + + + AAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAIAAAQEAAAA= + RdcMan\Models\LogonCredentialsDialogOptions.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAABAAA= + RdcMan\Models\ProfileScope.cs + + + + + + IABAAIAAQAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\Models\SaveResult.cs + + + + + + AAAACAAAAAAAAAAAAAAEAAAAAAAAAAAABAAAAAAAAAA= + RdcMan\NodeVisitorResult.cs + + + + + + AAAAAAAQgAAAAAABAABAAAAAAAAABAAAAAAAAAEAAAA= + RdcMan\OperationBehavior.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAIAAAAEAAAA= + RdcMan\ReconnectServerOptions.cs + + + + + + IAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAA= + RdcMan\RuleGroupOperator.cs + + + + + + ABAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAA= + RdcMan\RuleOperator.cs + + + + + + AAAAEAAEAAAAAACAAAAAQAAAAAAAAAAAAAAAAAAAAAA= + RdcMan\ServerProperty.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAEAg= + RdcMan\SortOrder.cs + + + + + + AEAAAAAAAAAAAAAAAAAAAAABAAAEAAAAAAAAAEAAAAg= + Win32\WinTrustDataChoice.cs + + + + + + AEgAIAQAAABAAQAAIABAABAABAAAAACEAAAAAAACAAA= + Win32\WinTrustDataProvFlags.cs + + + + + + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAEAAAA= + Win32\WinTrustDataRevocationChecks.cs + + + + + + AAAAAAAACAAAAQAAAAAAAAAAAAAAAAABAAACAACAAAA= + Win32\WinTrustDataStateAction.cs + + + + + + CAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAIAAAAEAAAA= + Win32\WinTrustDataUIChoice.cs + + + + + + AAAAAAAAAAAAAAQEAAAAAAAAAAAAAAAAAAAAAAAAAAA= + Win32\WinTrustDataUIContext.cs + + + + + + AQAAAAAAAAAAAgAQAAAAACgIAgAAEAAAAAAAIIAAAAA= + Win32\WinVerifyTrustResult.cs + + + + + + AAAAAAAAAAAAAAAAAAAABAAQAAAAAAAAAAAAAAAAAAA= + RdcMan\HeaderColumnClickEventHandler.cs + + + + \ No newline at end of file diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs index 3baa6fd..12eed09 100644 --- a/Properties/AssemblyInfo.cs +++ b/Properties/AssemblyInfo.cs @@ -12,4 +12,4 @@ [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] [assembly: ComVisible(false)] -[assembly: AssemblyVersion("2.90.1420.0")] +[assembly: AssemblyVersion("2.92.1430.0")] diff --git a/RDCMan.csproj b/RDCMan.csproj index fb24acc..30885db 100644 --- a/RDCMan.csproj +++ b/RDCMan.csproj @@ -5,6 +5,7 @@ WinExe True net48 + AnyCPU;x64 9.0 @@ -14,31 +15,42 @@ Resources\app.ico app.manifest + + x64 - + + + + + + - - + + + + + + RdcLib\AxInterop.MSTSCLib.dll + + + + RdcLib\Interop.MSTSCLib.dll + + - - RdcLib\AxMSTSCLib.dll - - - RdcLib\MSTSCLib.dll - \ No newline at end of file diff --git a/RDCMan.csproj.user b/RDCMan.csproj.user new file mode 100644 index 0000000..e73f123 --- /dev/null +++ b/RDCMan.csproj.user @@ -0,0 +1,255 @@ + + + + + + Form + + + Form + + + Component + + + Component + + + Component + + + Component + + + Form + + + Component + + + Form + + + Form + + + Component + + + Component + + + Form + + + Form + + + Component + + + Component + + + Component + + + Component + + + Component + + + Form + + + Component + + + Component + + + Form + + + Component + + + Form + + + Form + + + Component + + + Component + + + Form + + + Component + + + Component + + + Component + + + Form + + + Component + + + Component + + + Form + + + Form + + + Form + + + Form + + + Component + + + Component + + + Form + + + Component + + + Form + + + Component + + + Form + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Component + + + Form + + + Component + + + Form + + + Component + + + Form + + + Component + + + Component + + + Component + + + Form + + + Component + + + Component + + + Form + + + Component + + + Component + + + Component + + + Component + + + Component + + + Form + + + Component + + + Component + + + Component + + + Form + + + Component + + + \ No newline at end of file diff --git a/RDCMan.sln b/RDCMan.sln index 8084781..fde9f55 100644 --- a/RDCMan.sln +++ b/RDCMan.sln @@ -1,24 +1,31 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.32407.337 + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.4.33103.184 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RDCMan", "RDCMan.csproj", "{C862011B-2A9C-4F7F-BE06-2E7C3F5A2E04}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RDCMan", "RDCMan.csproj", "{E4F06803-E397-4AD5-A013-9B2E0935CF65}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {C862011B-2A9C-4F7F-BE06-2E7C3F5A2E04}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C862011B-2A9C-4F7F-BE06-2E7C3F5A2E04}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C862011B-2A9C-4F7F-BE06-2E7C3F5A2E04}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C862011B-2A9C-4F7F-BE06-2E7C3F5A2E04}.Release|Any CPU.Build.0 = Release|Any CPU + {E4F06803-E397-4AD5-A013-9B2E0935CF65}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E4F06803-E397-4AD5-A013-9B2E0935CF65}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E4F06803-E397-4AD5-A013-9B2E0935CF65}.Debug|x64.ActiveCfg = Debug|x64 + {E4F06803-E397-4AD5-A013-9B2E0935CF65}.Debug|x64.Build.0 = Debug|x64 + {E4F06803-E397-4AD5-A013-9B2E0935CF65}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E4F06803-E397-4AD5-A013-9B2E0935CF65}.Release|Any CPU.Build.0 = Release|Any CPU + {E4F06803-E397-4AD5-A013-9B2E0935CF65}.Release|x64.ActiveCfg = Release|x64 + {E4F06803-E397-4AD5-A013-9B2E0935CF65}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {FE1A1A73-2A1D-4B02-88BD-C4B2A4BF9A5A} + SolutionGuid = {B47E664F-6F1E-4053-8FCF-4A2DDB9B143B} EndGlobalSection EndGlobal diff --git a/README.md b/README.md index f0d7064..29effae 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,21 @@ -# RDCMan v2.90.1420.0 +# RDCMan v2.92.1430.0 微软远程桌面管理工具 Remote Desktop Connection Manager -reflect base on v2.90.1420.0 -[Official download link 发布时间: 2022 年 1 月 27 日](https://docs.microsoft.com/zh-cn/sysinternals/downloads/rdcman) +reflect base on v2.92.1430.0 +[Official download link 发布时间: 2023 年 1 月 25 日](https://docs.microsoft.com/zh-cn/sysinternals/downloads/rdcman) -汉化,及本土优化 +汉化,及本土优化 + +Use .Net Framework 4.8 + +## 控件版本说明 +需要 System32\mstscax.dll +产生 AxInterop.MSTSCLib.dll 和 Interop.MSTSCLib.dll +新的包含最新的 rdp client 10~11, +然后 引用程序集; +也可以使用 之前的 AxMSTSCLib.dll 和 MSTSCLib.dll -Use .Net Framework 4.8 ## 个性化更改的记录 没找到 支持 RdpClient10 的 lib , 注销掉了此部分支持代码 @@ -21,7 +29,7 @@ Use .Net Framework 4.8 影响文件: CredentialsUI.cs::InitPassword line:121 并 注释常量 DummyPassword -2. 增加汉化说明 +2. 增加汉化说明 影响文件: About.cs::InitializeComponent line:20/35/42 @@ -51,6 +59,22 @@ Use .Net Framework 4.8 影响文件: GlobalOptionsDialog.cs::CreateServerTreePage line:352/367/373/385 +8. `查找服务器` 界面和功能优化 +影响文件: + SelectServersDialogBase.cs line:10,27,35,46,53,63-66,89,92 + FindServersDialog.cs line:22,59,77 + +9. 未停靠时双击激活远程桌面显示 +影响文件: + SeverBox.cs::OnMouseDown line:23 新增 + +10. 双点击缩略图激活远程桌面显示 +影响文件: + SeverBox.cs::DbClickShow line:35 新增 + CiientPanel.cs::OnMouseDown line:459 新增 + + + 999. 内置组 (配置完成,功能未完成) 影响文件: GlobalSettings.cs<>ShowBuiltInGroup line:437 diff --git a/RdcLib/AxInterop.MSTSCLib.dll b/RdcLib/AxInterop.MSTSCLib.dll new file mode 100644 index 0000000..55ff0c4 Binary files /dev/null and b/RdcLib/AxInterop.MSTSCLib.dll differ diff --git a/RdcLib/AxMSTSCLib.dll b/RdcLib/AxMSTSCLib.dll deleted file mode 100644 index 0ceefd7..0000000 Binary files a/RdcLib/AxMSTSCLib.dll and /dev/null differ diff --git a/RdcLib/Interop.MSTSCLib.dll b/RdcLib/Interop.MSTSCLib.dll new file mode 100644 index 0000000..b141c7c Binary files /dev/null and b/RdcLib/Interop.MSTSCLib.dll differ diff --git a/RdcLib/MSTSCLib.dll b/RdcLib/MSTSCLib.dll deleted file mode 100644 index 63813a0..0000000 Binary files a/RdcLib/MSTSCLib.dll and /dev/null differ diff --git a/RdcMan/About.cs b/RdcMan/About.cs index 3be3fb0..5066efc 100644 --- a/RdcMan/About.cs +++ b/RdcMan/About.cs @@ -17,7 +17,7 @@ private void InitializeComponent(bool isLarge) { Location = new Point(53, 31), Width = num2 - FormTools.LabelWidth, AutoSize = true, - Text = "Copyright © 2022 Microsoft. By Julian Burger, lzp 汉化" + Text = "Copyright © 2023 Microsoft. By Julian Burger" }; LinkLabel linkLabel = new LinkLabel { Location = new Point(53, 48), diff --git a/RdcMan/AddNodeDialogHelper.cs b/RdcMan/AddNodeDialogHelper.cs index 9588436..4c9f9a7 100644 --- a/RdcMan/AddNodeDialogHelper.cs +++ b/RdcMan/AddNodeDialogHelper.cs @@ -161,4 +161,4 @@ private static void NotifyUserFileNeeded() { FormTools.InformationDialog("ӷ/֮ǰһеķֻļ (File->Open) 򴴽һļ (File->New)"); } } -} \ No newline at end of file +} diff --git a/RdcMan/ArgumentParser.cs b/RdcMan/ArgumentParser.cs index dd94bd5..0e83d7f 100644 --- a/RdcMan/ArgumentParser.cs +++ b/RdcMan/ArgumentParser.cs @@ -1,49 +1,62 @@ using System; using System.Collections.Generic; -namespace RdcMan { - public class ArgumentParser { +namespace RdcMan +{ + public class ArgumentParser + { public Dictionary Switches = new Dictionary(StringComparer.OrdinalIgnoreCase); public Dictionary SwitchValues = new Dictionary(StringComparer.OrdinalIgnoreCase); public List PlainArgs = new List(); - public void AddSwitch(string name, bool requiresValue) { + public void AddSwitch(string name, bool requiresValue) + { Switches[name] = requiresValue; } - public void Parse() { + public void Parse() + { string[] commandLineArgs = Environment.GetCommandLineArgs(); - for (int i = 1; i < commandLineArgs.Length; i++) { - if (IsSwitch(commandLineArgs[i])) { + for (int i = 1; i < commandLineArgs.Length; i++) + { + if (IsSwitch(commandLineArgs[i])) + { string key = commandLineArgs[i].Substring(1); - if (!Switches.TryGetValue(key, out var value)) { + if (!Switches.TryGetValue(key, out var value)) + { throw new ArgumentException("Unexpected switch: " + commandLineArgs[i]); } string value2 = string.Empty; - if (value) { - if (i >= commandLineArgs.Length - 1) { + if (value) + { + if (i >= commandLineArgs.Length - 1) + { throw new ArgumentException("Switch " + commandLineArgs[i] + " requires an argument"); } value2 = commandLineArgs[++i]; } SwitchValues[key] = value2; } - else { + else + { PlainArgs.Add(commandLineArgs[i]); } } } - public bool HasSwitch(string name) { + public bool HasSwitch(string name) + { string value; return SwitchValues.TryGetValue(name, out value); } - private bool IsSwitch(string arg) { + private bool IsSwitch(string arg) + { char c = arg[0]; - if (c != '/') { + if (c != '/') + { return c == '-'; } return true; diff --git a/RdcMan/BaseSetting.cs b/RdcMan/BaseSetting.cs index c2b1bde..4fdff89 100644 --- a/RdcMan/BaseSetting.cs +++ b/RdcMan/BaseSetting.cs @@ -1,24 +1,30 @@ using System.Xml; -namespace RdcMan { - public abstract class BaseSetting : ISetting { +namespace RdcMan +{ + public abstract class BaseSetting : ISetting + { internal T Value; - protected BaseSetting(object o) { + protected BaseSetting(object o) + { Value = ((o != null) ? ((T)o) : default(T)); } public abstract void ReadXml(XmlNode xmlNode, RdcTreeNode node); - public virtual void WriteXml(XmlTextWriter tw, RdcTreeNode node) { + public virtual void WriteXml(XmlTextWriter tw, RdcTreeNode node) + { tw.WriteString(Value.ToString()); } - public virtual void Copy(ISetting source) { + public virtual void Copy(ISetting source) + { Value = ((BaseSetting)source).Value; } - public override string ToString() { + public override string ToString() + { return Value.ToString(); } } diff --git a/RdcMan/BoolSetting.cs b/RdcMan/BoolSetting.cs index b77050f..134dc53 100644 --- a/RdcMan/BoolSetting.cs +++ b/RdcMan/BoolSetting.cs @@ -1,12 +1,16 @@ using System.Xml; -namespace RdcMan { - public class BoolSetting : Setting { +namespace RdcMan +{ + public class BoolSetting : Setting + { public BoolSetting(object o) - : base(o) { + : base(o) + { } - public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) { + public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) + { base.Value = bool.Parse(xmlNode.FirstChild.InnerText); } } diff --git a/RdcMan/BuiltInVirtualGroup.cs b/RdcMan/BuiltInVirtualGroup.cs index 54ceb29..3de9fbc 100644 --- a/RdcMan/BuiltInVirtualGroup.cs +++ b/RdcMan/BuiltInVirtualGroup.cs @@ -3,8 +3,10 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { - internal abstract class BuiltInVirtualGroup : VirtualGroup, IBuiltInVirtualGroup where TServerRef : ServerRef { +namespace RdcMan +{ + internal abstract class BuiltInVirtualGroup : VirtualGroup, IBuiltInVirtualGroup where TServerRef : ServerRef + { protected new static Dictionary NodeActions; string IBuiltInVirtualGroup.Text => base.Text; @@ -33,115 +35,152 @@ public bool IsInTree { protected virtual bool IsVisibilityConfigurable => true; - void IBuiltInVirtualGroup.ReadXml(XmlNode xmlNode, FileGroup fileGroup, ICollection errors) { + void IBuiltInVirtualGroup.ReadXml(XmlNode xmlNode, FileGroup fileGroup, ICollection errors) + { ReadXml(xmlNode, fileGroup, errors); } - void IBuiltInVirtualGroup.WriteXml(XmlTextWriter tw, FileGroup fileGroup) { + void IBuiltInVirtualGroup.WriteXml(XmlTextWriter tw, FileGroup fileGroup) + { WriteXml(tw, fileGroup); } - bool IBuiltInVirtualGroup.ShouldWriteNode(ServerRef serverRef, FileGroup file) { + bool IBuiltInVirtualGroup.ShouldWriteNode(ServerRef serverRef, FileGroup file) + { return ShouldWriteNode(serverRef, file); } - static BuiltInVirtualGroup() { + static BuiltInVirtualGroup() + { NodeActions = new Dictionary(GroupBase.NodeActions); - NodeActions["server"] = delegate (XmlNode childNode, RdcTreeNode parent, ICollection errors) { + NodeActions["server"] = delegate(XmlNode childNode, RdcTreeNode parent, ICollection errors) + { TreeNode treeNode = ServerTree.Instance.FindNodeByName(childNode.InnerText); if (treeNode != null && treeNode is Server serverBase) + { (parent as BuiltInVirtualGroup).AddReference(serverBase); + } }; } - public override void OnRemoving() { + public override void OnRemoving() + { Hide(); } - public sealed override bool ConfirmRemove(bool askUser) { - FormTools.InformationDialog("Use the View menu to hide the " + base.Text + " group"); + public sealed override bool ConfirmRemove(bool askUser) + { + FormTools.InformationDialog("ʹáͼ˵ " + base.Text + " "); return false; } - public sealed override bool CanDropOnTarget(RdcTreeNode targetNode) { + public sealed override bool CanDropOnTarget(RdcTreeNode targetNode) + { return false; } - public override bool CanDropServers() { + public override bool CanDropServers() + { return false; } - public sealed override bool CanRemove(bool popUI) { + public sealed override bool CanRemove(bool popUI) + { return false; } - public override void DoPropertiesDialog(Form parentForm, string activeTabName) { + public override void DoPropertiesDialog(Form parentForm, string activeTabName) + { throw new NotImplementedException(); } - internal override void ReadXml(XmlNode xmlNode, ICollection errors) { + internal override void ReadXml(XmlNode xmlNode, ICollection errors) + { throw new NotImplementedException(); } - internal override void WriteXml(XmlTextWriter tw) { + internal override void WriteXml(XmlTextWriter tw) + { throw new NotImplementedException(); } - protected virtual void ReadXml(XmlNode xmlNode, FileGroup fileGroup, ICollection errors) { - if (!string.IsNullOrEmpty(XmlNodeName)) { + protected virtual void ReadXml(XmlNode xmlNode, FileGroup fileGroup, ICollection errors) + { + if (!string.IsNullOrEmpty(XmlNodeName)) + { ReadXml(NodeActions, xmlNode, errors); if (base.Properties.Expanded.Value) + { Expand(); + } } } - protected virtual void WriteXml(XmlTextWriter tw, FileGroup file) { + protected virtual void WriteXml(XmlTextWriter tw, FileGroup file) + { if (string.IsNullOrEmpty(XmlNodeName)) + { return; - + } tw.WriteStartElement(XmlNodeName); if (file == null) + { WriteXmlSettingsGroups(tw); - - foreach (TreeNode node in base.Nodes) { + } + foreach (TreeNode node in base.Nodes) + { TServerRef val = node as TServerRef; if (ShouldWriteNode(val, file)) + { tw.WriteElementString("server", val.ServerNode.FullPath); + } } tw.WriteEndElement(); } - protected virtual bool ShouldWriteNode(RdcTreeNode node, FileGroup file) { + protected virtual bool ShouldWriteNode(RdcTreeNode node, FileGroup file) + { return node.FileGroup == file; } - public virtual TServerRef AddReference(ServerBase serverBase) { + public virtual TServerRef AddReference(ServerBase serverBase) + { if (serverBase == null) + { return null; - + } Server serverNode = serverBase.ServerNode; TServerRef val = serverNode.FindServerRef(); - if (val == null) { + if (val == null) + { val = base.ServerRefFactory.Create(serverNode) as TServerRef; ServerTree.Instance.AddNode(val, this); } return val; } - protected void UpdateVisibleInTree(bool isVisible) { - if (isVisible) { - if (base.TreeView == null) { + protected void UpdateVisibleInTree(bool isVisible) + { + if (isVisible) + { + if (base.TreeView == null) + { ServerTree.Instance.AddNode(this, ServerTree.Instance.RootNode); Expand(); - ServerTree.Instance.Operation(OperationBehavior.RestoreSelected, delegate { + ServerTree.Instance.Operation(OperationBehavior.RestoreSelected, delegate + { ServerTree.Instance.SortBuiltinGroups(); }); } } else if (base.TreeView != null) + { ServerTree.Instance.RemoveNode(this); + } if (IsVisibilityConfigurable) + { Program.Preferences.SetBuiltInGroupVisibility(this, isVisible); + } } } } diff --git a/RdcMan/BuiltInVirtualGroupCheckedMenu.cs b/RdcMan/BuiltInVirtualGroupCheckedMenu.cs index 95b40d9..9601edf 100644 --- a/RdcMan/BuiltInVirtualGroupCheckedMenu.cs +++ b/RdcMan/BuiltInVirtualGroupCheckedMenu.cs @@ -1,17 +1,22 @@ -namespace RdcMan { - internal class BuiltInVirtualGroupCheckedMenuItem : CheckedMenuItem { +namespace RdcMan +{ + internal class BuiltInVirtualGroupCheckedMenuItem : CheckedMenuItem + { private IBuiltInVirtualGroup _group; public BuiltInVirtualGroupCheckedMenuItem(IBuiltInVirtualGroup group) - : base(group.Text) { + : base(group.Text) + { _group = group; } - protected override void CheckChanged(bool isChecked) { + protected override void CheckChanged(bool isChecked) + { _group.IsInTree = isChecked; } - public override void Update() { + public override void Update() + { base.Checked = _group.IsInTree; } } diff --git a/RdcMan/ChangeType.cs b/RdcMan/ChangeType.cs index 5e07717..bf59cb1 100644 --- a/RdcMan/ChangeType.cs +++ b/RdcMan/ChangeType.cs @@ -1,8 +1,10 @@ using System; -namespace RdcMan { +namespace RdcMan +{ [Flags] - public enum ChangeType { + public enum ChangeType + { InvalidateUI = 1, TreeChanged = 3, PropertyChanged = 5 diff --git a/RdcMan/CheckedMenuItem.cs b/RdcMan/CheckedMenuItem.cs index 277ffd9..8e9b939 100644 --- a/RdcMan/CheckedMenuItem.cs +++ b/RdcMan/CheckedMenuItem.cs @@ -1,10 +1,14 @@ -namespace RdcMan { - internal abstract class CheckedMenuItem : RdcMenuItem { - protected CheckedMenuItem(string text) { +namespace RdcMan +{ + internal abstract class CheckedMenuItem : RdcMenuItem + { + protected CheckedMenuItem(string text) + { Text = text; } - protected sealed override void OnClick() { + protected sealed override void OnClick() + { CheckChanged(!base.Checked); } diff --git a/RdcMan/ClientPanel.cs b/RdcMan/ClientPanel.cs index de86705..0361895 100644 --- a/RdcMan/ClientPanel.cs +++ b/RdcMan/ClientPanel.cs @@ -6,15 +6,17 @@ using System.Windows.Forms; using Win32; -namespace RdcMan { - internal class ClientPanel : Control { +namespace RdcMan +{ + internal class ClientPanel : Control + { private static readonly int ThumbnailLabelHeight; private const int ThumbnailHorzSpace = 8; private const int ThumbnailVertSpace = 6; - private readonly Dictionary _layoutHash; + private Dictionary _layoutHash; private readonly Dictionary _groupScrollPosition; @@ -22,6 +24,8 @@ internal class ClientPanel : Control { private Size _savedSize; + private Size _savedBeforeSize; + private int _thumbnailUnitWidth; private int _thumbnailUnitHeight; @@ -30,15 +34,40 @@ internal class ClientPanel : Control { private readonly VScrollBar _verticalScrollBar; + private bool _resizing; + + public bool Resizing + { + get + { + return _resizing; + } + set + { + _resizing = value; + if (_resizing) + { + _savedBeforeSize = base.ClientSize; + } + else + { + OnClientSizeChanged(null); + } + } + } + private int UnitHeight => Math.Max(_thumbnailUnitHeight + ThumbnailLabelHeight + ThumbnailVertSpace, 1); - static ClientPanel() { + static ClientPanel() + { ThumbnailLabelHeight = ServerLabel.Height; } - public ClientPanel() { + public ClientPanel() + { base.TabStop = false; - _verticalScrollBar = new VScrollBar { + _verticalScrollBar = new VScrollBar + { Dock = DockStyle.Right, TabStop = false, Visible = false @@ -53,22 +82,27 @@ public ClientPanel() { _layoutHash = new Dictionary(); } - private void OnGroupChanged(GroupChangedEventArgs obj) { + private void OnGroupChanged(GroupChangedEventArgs obj) + { if ((obj.Group == ServerTree.Instance.RootNode && !obj.ChangeType.HasFlag(ChangeType.PropertyChanged)) || (obj.Group != ServerTree.Instance.RootNode && !obj.ChangeType.HasFlag(ChangeType.InvalidateUI))) + { return; - + } ThumbnailLayout layout = _layout; GroupBase groupBase = layout?.Group; bool flag = false; - if (layout != null) { + if (layout != null) + { ThumbnailLayout thumbnailLayout = CreateThumbnailLayout(groupBase); - if (!obj.ChangeType.HasFlag(ChangeType.PropertyChanged) && thumbnailLayout.Equals(layout)) { + if (!obj.ChangeType.HasFlag(ChangeType.PropertyChanged) && thumbnailLayout.Equals(layout)) + { Log.Write("ֲ䣬ػ"); thumbnailLayout.Dispose(); UpdateNonLayoutSettings(layout); } - else { + else + { HideGroup(groupBase); layout.Dispose(); _layoutHash[groupBase] = thumbnailLayout; @@ -77,13 +111,19 @@ private void OnGroupChanged(GroupChangedEventArgs obj) { } } TreeNode group = obj.Group; - if (group != ServerTree.Instance.RootNode) { - while (group != null) { - if (group == groupBase) { + if (group != ServerTree.Instance.RootNode) + { + while (group != null) + { + if (group == groupBase) + { if (!flag) + { break; + } } - else if (_layoutHash.TryGetValue(group, out ThumbnailLayout value)) { + else if (_layoutHash.TryGetValue(group, out ThumbnailLayout value)) + { _layoutHash.Remove(group); value.Dispose(); } @@ -91,87 +131,118 @@ private void OnGroupChanged(GroupChangedEventArgs obj) { } } else + { ResetLayout(); - + } if (layout == null && ServerTree.Instance.SelectedNode is ServerBase serverBase) + { UpdateNonLayoutSettings(serverBase.ServerNode); + } } - private void UpdateNonLayoutSettings(ThumbnailLayout shownLayout) { - shownLayout.LabelArray.ForEach(delegate (ServerLabel l) { + private void UpdateNonLayoutSettings(ThumbnailLayout shownLayout) + { + shownLayout.LabelArray.ForEach(delegate(ServerLabel l) + { UpdateNonLayoutSettings(l.Server); }); } - private void UpdateNonLayoutSettings(Server server) { + private void UpdateNonLayoutSettings(Server server) + { server.SetClientSizeProperties(); server.EnableDisableClient(); } - private void OnServerChanged(ServerChangedEventArgs obj) { + private void OnServerChanged(ServerChangedEventArgs obj) + { if (!obj.ChangeType.HasFlag(ChangeType.PropertyChanged)) + { return; - - using (Helpers.Timer("thumbnail ServerChanged handler")) { + } + using (Helpers.Timer("thumbnail ServerChanged handler")) + { Server serverNode = obj.Server.ServerNode; - foreach (ThumbnailLayout value in _layoutHash.Values) { + foreach (ThumbnailLayout value in _layoutHash.Values) + { ServerLabel[] labelArray = value.LabelArray; - foreach (ServerLabel serverLabel in labelArray) { + foreach (ServerLabel serverLabel in labelArray) + { if (serverLabel.Server == serverNode) + { serverLabel.CopyServerData(); + } } } } } - public RdcTreeNode GetSelectedNode(Control active) { + public RdcTreeNode GetSelectedNode(Control active) + { if (active is ServerLabel serverLabel) + { return serverLabel.AssociatedNode; + } return null; } - private void ResetLayout() { - foreach (ThumbnailLayout item in _layoutHash.Values.Where((ThumbnailLayout l) => l != _layout).ToList()) { + private void ResetLayout() + { + foreach (ThumbnailLayout item in _layoutHash.Values.Where((ThumbnailLayout l) => l != _layout).ToList()) + { item.Dispose(); _layoutHash.Remove(item.Group); } } [Conditional("DEBUG")] - private void AssertValid() { - foreach (Control control in base.Controls) { } + private void AssertValid() + { + foreach (Control control in base.Controls) + { + } } - public void ShowGroup(GroupBase group) { + public void ShowGroup(GroupBase group) + { bool flag = true; if (_layout != null && _layout.Group == group) + { flag = false; - - if (!_layoutHash.TryGetValue(group, out _layout)) { + } + if (!_layoutHash.TryGetValue(group, out _layout)) + { _layout = CreateThumbnailLayout(group); _layoutHash.Add(group, _layout); } ComputeScrollBarLimits(); - if (flag) { + if (flag) + { if (!_groupScrollPosition.TryGetValue(group, out var value)) + { value = 0; + } SetScrollPosition(value); } _thumbnailDrawn = new bool[_layout.NodeCount]; DrawThumbnails(group); } - private ThumbnailLayout CreateThumbnailLayout(GroupBase group) { - using (Helpers.Timer("creating thumbnail layout for {0}", group.Text)) { + private ThumbnailLayout CreateThumbnailLayout(GroupBase group) + { + using (Helpers.Timer("creating thumbnail layout for {0}", group.Text)) + { ThumbnailLayout thumbnailLayout = new ThumbnailLayout(group); int num; - if (Program.Preferences.ThumbnailSizeIsInPixels) { + if (Program.Preferences.ThumbnailSizeIsInPixels) + { Size thumbnailSize = Program.Preferences.ThumbnailSize; _thumbnailUnitWidth = thumbnailSize.Width; _thumbnailUnitHeight = thumbnailSize.Height; num = ComputeNumAcross(base.ClientSize.Width, _thumbnailUnitWidth); } - else { + else + { num = 100 / Program.Preferences.ThumbnailPercentage; _thumbnailUnitWidth = (base.ClientSize.Width - _verticalScrollBar.Width - ThumbnailHorzSpace) / num - ThumbnailHorzSpace; _thumbnailUnitHeight = (base.ClientSize.Height - ThumbnailVertSpace) / num - ThumbnailLabelHeight - ThumbnailVertSpace; @@ -182,39 +253,49 @@ private ThumbnailLayout CreateThumbnailLayout(GroupBase group) { } } - public void HideGroup(GroupBase group) { - if (_layout != null) { + public void HideGroup(GroupBase group) + { + if (_layout != null) + { if (_layout.Group != group) + { return; - + } _groupScrollPosition[group] = _verticalScrollBar.Value; - try { + try + { ServerLabel serverLabel = Program.TheForm.ActiveControl as ServerLabel; ServerLabel[] labelArray = _layout.LabelArray; - foreach (ServerLabel serverLabel2 in labelArray) { + foreach (ServerLabel serverLabel2 in labelArray) + { if (serverLabel == serverLabel2) + { Program.TheForm.ActiveControl = this; - + } serverLabel2.Server.Hide(); base.Controls.Remove(serverLabel2); } } - finally { + finally + { _layout = null; } } _verticalScrollBar.Hide(); } - public void ScrollServerIntoView(ServerLabel label) { + public void ScrollServerIntoView(ServerLabel label) + { int thumbnailIndex = label.ThumbnailIndex; if (!_layout.IsServerPositionComputed(thumbnailIndex)) + { ComputeThumbnailPosition(label); - + } Rectangle thumbnailAbsoluteBounds = _layout.GetThumbnailAbsoluteBounds(thumbnailIndex); int num = thumbnailAbsoluteBounds.Bottom + ServerLabel.Height; int num2 = base.ClientSize.Height; - if (thumbnailAbsoluteBounds.Top < _verticalScrollBar.Value || num > _verticalScrollBar.Value + num2 - 1) { + if (thumbnailAbsoluteBounds.Top < _verticalScrollBar.Value || num > _verticalScrollBar.Value + num2 - 1) + { int value = _verticalScrollBar.Value; int scrollPosition = ((value >= thumbnailAbsoluteBounds.Top) ? thumbnailAbsoluteBounds.Top : (num - num2 + 1)); SetScrollPosition(scrollPosition); @@ -222,12 +303,14 @@ public void ScrollServerIntoView(ServerLabel label) { } } - private void ComputeScrollBarLimits() { + private void ComputeScrollBarLimits() + { int unitHeight = UnitHeight; int num = (_layout.LowestTileY + 1) * unitHeight; int num2 = base.ClientSize.Height; int num3 = num - num2; - if (_verticalScrollBar.Visible = num3 > 0) { + if (_verticalScrollBar.Visible = num3 > 0) + { _verticalScrollBar.LargeChange = num2; _verticalScrollBar.SmallChange = unitHeight; _verticalScrollBar.Maximum = num; @@ -235,35 +318,44 @@ private void ComputeScrollBarLimits() { } } - private int GetServerHeight(int serverScale) { + private int GetServerHeight(int serverScale) + { return _thumbnailUnitHeight * serverScale + (ThumbnailLabelHeight + ThumbnailVertSpace) * (serverScale - 1); } - private void SetScrollPosition(int value) { + private void SetScrollPosition(int value) + { _verticalScrollBar.Value = Math.Min(value, _verticalScrollBar.Maximum - _verticalScrollBar.LargeChange + 1); } - private void DrawThumbnails(GroupBase group) { + private void DrawThumbnails(GroupBase group) + { if (_layout.NodeCount == 0) + { return; - - using (Helpers.Timer("drawing {0} ({1} thumbnails)", group.Text, _layout.NodeCount)) { + } + using (Helpers.Timer("drawing {0} ({1} thumbnails)", group.Text, _layout.NodeCount)) + { DrawThumbnails(_verticalScrollBar.Value, _verticalScrollBar.Value, base.ClientSize.Height); } } - private void DrawThumbnails(int oldValue, int newValue, int height) { - foreach (int item in GetUndrawnServersInViewport(newValue, height)) { + private void DrawThumbnails(int oldValue, int newValue, int height) + { + foreach (int item in GetUndrawnServersInViewport(newValue, height)) + { _thumbnailDrawn[item - 1] = true; ServerLabel label = _layout.LabelArray[item - 1]; if (!_layout.IsServerPositionComputed(item)) + { ComputeThumbnailPosition(label); - + } DrawThumbnail(label, oldValue); } } - private void DrawThumbnail(ServerLabel label, int windowTop) { + private void DrawThumbnail(ServerLabel label, int windowTop) + { Rectangle thumbnailAbsoluteBounds = _layout.GetThumbnailAbsoluteBounds(label.ThumbnailIndex); int num = thumbnailAbsoluteBounds.Top - windowTop; int top = num + ThumbnailLabelHeight - 1; @@ -274,28 +366,32 @@ private void DrawThumbnail(ServerLabel label, int windowTop) { base.Controls.Add(label); label.Show(); server.Show(); - if (Program.TheForm.ActiveControl == this && label.ThumbnailIndex == _layout.FocusedServerIndex) { + if (Program.TheForm.ActiveControl == this && label.ThumbnailIndex == _layout.FocusedServerIndex) + { label.Focus(); _layout.FocusedServerIndex = 0; } } - private unsafe void DrawAndScroll(int oldValue, int newValue) { - using (Helpers.Timer("scrolling thumbnails {0} => {1}", oldValue, newValue)) { + private unsafe void DrawAndScroll(int oldValue, int newValue) + { + using (Helpers.Timer("scrolling thumbnails {0} => {1}", oldValue, newValue)) + { Size clientSize = base.ClientSize; int num = clientSize.Height; DrawThumbnails(oldValue, newValue, num); - if (oldValue != newValue) { + if (oldValue != newValue) + { Structs.RECT rECT = default(Structs.RECT); rECT.top = 0; rECT.bottom = clientSize.Height; rECT.left = 0; rECT.right = _verticalScrollBar.Left - 1; Structs.RECT rECT2 = default(Structs.RECT); - rECT.top = -oldValue; - rECT.bottom = _verticalScrollBar.Maximum - oldValue; - rECT.left = 0; - rECT.right = _verticalScrollBar.Left - 1; + rECT2.top = -oldValue; + rECT2.bottom = _verticalScrollBar.Maximum - oldValue; + rECT2.left = 0; + rECT2.right = _verticalScrollBar.Left - 1; Structs.RECT* ptr = &rECT; Structs.RECT* ptr2 = &rECT2; User.ScrollWindowEx(base.Handle, 0, oldValue - newValue, (IntPtr)ptr2, (IntPtr)ptr, (IntPtr)(void*)null, (IntPtr)(void*)null, 7u); @@ -303,32 +399,45 @@ private unsafe void DrawAndScroll(int oldValue, int newValue) { } } - protected override void OnClientSizeChanged(EventArgs e) { + protected override void OnClientSizeChanged(EventArgs e) + { if (Program.TheForm.IsFullScreen) + { return; - + } Size clientSize = base.ClientSize; - try { + try + { TreeNode selectedNode = ServerTree.Instance.SelectedNode; - if (!(selectedNode is GroupBase groupBase)) { - if (selectedNode is ServerBase serverBase) { + if (!(selectedNode is GroupBase groupBase)) + { + if (selectedNode is ServerBase serverBase) + { if (serverBase.IsThumbnail) + { throw new InvalidOperationException("ѡͼ"); - + } serverBase.ServerNode.SetNormalView(); - if (clientSize.Width != _savedSize.Width || clientSize.Height != _savedSize.Height) + if (!Resizing && (_savedBeforeSize.Width != _savedSize.Width || _savedBeforeSize.Height != _savedSize.Height)) + { serverBase.ServerNode.Resize(); + } } ResetLayout(); } - else { - if (_layout == null || _layout.Group != groupBase) { + else + { + if (_layout == null || _layout.Group != groupBase) + { return; } - if (Program.Preferences.ThumbnailSizeIsInPixels) { + if (Program.Preferences.ThumbnailSizeIsInPixels) + { int unitWidth = Program.Preferences.ThumbnailSize.Width; - if (ComputeNumAcross(clientSize.Width, unitWidth) == ComputeNumAcross(_savedSize.Width, unitWidth)) { - if (_savedSize.Height != clientSize.Height) { + if (ComputeNumAcross(clientSize.Width, unitWidth) == ComputeNumAcross(_savedSize.Width, unitWidth)) + { + if (_savedSize.Height != clientSize.Height) + { int value = _verticalScrollBar.Value; ComputeScrollBarLimits(); DrawAndScroll(value, _verticalScrollBar.Value); @@ -341,13 +450,37 @@ protected override void OnClientSizeChanged(EventArgs e) { ShowGroup(groupBase); } } - finally { + finally + { _savedSize = clientSize; } } - protected override void OnMouseWheel(MouseEventArgs e) { - if (ServerTree.Instance.SelectedNode is GroupBase) { + protected override void OnMouseDown(MouseEventArgs e) { + if (e.Button == MouseButtons.Left && e.Clicks == 2) { + ServerBox box = null; + + foreach (var c in Controls) { + if (c.GetType() == typeof(ServerBox)) { + Point l = ((ServerBox)c).Location; + Size s = ((ServerBox)c).ClientSize; + if ((l.X <= e.X && (l.X + s.Width) >= e.X) && (l.Y <= e.Y && (l.Y + s.Height) >= e.Y)) { + box = (ServerBox)c; + break; + } + } + } + if (box != null) + box.DbClickShow(); + } + else + base.OnMouseDown(e); + } + + protected override void OnMouseWheel(MouseEventArgs e) + { + if (ServerTree.Instance.SelectedNode is GroupBase) + { int value = _verticalScrollBar.Value; int val = value - Math.Sign(e.Delta) * _verticalScrollBar.SmallChange; SetScrollPosition(Math.Max(0, val)); @@ -355,13 +488,15 @@ protected override void OnMouseWheel(MouseEventArgs e) { } } - private int ComputeNumAcross(int totalWidth, int unitWidth) { + private int ComputeNumAcross(int totalWidth, int unitWidth) + { totalWidth -= _verticalScrollBar.Width; totalWidth -= ThumbnailHorzSpace; return totalWidth / (unitWidth + ThumbnailHorzSpace); } - private void ComputeThumbnailPosition(ServerLabel label) { + private void ComputeThumbnailPosition(ServerLabel label) + { int value = label.Server.DisplaySettings.ThumbnailScale.Value; int num = _thumbnailUnitWidth * value + ThumbnailHorzSpace * (value - 1); int serverHeight = GetServerHeight(value); @@ -373,67 +508,84 @@ private void ComputeThumbnailPosition(ServerLabel label) { _layout.SetThumbnailAbsoluteBounds(thumbnailIndex, num4, num5, num, serverHeight); } - private IEnumerable GetUndrawnServersInViewport(int position, int height) { + private IEnumerable GetUndrawnServersInViewport(int position, int height) + { HashSet hashSet = new HashSet(); if (_layout.NodeCount == 0) + { return hashSet; - + } int upperBound = _layout.ServerLayoutToIndex.GetUpperBound(1); int unitHeight = UnitHeight; int num = position / unitHeight; int val = (position + height - 1) / unitHeight; val = Math.Min(val, _layout.ServerLayoutToIndex.GetUpperBound(0)); - for (int i = num; i <= val; i++) { + for (int i = num; i <= val; i++) + { ServerLabel serverLabel; - for (int j = 0; j <= upperBound; j += serverLabel.Server.DisplaySettings.ThumbnailScale.Value) { + for (int j = 0; j <= upperBound; j += serverLabel.Server.DisplaySettings.ThumbnailScale.Value) + { int num2 = _layout.ServerLayoutToIndex[i, j]; if (num2 == 0) + { break; - + } if (!_thumbnailDrawn[num2 - 1]) + { hashSet.Add(num2); - + } serverLabel = _layout.LabelArray[num2 - 1]; } } return hashSet; } - private void OnScroll(object sender, ScrollEventArgs e) { + private void OnScroll(object sender, ScrollEventArgs e) + { DrawAndScroll(e.OldValue, e.NewValue); } - public void RecordLastFocusedServerLabel(ServerLabel label) { + public void RecordLastFocusedServerLabel(ServerLabel label) + { _layout.FocusedServerIndex = label.ThumbnailIndex; } - protected override void OnEnter(EventArgs e) { + protected override void OnEnter(EventArgs e) + { bool flag = true; base.OnEnter(e); - if (_layout != null) { - if (_layout.NodeCount > 0) { + if (_layout != null) + { + if (_layout.NodeCount > 0) + { ServerLabel serverLabel = _layout.LabelArray[_layout.FocusedServerIndex - 1]; - if (serverLabel.Parent == this) { + if (serverLabel.Parent == this) + { serverLabel.Focus(); flag = false; } } } - else if (ServerTree.Instance.SelectedNode is ServerBase serverBase) { + else if (ServerTree.Instance.SelectedNode is ServerBase serverBase) + { serverBase.Focus(); flag = false; } - if (flag) { + if (flag) + { Focus(); } } - protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { ServerLabel serverLabel = Program.TheForm.ActiveControl as ServerLabel; - if (serverLabel == null) { + if (serverLabel == null) + { if (_layout == null || Program.TheForm.ActiveControl != this) + { return base.ProcessCmdKey(ref msg, keyData); - + } serverLabel = _layout.LabelArray[_layout.FocusedServerIndex - 1]; } _layout.EnsureTabIndex(); @@ -442,71 +594,85 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { int num = _layout.ServerTileX[thumbnailIndex]; int num2 = _layout.ServerTileY[thumbnailIndex]; int num3 = serverLabel.TabIndex; - switch (keyData) { - case Keys.Tab: - case Keys.Tab | Keys.Shift: - ServerTree.Instance.Focus(); + switch (keyData) + { + case Keys.Tab: + case Keys.Tab | Keys.Shift: + ServerTree.Instance.Focus(); + return true; + case Keys.Left: + if (--num3 == 0) + { return true; - case Keys.Left: - if (--num3 == 0) - return true; - - thumbnailIndex = _layout.TabIndexToServerIndex[num3]; - num = _layout.ServerTileX[thumbnailIndex]; - num2 = _layout.ServerTileY[thumbnailIndex]; - break; - case Keys.Right: - if (++num3 > _layout.NodeCount) - return true; - - thumbnailIndex = _layout.TabIndexToServerIndex[num3]; - num = _layout.ServerTileX[thumbnailIndex]; - num2 = _layout.ServerTileY[thumbnailIndex]; - break; - case Keys.Up: - if (--num2 < 0) - return true; - break; - case Keys.Down: - num2 += value; - if (num2 > _layout.LowestTileY) - return true; - break; - case Keys.Home: - num = 0; - num2 = 0; - break; - case Keys.End: - num = _layout.ServerLayoutToIndex.GetUpperBound(1); - num2 = _layout.LowestTileY; - break; - case Keys.Prior: - if (num2 == 0) - return true; - - int val3 = (int)Math.Floor((double)serverLabel.Top / (double)UnitHeight); - int val4 = base.Height / UnitHeight; - int num5 = Math.Max(val3, val4); - num2 = Math.Max(0, num2 - num5); - break; - case Keys.Next: - if (num2 == _layout.LowestTileY) - return true; - - int val = (int)Math.Floor((double)(serverLabel.Top + GetServerHeight(value)) / (double)UnitHeight); - int val2 = base.Height / UnitHeight; - int num4 = Math.Max(val, val2); - num2 = Math.Min(_layout.LowestTileY, num2 + num4); - break; - - default: - return base.ProcessCmdKey(ref msg, keyData); + } + thumbnailIndex = _layout.TabIndexToServerIndex[num3]; + num = _layout.ServerTileX[thumbnailIndex]; + num2 = _layout.ServerTileY[thumbnailIndex]; + break; + case Keys.Right: + if (++num3 > _layout.NodeCount) + { + return true; + } + thumbnailIndex = _layout.TabIndexToServerIndex[num3]; + num = _layout.ServerTileX[thumbnailIndex]; + num2 = _layout.ServerTileY[thumbnailIndex]; + break; + case Keys.Up: + if (--num2 < 0) + { + return true; + } + break; + case Keys.Down: + num2 += value; + if (num2 > _layout.LowestTileY) + { + return true; + } + break; + case Keys.Home: + num = 0; + num2 = 0; + break; + case Keys.End: + num = _layout.ServerLayoutToIndex.GetUpperBound(1); + num2 = _layout.LowestTileY; + break; + case Keys.Prior: + { + if (num2 == 0) + { + return true; + } + int val3 = (int)Math.Floor((double)serverLabel.Top / (double)UnitHeight); + int val4 = base.Height / UnitHeight; + int num5 = Math.Max(val3, val4); + num2 = Math.Max(0, num2 - num5); + break; + } + case Keys.Next: + { + if (num2 == _layout.LowestTileY) + { + return true; + } + int val = (int)Math.Floor((double)(serverLabel.Top + GetServerHeight(value)) / (double)UnitHeight); + int val2 = base.Height / UnitHeight; + int num4 = Math.Max(val, val2); + num2 = Math.Min(_layout.LowestTileY, num2 + num4); + break; + } + default: + return base.ProcessCmdKey(ref msg, keyData); } - while (true) { + while (true) + { thumbnailIndex = _layout.ServerLayoutToIndex[num2, num]; if (thumbnailIndex != 0) + { break; - + } num--; } serverLabel = _layout.LabelArray[thumbnailIndex - 1]; diff --git a/RdcMan/ClientSizeCheckedMenuItem.cs b/RdcMan/ClientSizeCheckedMenuItem.cs index d877dde..75bc942 100644 --- a/RdcMan/ClientSizeCheckedMenuItem.cs +++ b/RdcMan/ClientSizeCheckedMenuItem.cs @@ -1,21 +1,26 @@ using System.Drawing; -namespace RdcMan { - internal class ClientSizeCheckedMenuItem : CheckedMenuItem { - private readonly RdcBaseForm _form; +namespace RdcMan +{ + internal class ClientSizeCheckedMenuItem : CheckedMenuItem + { + private RdcBaseForm _form; public ClientSizeCheckedMenuItem(RdcBaseForm form, Size size) - : base(size.ToFormattedString()) { + : base(size.ToFormattedString()) + { base.Tag = size; _form = form; } - protected override void CheckChanged(bool isChecked) { + protected override void CheckChanged(bool isChecked) + { Size clientSize = (Size)base.Tag; _form.SetClientSize(clientSize); } - public override void Update() { + public override void Update() + { Size size = (Size)base.Tag; Size clientSize = _form.GetClientSize(); base.Checked = clientSize == size; diff --git a/RdcMan/CommonDisplaySettings.cs b/RdcMan/CommonDisplaySettings.cs index 3835437..9c44b86 100644 --- a/RdcMan/CommonDisplaySettings.cs +++ b/RdcMan/CommonDisplaySettings.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public abstract class CommonDisplaySettings : SettingsGroup { +namespace RdcMan +{ + public abstract class CommonDisplaySettings : SettingsGroup + { //public const string TabName = "ʾ"; [Setting("thumbnailScale", DefaultValue = 1)] @@ -12,10 +14,12 @@ public abstract class CommonDisplaySettings : SettingsGroup { public EnumSetting SmartSizeUndockedWindow { get; protected set; } protected CommonDisplaySettings() - : base("ʾ", "displaySettings") { + : base("ʾ", "displaySettings") + { } - protected override void Copy(RdcTreeNode node) { + protected override void Copy(RdcTreeNode node) + { Copy(node.DisplaySettings); } } diff --git a/RdcMan/CommonNodeSettings.cs b/RdcMan/CommonNodeSettings.cs index cf552a7..fe91364 100644 --- a/RdcMan/CommonNodeSettings.cs +++ b/RdcMan/CommonNodeSettings.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public abstract class CommonNodeSettings : SettingsGroup { +namespace RdcMan +{ + public abstract class CommonNodeSettings : SettingsGroup + { [Setting("name")] protected StringSetting NodeName { get; set; } @@ -7,11 +9,13 @@ public abstract class CommonNodeSettings : SettingsGroup { public StringSetting Comment { get; protected set; } protected CommonNodeSettings(string name) - : base(name, "properties") { + : base(name, "properties") + { base.InheritSettingsType.Mode = InheritanceMode.Disabled; } - protected override void Copy(RdcTreeNode node) { + protected override void Copy(RdcTreeNode node) + { Copy(node.Properties); } } diff --git a/RdcMan/ConnectAsDialog.cs b/RdcMan/ConnectAsDialog.cs index f6058ed..4012f8c 100644 --- a/RdcMan/ConnectAsDialog.cs +++ b/RdcMan/ConnectAsDialog.cs @@ -19,11 +19,13 @@ public static ConnectAsDialog NewConnectAsDialog(RdcTreeNode node, Form parentFo connectAsDialog.LogonCredentials = new LogonCredentials(); connectAsDialog.ConnectionSettings = new ConnectionSettings(); if (node.LogonCredentials != null) + { connectAsDialog.LogonCredentials.Copy(node.LogonCredentials); - + } if (node.ConnectionSettings != null) + { connectAsDialog.ConnectionSettings.Copy(node.ConnectionSettings); - + } connectAsDialog.CreateControls(inputServerName: false, connectAsDialog.LogonCredentials, connectAsDialog.ConnectionSettings, node.FileGroup); return connectAsDialog; } diff --git a/RdcMan/ConnectServersDialog.cs b/RdcMan/ConnectServersDialog.cs index 40b879a..a29bcca 100644 --- a/RdcMan/ConnectServersDialog.cs +++ b/RdcMan/ConnectServersDialog.cs @@ -1,24 +1,29 @@ using System.Collections.Generic; using System.Windows.Forms; -namespace RdcMan { - internal class ConnectServersDialog : SelectServersDialogBase { +namespace RdcMan +{ + internal class ConnectServersDialog : SelectServersDialogBase + { public ConnectServersDialog(IEnumerable servers) - : base("ӷ", "(&C)") { + : base("ӷ", "(&C)") + { int rowIndex = 0; int num = 0; AddLabel("ѡҪӵķ", ref rowIndex, ref num); AddListView(ref rowIndex, ref num); InitButtons(); this.ScaleAndLayout(); - servers.ForEach(delegate (ServerBase server) { + servers.ForEach(delegate(ServerBase server) + { base.ListView.Items.Add(CreateListViewItem(server)); }); base.ListView.ItemChecked += ListView_ItemChecked; _acceptButton.Enabled = false; } - private void ListView_ItemChecked(object sender, ItemCheckedEventArgs e) { + private void ListView_ItemChecked(object sender, ItemCheckedEventArgs e) + { _acceptButton.Enabled = base.ListView.CheckedItems.Count > 0; } } diff --git a/RdcMan/ConnectToDialog.cs b/RdcMan/ConnectToDialog.cs index 6a0aff9..6405743 100644 --- a/RdcMan/ConnectToDialog.cs +++ b/RdcMan/ConnectToDialog.cs @@ -1,14 +1,18 @@ using System.Windows.Forms; -namespace RdcMan { - public class ConnectToDialog : QuickConnectDialog { +namespace RdcMan +{ + public class ConnectToDialog : QuickConnectDialog + { public TemporaryServer Server { get; private set; } private ConnectToDialog(string title, string buttonText, Form parentForm) - : base(title, buttonText, parentForm) { + : base(title, buttonText, parentForm) + { } - public static ConnectToDialog NewConnectToDialog(Form parentForm) { + public static ConnectToDialog NewConnectToDialog(Form parentForm) + { ConnectToDialog connectToDialog = new ConnectToDialog("ӵ", "(&C)", parentForm); connectToDialog.Server = TemporaryServer.CreateForQuickConnect(); connectToDialog.CreateControls(inputServerName: true, connectToDialog.Server.LogonCredentials, connectToDialog.Server.ConnectionSettings, null); diff --git a/RdcMan/ConnectToGroup.cs b/RdcMan/ConnectToGroup.cs index f9d5411..94f9f1b 100644 --- a/RdcMan/ConnectToGroup.cs +++ b/RdcMan/ConnectToGroup.cs @@ -1,29 +1,37 @@ using System; using System.ComponentModel.Composition; -namespace RdcMan { +namespace RdcMan +{ [Export(typeof(IBuiltInVirtualGroup))] - internal class ConnectToGroup : BuiltInVirtualGroup, IServerRefFactory { + internal class ConnectToGroup : BuiltInVirtualGroup, IServerRefFactory + { public static ConnectToGroup Instance { get; private set; } protected override bool IsVisibilityConfigurable => false; - private ConnectToGroup() { + private ConnectToGroup() + { base.Text = "ӵ"; Instance = this; } - public override ServerRef AddReference(ServerBase serverBase) { + public override ServerRef AddReference(ServerBase serverBase) + { throw new InvalidOperationException(); } - public override void InvalidateNode() { + public override void InvalidateNode() + { base.InvalidateNode(); if (base.Nodes.Count == 0) + { base.IsInTree = false; + } } - public ServerRef Create(Server server) { + public ServerRef Create(Server server) + { throw new NotImplementedException("ӵ"); } } diff --git a/RdcMan/ConnectedGroup.cs b/RdcMan/ConnectedGroup.cs index 493d2a0..a9577c7 100644 --- a/RdcMan/ConnectedGroup.cs +++ b/RdcMan/ConnectedGroup.cs @@ -1,42 +1,56 @@ using System; using System.ComponentModel.Composition; -namespace RdcMan { +namespace RdcMan +{ [Export(typeof(IBuiltInVirtualGroup))] - internal class ConnectedGroup : BuiltInVirtualGroup, IServerRefFactory { + internal class ConnectedGroup : BuiltInVirtualGroup, IServerRefFactory + { public static ConnectedGroup Instance { get; private set; } protected override string XmlNodeName => "connected"; - static ConnectedGroup() { + static ConnectedGroup() + { Server.ConnectionStateChanged += Server_ConnectionStateChanged; Server.FocusReceived += Server_FocusReceived; } - private ConnectedGroup() { + private ConnectedGroup() + { base.Text = ""; Instance = this; } - private static void Server_FocusReceived(Server server) { + private static void Server_FocusReceived(Server server) + { ConnectedServerRef connectedServerRef = server.FindServerRef(); - if (connectedServerRef != null) { + if (connectedServerRef != null) + { connectedServerRef.LastFocusTime = DateTime.Now; if (ServerTree.Instance.SortGroup(Instance)) + { ServerTree.Instance.OnGroupChanged(Instance, ChangeType.InvalidateUI); + } } } - private static void Server_ConnectionStateChanged(ConnectionStateChangedEventArgs args) { - switch (args.State) { - case RdpClient.ConnectionState.Connected: - Instance.AddReference(args.Server); - break; - case RdpClient.ConnectionState.Disconnected: - RdcTreeNode rdcTreeNode = args.Server.FindServerRef(); - if (rdcTreeNode != null) - ServerTree.Instance.RemoveNode(rdcTreeNode); - break; + private static void Server_ConnectionStateChanged(ConnectionStateChangedEventArgs args) + { + switch (args.State) + { + case RdpClient.ConnectionState.Connected: + Instance.AddReference(args.Server); + break; + case RdpClient.ConnectionState.Disconnected: + { + RdcTreeNode rdcTreeNode = args.Server.FindServerRef(); + if (rdcTreeNode != null) + { + ServerTree.Instance.RemoveNode(rdcTreeNode); + } + break; + } } } @@ -44,7 +58,8 @@ private static void Server_ConnectionStateChanged(ConnectionStateChangedEventArg public override bool CanRemoveChildren() => false; - public override void Disconnect() { + public override void Disconnect() + { Hide(); base.Disconnect(); } diff --git a/RdcMan/ConnectedServerRef.cs b/RdcMan/ConnectedServerRef.cs index 6c3bd95..a0bb327 100644 --- a/RdcMan/ConnectedServerRef.cs +++ b/RdcMan/ConnectedServerRef.cs @@ -1,14 +1,18 @@ using System; -namespace RdcMan { - internal class ConnectedServerRef : ServerRef { +namespace RdcMan +{ + internal class ConnectedServerRef : ServerRef + { public DateTime LastFocusTime { get; set; } public ConnectedServerRef(Server server) - : base(server) { + : base(server) + { } - public override bool ConfirmRemove(bool askUser) { + public override bool ConfirmRemove(bool askUser) + { FormTools.InformationDialog("ϿԽ ɾ"); return false; } diff --git a/RdcMan/ConnectionSettings.cs b/RdcMan/ConnectionSettings.cs index c6910c3..0472722 100644 --- a/RdcMan/ConnectionSettings.cs +++ b/RdcMan/ConnectionSettings.cs @@ -1,8 +1,10 @@ using System.Collections.Generic; using System.Windows.Forms; -namespace RdcMan { - public class ConnectionSettings : SettingsGroup { +namespace RdcMan +{ + public class ConnectionSettings : SettingsGroup + { //internal const string TabName = ""; private static Dictionary _settingProperties; @@ -24,12 +26,14 @@ public class ConnectionSettings : SettingsGroup { [Setting("loadBalanceInfo")] public StringSetting LoadBalanceInfo { get; private set; } - static ConnectionSettings() { + static ConnectionSettings() + { typeof(ConnectionSettings).GetSettingProperties(out _settingProperties); } public ConnectionSettings() - : base("", "connectionSettings") { + : base("", "connectionSettings") + { } public override TabPage CreateTabPage(TabbedSettingsDialog dialog) => new ConnectionSettingsTabPage(dialog, this); diff --git a/RdcMan/ConnectionSettingsTabPage.cs b/RdcMan/ConnectionSettingsTabPage.cs index 0657c76..3a2609e 100644 --- a/RdcMan/ConnectionSettingsTabPage.cs +++ b/RdcMan/ConnectionSettingsTabPage.cs @@ -2,32 +2,37 @@ using System.Drawing; using System.Windows.Forms; -namespace RdcMan { - public class ConnectionSettingsTabPage : SettingsTabPage { +namespace RdcMan +{ + public class ConnectionSettingsTabPage : SettingsTabPage + { private Label _portDefaultLabel; private NumericUpDown _portUpDown; public ConnectionSettingsTabPage(TabbedSettingsDialog dialog, ConnectionSettings settings) - : base(dialog, settings) { - int num = 0; + : base(dialog, settings) + { + int tabIndex = 0; int rowIndex = 0; - CreateInheritanceControl(ref rowIndex, ref num); - FormTools.AddCheckBox(this, "ӵ̨(&C)", settings.ConnectToConsole, 1, ref rowIndex, ref num); - FormTools.AddLabeledTextBox(this, "(&S)", settings.StartProgram, ref rowIndex, ref num); - FormTools.AddLabeledTextBox(this, "Ŀ¼(&W)", settings.WorkingDir, ref rowIndex, ref num); + CreateInheritanceControl(ref rowIndex, ref tabIndex); + FormTools.AddCheckBox(this, "ӵ̨(&C)", settings.ConnectToConsole, 1, ref rowIndex, ref tabIndex); + FormTools.AddLabeledTextBox(this, "(&S)", settings.StartProgram, ref rowIndex, ref tabIndex); + FormTools.AddLabeledTextBox(this, "Ŀ¼(&W)", settings.WorkingDir, ref rowIndex, ref tabIndex); Label label = FormTools.NewLabel("˿(&P)", 0, rowIndex); _portUpDown = new NumericUpDown { Location = FormTools.NewLocation(1, rowIndex++), Size = new Size(160, FormTools.ControlHeight), - Minimum = 1m, - Maximum = 65535m, - TabIndex = num++ + Minimum = 1, + Maximum = 65535, + TabIndex = tabIndex++ }; - _portUpDown.KeyUp += delegate { + _portUpDown.KeyUp += delegate + { UpdatePortDefaultLabel(); }; - _portUpDown.ValueChanged += delegate { + _portUpDown.ValueChanged += delegate + { UpdatePortDefaultLabel(); }; ((ISupportInitialize)_portUpDown).EndInit(); @@ -36,22 +41,24 @@ public ConnectionSettingsTabPage(TabbedSettingsDialog dialog, ConnectionSettings Size = new Size(FormTools.LabelWidth, FormTools.ControlHeight), TextAlign = ContentAlignment.MiddleLeft }; - FormTools.AddLabeledTextBox(this, "ؾ(&L)", settings.LoadBalanceInfo, ref rowIndex, ref num); + FormTools.AddLabeledTextBox(this, "ؾ(&L)", settings.LoadBalanceInfo, ref rowIndex, ref tabIndex); base.Controls.Add(label, _portUpDown, _portDefaultLabel); } - protected override void UpdateControls() { + protected override void UpdateControls() + { base.UpdateControls(); _portUpDown.Text = base.Settings.Port.Value.ToString(); } - protected override void UpdateSettings() { + protected override void UpdateSettings() + { base.UpdateSettings(); base.Settings.Port.Value = (int)_portUpDown.Value; } private void UpdatePortDefaultLabel() { - _portDefaultLabel.Text = ((_portUpDown.Value == 3389m) ? "(default)" : string.Empty); + _portDefaultLabel.Text = ((_portUpDown.Value == 3389) ? "(Ĭ)" : string.Empty); } } } diff --git a/RdcMan/ConnectionStateChangedEventArg.cs b/RdcMan/ConnectionStateChangedEventArg.cs index 7ff906a..c48e79c 100644 --- a/RdcMan/ConnectionStateChangedEventArg.cs +++ b/RdcMan/ConnectionStateChangedEventArg.cs @@ -1,12 +1,15 @@ using System; -namespace RdcMan { - public class ConnectionStateChangedEventArgs : EventArgs { +namespace RdcMan +{ + public class ConnectionStateChangedEventArgs : EventArgs + { public Server Server { get; private set; } public RdpClient.ConnectionState State { get; private set; } - public ConnectionStateChangedEventArgs(Server server, RdpClient.ConnectionState state) { + public ConnectionStateChangedEventArgs(Server server, RdpClient.ConnectionState state) + { Server = server; State = state; } diff --git a/RdcMan/ConnectionType.cs b/RdcMan/ConnectionType.cs index 053e70e..6d0aef2 100644 --- a/RdcMan/ConnectionType.cs +++ b/RdcMan/ConnectionType.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public enum ConnectionType { +namespace RdcMan +{ + public enum ConnectionType + { Normal, VirtualMachineConsoleConnect } diff --git a/RdcMan/ControlExtensions.cs b/RdcMan/ControlExtensions.cs index 98cb1d8..16ce3ed 100644 --- a/RdcMan/ControlExtensions.cs +++ b/RdcMan/ControlExtensions.cs @@ -1,15 +1,21 @@ using System.Collections.Generic; using System.Windows.Forms; -namespace RdcMan { - public static class ControlExtensions { - public static IEnumerable FlattenControls(this Control.ControlCollection controls) { - foreach (Control c in controls) { +namespace RdcMan +{ + public static class ControlExtensions + { + public static IEnumerable FlattenControls(this Control.ControlCollection controls) + { + foreach (Control c in controls) + { yield return c; if (c.Controls.Count <= 0) + { continue; - - foreach (Control item in c.Controls.FlattenControls()) { + } + foreach (Control item in c.Controls.FlattenControls()) + { yield return item; } } diff --git a/RdcMan/ControlVisibility.cs b/RdcMan/ControlVisibility.cs index f26ec47..84da7a8 100644 --- a/RdcMan/ControlVisibility.cs +++ b/RdcMan/ControlVisibility.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public enum ControlVisibility { +namespace RdcMan +{ + public enum ControlVisibility + { Dock, AutoHide, Hide diff --git a/RdcMan/CredentialsProfile.cs b/RdcMan/CredentialsProfile.cs index 5b03c10..aa58418 100644 --- a/RdcMan/CredentialsProfile.cs +++ b/RdcMan/CredentialsProfile.cs @@ -1,16 +1,18 @@ -namespace RdcMan { - public class CredentialsProfile : ILogonCredentials, IDeferDecryption { +namespace RdcMan +{ + public class CredentialsProfile : ILogonCredentials, IDeferDecryption + { public const string CustomProfileName = "Custom"; private readonly string _profileName; private readonly ProfileScope _profileScope; - private readonly string _userName; + private string _userName; - private readonly PasswordSetting _password; + private PasswordSetting _password; - private readonly string _domain; + private string _domain; public string ProfileName => _profileName; @@ -22,24 +24,34 @@ public class CredentialsProfile : ILogonCredentials, IDeferDecryption { public string Domain => _domain; - public bool IsDecrypted { - get => _password.IsDecrypted; - set => _password.IsDecrypted = value; + public bool IsDecrypted + { + get + { + return _password.IsDecrypted; + } + set + { + _password.IsDecrypted = value; + } } public string QualifiedName => LogonCredentials.ConstructQualifiedName(this); - public CredentialsProfile(string profileName, ProfileScope profileScope, string userName, string password, string domain) { + public CredentialsProfile(string profileName, ProfileScope profileScope, string userName, string password, string domain) + { _profileName = profileName; _profileScope = profileScope; _userName = userName; - _password = new PasswordSetting(password) { + _password = new PasswordSetting(password) + { IsDecrypted = true }; _domain = domain; } - public CredentialsProfile(string profileName, ProfileScope profileScope, string userName, PasswordSetting password, string domain) { + public CredentialsProfile(string profileName, ProfileScope profileScope, string userName, PasswordSetting password, string domain) + { _profileName = profileName; _profileScope = profileScope; _userName = userName; @@ -47,11 +59,13 @@ public CredentialsProfile(string profileName, ProfileScope profileScope, string _domain = domain; } - public void Decrypt(EncryptionSettings settings) { + public void Decrypt(EncryptionSettings settings) + { _password.Decrypt(settings); } - public override string ToString() { + public override string ToString() + { return ProfileName; } } diff --git a/RdcMan/CredentialsStore.cs b/RdcMan/CredentialsStore.cs index f7fd91e..19f640c 100644 --- a/RdcMan/CredentialsStore.cs +++ b/RdcMan/CredentialsStore.cs @@ -2,8 +2,10 @@ using System.Collections.Generic; using System.Xml; -namespace RdcMan { - public class CredentialsStore { +namespace RdcMan +{ + public class CredentialsStore + { public const string XmlNodeName = "credentialsProfiles"; public const string ProfileXmlNodeName = "credentialsProfile"; @@ -12,9 +14,11 @@ public class CredentialsStore { public int ChangeId { get; private set; } - public CredentialsProfile this[string name] { + public CredentialsProfile this[string name] + { get => _profiles[name]; - set { + set + { _profiles[name] = value; ChangeId++; } @@ -22,12 +26,15 @@ public CredentialsProfile this[string name] { public IEnumerable Profiles => _profiles.Values; - public CredentialsStore() { + public CredentialsStore() + { _profiles = new Dictionary(StringComparer.OrdinalIgnoreCase); } - public void ReadXml(XmlNode xmlNode, ProfileScope scope, RdcTreeNode node, ICollection errors) { - foreach (XmlNode childNode in xmlNode.ChildNodes) { + public void ReadXml(XmlNode xmlNode, ProfileScope scope, RdcTreeNode node, ICollection errors) + { + foreach (XmlNode childNode in xmlNode.ChildNodes) + { LogonCredentials logonCredentials = new LogonCredentials("", "credentialsProfile"); logonCredentials.ReadXml(childNode, node, errors); ILogonCredentials logonCredentials2 = logonCredentials; @@ -37,9 +44,11 @@ public void ReadXml(XmlNode xmlNode, ProfileScope scope, RdcTreeNode node, IColl } } - public void WriteXml(XmlTextWriter tw, RdcTreeNode node) { + public void WriteXml(XmlTextWriter tw, RdcTreeNode node) + { tw.WriteStartElement("credentialsProfiles"); - foreach (CredentialsProfile profile in Profiles) { + foreach (CredentialsProfile profile in Profiles) + { LogonCredentials logonCredentials = new LogonCredentials("", "credentialsProfile"); logonCredentials.InheritSettingsType.Mode = InheritanceMode.None; logonCredentials.ProfileName.Value = ((ILogonCredentials)profile).ProfileName; @@ -51,16 +60,19 @@ public void WriteXml(XmlTextWriter tw, RdcTreeNode node) { tw.WriteEndElement(); } - public bool TryGetValue(string name, out CredentialsProfile profile) { + public bool TryGetValue(string name, out CredentialsProfile profile) + { return _profiles.TryGetValue(name, out profile); } - public void Remove(string name) { + public void Remove(string name) + { _profiles.Remove(name); ChangeId++; } - public bool Contains(string name) { + public bool Contains(string name) + { return _profiles.ContainsKey(name); } } diff --git a/RdcMan/CredentialsTabPage.cs b/RdcMan/CredentialsTabPage.cs index 79b3bf2..3fc79f4 100644 --- a/RdcMan/CredentialsTabPage.cs +++ b/RdcMan/CredentialsTabPage.cs @@ -1,32 +1,44 @@ -namespace RdcMan { - public abstract class CredentialsTabPage : SettingsTabPage, ICredentialsTabPage where TSettingGroup : LogonCredentials { +namespace RdcMan +{ + public abstract class CredentialsTabPage : SettingsTabPage, ICredentialsTabPage where TSettingGroup : LogonCredentials + { protected CredentialsUI _credentialsUI; public CredentialsProfile Credentials => _credentialsUI.ProfileComboBox.SelectedValue; protected CredentialsTabPage(TabbedSettingsDialog dialog, TSettingGroup settings) - : base(dialog, settings) { + : base(dialog, settings) + { } - public void PopulateCredentialsProfiles(FileGroup file) { + public void PopulateCredentialsProfiles(FileGroup file) + { if (_credentialsUI != null) + { _credentialsUI.PopulateCredentialsProfiles(file); + } } - protected override void UpdateControls() { + protected override void UpdateControls() + { base.UpdateControls(); if (_credentialsUI != null) + { _credentialsUI.InitFromCredentials(base.Settings); + } } - protected override void UpdateSettings() { + protected override void UpdateSettings() + { base.UpdateSettings(); - if (_credentialsUI != null) { + if (_credentialsUI != null) + { base.Settings.ProfileName.UpdateValue(_credentialsUI.ProfileComboBox.SelectedValue.ProfileName, _credentialsUI.ProfileComboBox.SelectedValue.ProfileScope); base.Settings.UserName.Value = _credentialsUI.UserNameTextBox.Text; if (_credentialsUI.PasswordChanged) + { base.Settings.Password.SetPlainText(_credentialsUI.PasswordTextBox.Text); - + } base.Settings.Domain.Value = _credentialsUI.DomainTextBox.Text; } } diff --git a/RdcMan/CredentialsUI.cs b/RdcMan/CredentialsUI.cs index 0ad4481..782eb88 100644 --- a/RdcMan/CredentialsUI.cs +++ b/RdcMan/CredentialsUI.cs @@ -2,8 +2,10 @@ using System.Drawing; using System.Windows.Forms; -namespace RdcMan { - public class CredentialsUI { +namespace RdcMan +{ + public class CredentialsUI + { public const char DomainSeparator = '\\'; //private const string DummyPassword = "Placeholder1234567890"; @@ -30,37 +32,46 @@ public class CredentialsUI { public bool PasswordChanged { get; private set; } - private static bool HasDomainUser(string userName) { + private static bool HasDomainUser(string userName) + { return userName.IndexOf('\\') != -1; } - public static string GetUserName(string userName) { + public static string GetUserName(string userName) + { int num = userName.IndexOf('\\'); - if (num == -1) { + if (num == -1) + { return userName; } return userName.Substring(num + 1); } - public static string GetQualifiedUserName(string userName, string domain) { + public static string GetQualifiedUserName(string userName, string domain) + { string text = userName; - if (!HasDomainUser(text) && !string.IsNullOrEmpty(domain)) { + if (!HasDomainUser(text) && !string.IsNullOrEmpty(domain)) + { text = domain + "\\" + text; } return text; } - public static string GetLoggedInUser() { + public static string GetLoggedInUser() + { return GetQualifiedUserName(Environment.UserName, Environment.UserDomainName); } - public CredentialsUI(InheritanceControl inheritSettings) { + public CredentialsUI(InheritanceControl inheritSettings) + { _inheritSettings = inheritSettings; PasswordChanged = true; } - public void AddControlsToParent(Control parent, LogonCredentialsDialogOptions options, ref int rowIndex, ref int tabIndex) { - if ((options & LogonCredentialsDialogOptions.ShowProfiles) != 0) { + public void AddControlsToParent(Control parent, LogonCredentialsDialogOptions options, ref int rowIndex, ref int tabIndex) + { + if ((options & LogonCredentialsDialogOptions.ShowProfiles) != 0) + { ProfileComboBox = FormTools.AddLabeledValueDropDown(parent, "配置文件:", ref rowIndex, ref tabIndex, null, null); ProfileComboBox.SelectedIndexChanged += OnProfileChanged; ProfileComboBox.VisibleChanged += OnProfileVisible; @@ -81,15 +92,19 @@ public void AddControlsToParent(Control parent, LogonCredentialsDialogOptions op DomainTextBox = FormTools.AddLabeledTextBox(parent, "域名(&D):", ref rowIndex, ref tabIndex); } - public void PopulateCredentialsProfiles(FileGroup file) { - if (file == null || _file != file) { + public void PopulateCredentialsProfiles(FileGroup file) + { + if (file == null || _file != file) + { _file = file; PopulateCredentialsProfilesWorker(); } } - public void InitFromCredentials(ILogonCredentials credentials) { - if (ProfileComboBox != null) { + public void InitFromCredentials(ILogonCredentials credentials) + { + if (ProfileComboBox != null) + { _usingCustomCredentials = LogonCredentials.IsCustomProfile(credentials.ProfileName); ProfileComboBox.SelectedIndex = ProfileComboBox.FindItem(LogonCredentials.ConstructQualifiedName(credentials)); } @@ -98,34 +113,44 @@ public void InitFromCredentials(ILogonCredentials credentials) { DomainTextBox.Text = credentials.Domain; } - public void InitPassword(PasswordSetting password) { - if (password != null && password.IsDecrypted && !string.IsNullOrEmpty(password.Value)) { + public void InitPassword(PasswordSetting password) + { + if (password != null && password.IsDecrypted && !string.IsNullOrEmpty(password.Value)) + { PasswordTextBox.Text = password.Value;// DummyPassword; 直接放置原密码 PasswordChanged = false; } else + { PasswordTextBox.Text = string.Empty; + } } - public void EnableDisableControls(bool enable) { + public void EnableDisableControls(bool enable) + { enable &= _inheritSettings == null || !_inheritSettings.FromParentCheck.Checked; - if (ProfileComboBox != null) { + if (ProfileComboBox != null) + { ProfileComboBox.Enabled = enable; enable &= _usingCustomCredentials; } if (_saveProfileButton != null) + { _saveProfileButton.Enabled = enable; - + } UserNameTextBox.Enabled = enable; DomainTextBox.Enabled = enable; PasswordTextBox.Enabled = enable; OnUserNameChanged(null, null); } - private void OnUserNameChanged(object sender, EventArgs e) { - if (_inheritSettings == null || !_inheritSettings.FromParentCheck.Checked) { + private void OnUserNameChanged(object sender, EventArgs e) + { + if (_inheritSettings == null || !_inheritSettings.FromParentCheck.Checked) + { int num = UserNameTextBox.Text.IndexOf('\\'); - if (num == -1) { + if (num == -1) + { DomainTextBox.Enabled = UserNameTextBox.Enabled; return; } @@ -134,21 +159,26 @@ private void OnUserNameChanged(object sender, EventArgs e) { } } - private void OnPasswordChanged(object sender, EventArgs e) { + private void OnPasswordChanged(object sender, EventArgs e) + { PasswordChanged = true; } - private void OnProfileChanged(object sender, EventArgs e) { - if (_inheritSettings == null || !_inheritSettings.FromParentCheck.Checked) { + private void OnProfileChanged(object sender, EventArgs e) + { + if (_inheritSettings == null || !_inheritSettings.FromParentCheck.Checked) + { ILogonCredentials selectedValue = ProfileComboBox.SelectedValue; _usingCustomCredentials = LogonCredentials.IsCustomProfile(selectedValue.ProfileName); EnableDisableControls(enable: true); - if (_usingCustomCredentials) { + if (_usingCustomCredentials) + { UserNameTextBox.Text = Environment.UserName; InitPassword(null); DomainTextBox.Text = Environment.UserDomainName; } - else { + else + { UserNameTextBox.Text = selectedValue.UserName; InitPassword(selectedValue.Password); DomainTextBox.Text = selectedValue.Domain; @@ -156,54 +186,69 @@ private void OnProfileChanged(object sender, EventArgs e) { } } - private void OnProfileVisible(object sender, EventArgs e) { + private void OnProfileVisible(object sender, EventArgs e) + { PopulateCredentialsProfilesIfChanged(); } - private void PopulateCredentialsProfilesIfChanged() { + private void PopulateCredentialsProfilesIfChanged() + { if (_globalStoreChangeId != Program.CredentialsProfiles.ChangeId || (_file != null && _fileStoreChangeId != _file.CredentialsProfiles.ChangeId)) + { PopulateCredentialsProfilesWorker(); + } } - private void PopulateCredentialsProfilesWorker() { + private void PopulateCredentialsProfilesWorker() + { CredentialsProfile selectedValue = ProfileComboBox.SelectedValue; ProfileComboBox.ClearItems(); ProfileComboBox.AddItem("Custom", new CredentialsProfile("Custom", ProfileScope.Local, string.Empty, string.Empty, string.Empty)); ProfileComboBox.SelectedIndex = 0; PopulateComboFromStore(Program.CredentialsProfiles); _globalStoreChangeId = Program.CredentialsProfiles.ChangeId; - if (_file != null) { + if (_file != null) + { PopulateComboFromStore(_file.CredentialsProfiles); _fileStoreChangeId = _file.CredentialsProfiles.ChangeId; } ProfileComboBox.SelectedValue = selectedValue; } - private void PopulateComboFromStore(CredentialsStore store) { - foreach (CredentialsProfile profile in store.Profiles) { + private void PopulateComboFromStore(CredentialsStore store) + { + foreach (CredentialsProfile profile in store.Profiles) + { string qualifiedName = profile.QualifiedName; ProfileComboBox.AddItem(qualifiedName, profile); } } - private void SaveProfileButton_Click(object sender, EventArgs e) { + private void SaveProfileButton_Click(object sender, EventArgs e) + { string qualifiedUserName = GetQualifiedUserName(UserNameTextBox.Text, DomainTextBox.Text); - using (SaveCredentialsDialog saveCredentialsDialog = new SaveCredentialsDialog(_file, qualifiedUserName)) { - if (saveCredentialsDialog.ShowDialog() == DialogResult.OK) { + using (SaveCredentialsDialog saveCredentialsDialog = new SaveCredentialsDialog(_file, qualifiedUserName)) + { + if (saveCredentialsDialog.ShowDialog() == DialogResult.OK) + { ProfileScope profileScope = saveCredentialsDialog.ProfileScope; CredentialsStore credentialsProfiles = Program.CredentialsProfiles; if (profileScope == ProfileScope.File) + { credentialsProfiles = _file.CredentialsProfiles; - + } qualifiedUserName = saveCredentialsDialog.ProfileName; bool flag = !credentialsProfiles.Contains(qualifiedUserName); CredentialsProfile credentialsProfile2 = (credentialsProfiles[qualifiedUserName] = new CredentialsProfile(qualifiedUserName, profileScope, UserNameTextBox.Text, PasswordTextBox.Text, DomainTextBox.Text)); string qualifiedName = credentialsProfile2.QualifiedName; if (flag) + { ProfileComboBox.AddItem(qualifiedName, credentialsProfile2); + } else + { ProfileComboBox.ReplaceItem(qualifiedName, credentialsProfile2); - + } ProfileComboBox.SelectedValue = credentialsProfile2; } } diff --git a/RdcMan/CustomClientSizeCheckedMenuIte.cs b/RdcMan/CustomClientSizeCheckedMenuIte.cs index 1a3e382..873f0c6 100644 --- a/RdcMan/CustomClientSizeCheckedMenuIte.cs +++ b/RdcMan/CustomClientSizeCheckedMenuIte.cs @@ -2,34 +2,41 @@ using System.Linq; using System.Windows.Forms; -namespace RdcMan { - internal class CustomClientSizeCheckedMenuItem : CheckedMenuItem { +namespace RdcMan +{ + internal class CustomClientSizeCheckedMenuItem : CheckedMenuItem + { private RdcBaseForm _form; private string _baseText; public CustomClientSizeCheckedMenuItem(RdcBaseForm form, string text) - : base(text) { + : base(text) + { _baseText = Text; _form = form; } - protected override void CheckChanged(bool isChecked) { + protected override void CheckChanged(bool isChecked) + { Size clientSize = _form.GetClientSize(); using CustomSizeDialog customSizeDialog = new CustomSizeDialog(clientSize); - if (customSizeDialog.ShowDialog() == DialogResult.OK) { + if (customSizeDialog.ShowDialog() == DialogResult.OK) + { Size clientSize2 = SizeHelper.FromString(customSizeDialog.WidthText, customSizeDialog.HeightText); _form.SetClientSize(clientSize2); } } - public override void Update() { + public override void Update() + { Size clientSize = _form.GetClientSize(); bool flag2 = (base.Checked = SizeHelper.StockSizes.All((Size size) => size != clientSize)); string text = _baseText; if (flag2) + { text += " ({0})".InvariantFormat(clientSize.ToFormattedString()); - + } Text = text + "..."; } } diff --git a/RdcMan/CustomSizeDialog.cs b/RdcMan/CustomSizeDialog.cs index afd5e4a..e695260 100644 --- a/RdcMan/CustomSizeDialog.cs +++ b/RdcMan/CustomSizeDialog.cs @@ -2,8 +2,10 @@ using System.Drawing; using System.Windows.Forms; -namespace RdcMan { - public class CustomSizeDialog : RdcDialog { +namespace RdcMan +{ + public class CustomSizeDialog : RdcDialog + { private NumericTextBox _widthTextBox; private NumericTextBox _heightTextBox; @@ -19,23 +21,25 @@ public class CustomSizeDialog : RdcDialog { public string HeightText => _heightTextBox.Text; public CustomSizeDialog(Size size) - : base("ԶС", "ȷ") { + : base("ԶС", "ȷ") + { InitComp(); _widthTextBox.Text = size.Width.ToString(); _heightTextBox.Text = size.Height.ToString(); } - private void InitComp() { + private void InitComp() + { int num = 0; Label label = new Label { Location = new Point(8, 8), - Size = new Size(50, 23), + Size = new Size(60, 23), Text = "(&W)", TextAlign = ContentAlignment.MiddleLeft }; Label label2 = new Label { Location = new Point(8, 40), - Size = new Size(50, 23), + Size = new Size(60, 23), Text = "߶(&H)", TextAlign = ContentAlignment.MiddleLeft }; @@ -73,19 +77,22 @@ private void InitComp() { this.ScaleAndLayout(); } - private void fourThreeButton_Click(object sender, EventArgs e) { + private void fourThreeButton_Click(object sender, EventArgs e) + { int num = int.Parse(_widthTextBox.Text); int num2 = num * 3 / 4; _heightTextBox.Text = num2.ToString(); } - private void sixteenNineButton_Click(object sender, EventArgs e) { + private void sixteenNineButton_Click(object sender, EventArgs e) + { int num = int.Parse(_widthTextBox.Text); int num2 = num * 9 / 16; _heightTextBox.Text = num2.ToString(); } - private void sixteenTenButton_Click(object sender, EventArgs e) { + private void sixteenTenButton_Click(object sender, EventArgs e) + { int num = int.Parse(_widthTextBox.Text); int num2 = num * 10 / 16; _heightTextBox.Text = num2.ToString(); diff --git a/RdcMan/DefaultGroupPropertiesDialog.cs b/RdcMan/DefaultGroupPropertiesDialog.cs index ed190d3..e07c118 100644 --- a/RdcMan/DefaultGroupPropertiesDialog.cs +++ b/RdcMan/DefaultGroupPropertiesDialog.cs @@ -1,12 +1,16 @@ using System.Windows.Forms; -namespace RdcMan { - internal class DefaultGroupPropertiesDialog : GroupBasePropertiesDialog { +namespace RdcMan +{ + internal class DefaultGroupPropertiesDialog : GroupBasePropertiesDialog + { protected DefaultGroupPropertiesDialog(GroupBase group, Form parentForm) - : base(group, "Ĭ", "ȷ", parentForm) { + : base(group, "Ĭ", "ȷ", parentForm) + { } - public static DefaultGroupPropertiesDialog NewPropertiesDialog(GroupBase group, Form parentForm) { + public static DefaultGroupPropertiesDialog NewPropertiesDialog(GroupBase group, Form parentForm) + { DefaultGroupPropertiesDialog defaultGroupPropertiesDialog = new DefaultGroupPropertiesDialog(group, parentForm); defaultGroupPropertiesDialog.CreateControls(group); defaultGroupPropertiesDialog.PopulateCredentialsProfiles(null); @@ -14,7 +18,8 @@ public static DefaultGroupPropertiesDialog NewPropertiesDialog(GroupBase group, return defaultGroupPropertiesDialog; } - public override void CreateControls(RdcTreeNode settingsNode) { + public override void CreateControls(RdcTreeNode settingsNode) + { base.CreateControls(settingsNode); AddTabPage(settingsNode.EncryptionSettings.CreateTabPage(this)); CreateProfileManagementTabPage(); diff --git a/RdcMan/DefaultSettingsGroup.cs b/RdcMan/DefaultSettingsGroup.cs index 98ab868..587ac37 100644 --- a/RdcMan/DefaultSettingsGroup.cs +++ b/RdcMan/DefaultSettingsGroup.cs @@ -2,48 +2,59 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { - internal class DefaultSettingsGroup : VirtualGroup { +namespace RdcMan +{ + internal class DefaultSettingsGroup : VirtualGroup + { //public new const string Name = "Ĭ"; - //private const string XmlTopNode = "defaultSettings"; + private const string XmlTopNode = "defaultSettings"; public static DefaultSettingsGroup Instance { get; private set; } public override EncryptionSettings EncryptionSettings { get; protected set; } - static DefaultSettingsGroup() { + static DefaultSettingsGroup() + { Instance = new DefaultSettingsGroup(); } - private DefaultSettingsGroup() { + private DefaultSettingsGroup() + { EncryptionSettings = new EncryptionSettings(); base.AllSettingsGroups.Add(EncryptionSettings); - foreach (SettingsGroup allSettingsGroup in base.AllSettingsGroups) { + foreach (SettingsGroup allSettingsGroup in base.AllSettingsGroups) + { allSettingsGroup.InheritSettingsType.Mode = InheritanceMode.Disabled; } } - internal override void ReadXml(XmlNode node, ICollection errors) { - if (!node.Name.Equals("defaultSettings")) { + internal override void ReadXml(XmlNode node, ICollection errors) + { + if (!node.Name.Equals("defaultSettings")) + { errors.Add("Ĭøʽ"); return; } - foreach (XmlNode childNode in node.ChildNodes) { + foreach (XmlNode childNode in node.ChildNodes) + { ReadXmlSettingsGroup(childNode, errors); } } - internal override void WriteXml(XmlTextWriter tw) { + internal override void WriteXml(XmlTextWriter tw) + { tw.WriteStartElement("defaultSettings"); WriteXmlSettingsGroups(tw); tw.WriteEndElement(); } - public override void DoPropertiesDialog(Form parentForm, string activeTabName) { + public override void DoPropertiesDialog(Form parentForm, string activeTabName) + { using DefaultGroupPropertiesDialog defaultGroupPropertiesDialog = DefaultGroupPropertiesDialog.NewPropertiesDialog(this, parentForm); defaultGroupPropertiesDialog.SetActiveTab(activeTabName); - if (defaultGroupPropertiesDialog.ShowDialog() == DialogResult.OK) { + if (defaultGroupPropertiesDialog.ShowDialog() == DialogResult.OK) + { UpdateSettings(defaultGroupPropertiesDialog); ServerTree.Instance.OnGroupChanged(ServerTree.Instance.RootNode, ChangeType.PropertyChanged); Program.Preferences.NeedToSave = true; diff --git a/RdcMan/DeferDecryptionItem.cs b/RdcMan/DeferDecryptionItem.cs index 7c507af..ac01cf0 100644 --- a/RdcMan/DeferDecryptionItem.cs +++ b/RdcMan/DeferDecryptionItem.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - internal class DeferDecryptionItem { +namespace RdcMan +{ + internal class DeferDecryptionItem + { public IDeferDecryption Object; public RdcTreeNode Node; diff --git a/RdcMan/DelegateCheckedMenuItem.cs b/RdcMan/DelegateCheckedMenuItem.cs index f8e9a98..170d5cc 100644 --- a/RdcMan/DelegateCheckedMenuItem.cs +++ b/RdcMan/DelegateCheckedMenuItem.cs @@ -1,23 +1,28 @@ using System; -namespace RdcMan { - internal class DelegateCheckedMenuItem : CheckedMenuItem { +namespace RdcMan +{ + internal class DelegateCheckedMenuItem : CheckedMenuItem + { private readonly Func _initDelegate; private readonly Action _changedDelegate; public DelegateCheckedMenuItem(string text, MenuNames name, Func initDelegate, Action changedDelegate) - : base(text) { + : base(text) + { base.Name = name.ToString(); _initDelegate = initDelegate; _changedDelegate = changedDelegate; } - protected sealed override void CheckChanged(bool isChecked) { + protected sealed override void CheckChanged(bool isChecked) + { _changedDelegate(isChecked); } - public sealed override void Update() { + public sealed override void Update() + { base.Checked = _initDelegate(); } } diff --git a/RdcMan/DelegateMenuItem.cs b/RdcMan/DelegateMenuItem.cs index 900ecac..dcad90c 100644 --- a/RdcMan/DelegateMenuItem.cs +++ b/RdcMan/DelegateMenuItem.cs @@ -1,18 +1,23 @@ using System; using System.Windows.Forms; -namespace RdcMan { - public class DelegateMenuItem : ToolStripMenuItem { +namespace RdcMan +{ + public class DelegateMenuItem : ToolStripMenuItem + { public DelegateMenuItem(string text, MenuNames name, Action click) - : base(text) { - base.Click += delegate { + : base(text) + { + base.Click += delegate + { click(); }; base.Name = name.ToString(); } public DelegateMenuItem(string text, MenuNames name, string shortcut, Action click) - : this(text, name, click) { + : this(text, name, click) + { base.ShortcutKeyDisplayString = shortcut; } } diff --git a/RdcMan/DisplaySettingsTabPage.cs b/RdcMan/DisplaySettingsTabPage.cs index a56f9c4..cece7c0 100644 --- a/RdcMan/DisplaySettingsTabPage.cs +++ b/RdcMan/DisplaySettingsTabPage.cs @@ -1,13 +1,17 @@ using System.Drawing; using System.Windows.Forms; -namespace RdcMan { - public abstract class DisplaySettingsTabPage : SettingsTabPage where TSettingsGroup : CommonDisplaySettings { +namespace RdcMan +{ + public abstract class DisplaySettingsTabPage : SettingsTabPage where TSettingsGroup : CommonDisplaySettings + { protected DisplaySettingsTabPage(TabbedSettingsDialog dialog, TSettingsGroup settings) - : base(dialog, settings) { + : base(dialog, settings) + { } - protected void Create(out int rowIndex, out int tabIndex) { + protected void Create(out int rowIndex, out int tabIndex) + { tabIndex = 0; rowIndex = 0; CreateInheritanceControl(ref rowIndex, ref tabIndex); @@ -15,8 +19,8 @@ protected void Create(out int rowIndex, out int tabIndex) { label.Size = new Size(140, 20); RdcNumericUpDown rdcNumericUpDown = new RdcNumericUpDown { Location = FormTools.NewLocation(1, rowIndex++), - Minimum = 1m, - Maximum = 9m, + Minimum = 1, + Maximum = 9, Setting = base.Settings.ThumbnailScale, Size = new Size(40, 20), TabIndex = tabIndex++ diff --git a/RdcMan/EnableTabsEventArgs.cs b/RdcMan/EnableTabsEventArgs.cs index c18f0a9..a16d08d 100644 --- a/RdcMan/EnableTabsEventArgs.cs +++ b/RdcMan/EnableTabsEventArgs.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; -namespace RdcMan { - public class EnableTabsEventArgs : EventArgs { +namespace RdcMan +{ + public class EnableTabsEventArgs : EventArgs + { public bool Enabled; public string Reason; diff --git a/RdcMan/Encryption.cs b/RdcMan/Encryption.cs index 33a80ca..5553186 100644 --- a/RdcMan/Encryption.cs +++ b/RdcMan/Encryption.cs @@ -7,106 +7,141 @@ using System.Windows.Forms; using Win32; -namespace RdcMan { - public static class Encryption { +namespace RdcMan +{ + public static class Encryption + { private static readonly List PendingDecryption = new List(); - public static void DeferDecryption(IDeferDecryption o, RdcTreeNode node, string errorDetail) { - PendingDecryption.Add(new DeferDecryptionItem { + public static void DeferDecryption(IDeferDecryption o, RdcTreeNode node, string errorDetail) + { + PendingDecryption.Add(new DeferDecryptionItem + { Object = o, Node = node, ErrorDetail = errorDetail }); } - public static void DecryptPasswords() { + public static void DecryptPasswords() + { StringBuilder builder = new StringBuilder("ijЩƾ֤ʱ⡣").AppendLine().AppendLine("ȷϸϢƵ塣"); bool credentialsProfileFail = false; - PendingDecryption.Where((DeferDecryptionItem d) => d.Object is CredentialsProfile).ForEach(delegate (DeferDecryptionItem item) { + PendingDecryption.Where((DeferDecryptionItem d) => d.Object is CredentialsProfile).ForEach(delegate(DeferDecryptionItem item) + { DecryptPassword(item, builder, "ƾ֤ļ", ref credentialsProfileFail); }); bool passwordFail = false; - PendingDecryption.Where((DeferDecryptionItem d) => d.Object is PasswordSetting).ForEach(delegate (DeferDecryptionItem item) { + PendingDecryption.Where((DeferDecryptionItem d) => d.Object is PasswordSetting).ForEach(delegate(DeferDecryptionItem item) + { DecryptPassword(item, builder, "Զ룺", ref passwordFail); }); PendingDecryption.Clear(); - if (credentialsProfileFail || passwordFail) { + if (credentialsProfileFail || passwordFail) + { DialogResult dialogResult = FormTools.ExclamationDialog(builder.ToString(), MessageBoxButtons.OKCancel); if (dialogResult == DialogResult.OK) + { Clipboard.SetText(builder.ToString()); + } } } - private static bool DecryptPassword(DeferDecryptionItem item, StringBuilder builder, string header, ref bool anyFailed) { + private static bool DecryptPassword(DeferDecryptionItem item, StringBuilder builder, string header, ref bool anyFailed) + { IDeferDecryption @object = item.Object; RdcTreeNode node = item.Node; string errorDetail = item.ErrorDetail; bool anyInherited = false; node.EncryptionSettings.InheritSettings(node, ref anyInherited); - try { + try + { @object.Decrypt(node.EncryptionSettings); } - catch (Exception ex) { - if (!anyFailed) { + catch (Exception ex) + { + if (!anyFailed) + { builder.AppendLine().AppendLine(header); anyFailed = true; } if (node is DefaultSettingsGroup) + { builder.Append("Ĭ"); + } else + { builder.Append(node.FullPath); - builder.AppendFormat(" {0}", errorDetail); + } + builder.AppendFormat(": {0}", errorDetail); if (!string.IsNullOrEmpty(ex.Message)) + { builder.AppendFormat(" [{0}]", ex.Message); + } builder.AppendLine(); } return anyFailed; } - public static string SimpleName(this X509Certificate2 cert) { + public static string SimpleName(this X509Certificate2 cert) + { string text = cert.FriendlyName; if (string.IsNullOrEmpty(text)) + { text = cert.GetNameInfo(X509NameType.SimpleName, forIssuer: false); - + } return text + ", " + cert.GetNameInfo(X509NameType.SimpleName, forIssuer: true); } - public static string EncryptionMethodToString(EncryptionMethod method) { - return method switch { + public static string EncryptionMethodToString(EncryptionMethod method) + { + return method switch + { EncryptionMethod.Certificate => "֤", EncryptionMethod.LogonCredentials => "ʹûƾ֤¼", _ => throw new Exception("ļܷ"), }; } - public static X509Certificate2 SelectCertificate() { + public static X509Certificate2 SelectCertificate() + { X509Store x509Store = new X509Store(); X509Certificate2Collection privateCollection = new X509Certificate2Collection(); - try { + try + { x509Store.Open(OpenFlags.OpenExistingOnly); X509Certificate2Collection certificates = x509Store.Certificates; X509Certificate2Collection foundCollection = certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, validOnly: false); - LongRunningActionForm.PerformOperation("Ч֤", showImmediately: true, delegate { + LongRunningActionForm.PerformOperation("Ч֤", showImmediately: true, delegate + { X509Certificate2Enumerator enumerator = foundCollection.GetEnumerator(); - while (enumerator.MoveNext()) { + while (enumerator.MoveNext()) + { X509Certificate2 current = enumerator.Current; - try { + try + { if (DecryptStringUsingCertificate(current, EncryptStringUsingCertificate(current, "test")) == "test") + { privateCollection.Add(current); + } + } + catch + { } - catch { } LongRunningActionForm.Instance.UpdateStatus(current.SimpleName()); } }); } - finally { + finally + { x509Store.Close(); } X509Certificate2Collection x509Certificate2Collection = X509Certificate2UI.SelectFromCollection(privateCollection, "ѡ֤", "ѡڰȫ洢֤", X509SelectionFlag.SingleSelection, Program.TheForm.Handle); return x509Certificate2Collection.Count != 1 ? null : x509Certificate2Collection[0]; } - public static X509Certificate2 GetCertificate(string thumbprint) { + public static X509Certificate2 GetCertificate(string thumbprint) + { X509Store x509Store = new X509Store(); x509Store.Open(OpenFlags.OpenExistingOnly); X509Certificate2Collection certificates = x509Store.Certificates; @@ -114,40 +149,49 @@ public static X509Certificate2 GetCertificate(string thumbprint) { return x509Certificate2Collection.Count != 1 ? null : x509Certificate2Collection[0]; } - public static string EncryptString(string plaintext, EncryptionSettings settings) { - switch (settings.EncryptionMethod.Value) { - case EncryptionMethod.LogonCredentials: - return EncryptStringUsingLocalUser(plaintext); - case EncryptionMethod.Certificate: - X509Certificate2 certificate = GetCertificate(settings.CredentialData.Value); - return EncryptStringUsingCertificate(certificate, plaintext); - default: - throw new NotImplementedException("ļܷ{0}".InvariantFormat(settings.EncryptionMethod.Value.ToString())); + public static string EncryptString(string plaintext, EncryptionSettings settings) + { + switch (settings.EncryptionMethod.Value) + { + case EncryptionMethod.LogonCredentials: + return EncryptStringUsingLocalUser(plaintext); + case EncryptionMethod.Certificate: + { + X509Certificate2 certificate = GetCertificate(settings.CredentialData.Value); + return EncryptStringUsingCertificate(certificate, plaintext); + } + default: + throw new NotImplementedException("ļܷ{0}".InvariantFormat(settings.EncryptionMethod.Value.ToString())); } } - private unsafe static string EncryptStringUsingLocalUser(string plaintext) { + private unsafe static string EncryptStringUsingLocalUser(string plaintext) + { Crypto.DataBlob optionalEntropy = default(Crypto.DataBlob); Crypto.CryptProtectPromptStruct promptStruct = default(Crypto.CryptProtectPromptStruct); if (string.IsNullOrEmpty(plaintext)) + { return null; - + } optionalEntropy.Size = 0; promptStruct.Size = 0; char[] array = plaintext.ToCharArray(); Crypto.DataBlob dataIn = default(Crypto.DataBlob); dataIn.Size = array.Length * 2; Crypto.DataBlob dataOut; - fixed (char* ptr = array) { + fixed (char* ptr = array) + { dataIn.Data = (IntPtr)ptr; - if (!Crypto.CryptProtectData(ref dataIn, null, ref optionalEntropy, (IntPtr)(void*)null, ref promptStruct, 0, out dataOut)) { + if (!Crypto.CryptProtectData(ref dataIn, null, ref optionalEntropy, (IntPtr)(void*)null, ref promptStruct, 0, out dataOut)) + { FormTools.ErrorDialog("޷"); return null; } } byte* ptr2 = (byte*)(void*)dataOut.Data; byte[] array2 = new byte[dataOut.Size]; - for (int i = 0; i < array2.Length; i++) { + for (int i = 0; i < array2.Length; i++) + { array2[i] = ptr2[i]; } string result = Convert.ToBase64String(array2); @@ -155,36 +199,45 @@ private unsafe static string EncryptStringUsingLocalUser(string plaintext) { return result; } - private static string EncryptStringUsingCertificate(X509Certificate2 cert, string plaintext) { + private static string EncryptStringUsingCertificate(X509Certificate2 cert, string plaintext) + { RSACryptoServiceProvider rSACryptoServiceProvider = (RSACryptoServiceProvider)cert.PublicKey.Key; byte[] inArray = rSACryptoServiceProvider.Encrypt(Encoding.UTF8.GetBytes(plaintext), fOAEP: false); return Convert.ToBase64String(inArray); } - public static string DecryptString(string encryptedString, EncryptionSettings settings) { + public static string DecryptString(string encryptedString, EncryptionSettings settings) + { if (string.IsNullOrEmpty(encryptedString)) + { return encryptedString; - - switch (settings.EncryptionMethod.Value) { - case EncryptionMethod.LogonCredentials: - return DecryptStringUsingLocalUser(encryptedString); - case EncryptionMethod.Certificate: - X509Certificate2 certificate = GetCertificate(settings.CredentialData.Value); - if (certificate == null) - throw new Exception("δҵָơ{1}֤顰{0}".InvariantFormat(settings.CredentialName.Value, settings.CredentialData.Value)); - - return DecryptStringUsingCertificate(certificate, encryptedString); - default: - throw new NotImplementedException("ļܷ{0}".InvariantFormat(settings.EncryptionMethod.Value.ToString())); + } + switch (settings.EncryptionMethod.Value) + { + case EncryptionMethod.LogonCredentials: + return DecryptStringUsingLocalUser(encryptedString); + case EncryptionMethod.Certificate: + { + X509Certificate2 certificate = GetCertificate(settings.CredentialData.Value); + if (certificate == null) + { + throw new Exception("δҵָơ{1}֤顰{0}".InvariantFormat(settings.CredentialName.Value, settings.CredentialData.Value)); + } + return DecryptStringUsingCertificate(certificate, encryptedString); + } + default: + throw new NotImplementedException("ļܷ{0}".InvariantFormat(settings.EncryptionMethod.Value.ToString())); } } - private unsafe static string DecryptStringUsingLocalUser(string encryptedString) { + private unsafe static string DecryptStringUsingLocalUser(string encryptedString) + { Crypto.DataBlob optionalEntropy = default(Crypto.DataBlob); Crypto.CryptProtectPromptStruct promptStruct = default(Crypto.CryptProtectPromptStruct); if (string.IsNullOrEmpty(encryptedString)) + { return string.Empty; - + } optionalEntropy.Size = 0; promptStruct.Size = 0; byte[] array = Convert.FromBase64String(encryptedString); @@ -192,14 +245,17 @@ private unsafe static string DecryptStringUsingLocalUser(string encryptedString) dataIn.Size = array.Length; Crypto.DataBlob dataOut; string result; - fixed (byte* ptr = array) { + fixed (byte* ptr = array) + { dataIn.Data = (IntPtr)ptr; if (!Crypto.CryptUnprotectData(ref dataIn, null, ref optionalEntropy, (IntPtr)(void*)null, ref promptStruct, 0, out dataOut)) + { throw new Exception("ʹ {0} ƾ֤ʧ".InvariantFormat(CredentialsUI.GetLoggedInUser())); - + } char* ptr2 = (char*)(void*)dataOut.Data; char[] array2 = new char[dataOut.Size / 2]; - for (int i = 0; i < array2.Length; i++) { + for (int i = 0; i < array2.Length; i++) + { array2[i] = ptr2[i]; } result = new string(array2); @@ -208,9 +264,12 @@ private unsafe static string DecryptStringUsingLocalUser(string encryptedString) return result; } - private static string DecryptStringUsingCertificate(X509Certificate2 cert, string encryptedString) { - if (string.IsNullOrEmpty(encryptedString) || !cert.HasPrivateKey) + private static string DecryptStringUsingCertificate(X509Certificate2 cert, string encryptedString) + { + if (string.IsNullOrEmpty(encryptedString)) + { return null; + } RSACryptoServiceProvider rSACryptoServiceProvider = (RSACryptoServiceProvider)cert.PrivateKey; byte[] bytes = rSACryptoServiceProvider.Decrypt(Convert.FromBase64String(encryptedString), fOAEP: false); return Encoding.UTF8.GetString(bytes); diff --git a/RdcMan/EncryptionMethod.cs b/RdcMan/EncryptionMethod.cs index aecff94..5d1da5b 100644 --- a/RdcMan/EncryptionMethod.cs +++ b/RdcMan/EncryptionMethod.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public enum EncryptionMethod { +namespace RdcMan +{ + public enum EncryptionMethod + { LogonCredentials, Certificate } diff --git a/RdcMan/EncryptionSettings.cs b/RdcMan/EncryptionSettings.cs index 6004503..cef11e3 100644 --- a/RdcMan/EncryptionSettings.cs +++ b/RdcMan/EncryptionSettings.cs @@ -1,9 +1,11 @@ using System.Collections.Generic; using System.Windows.Forms; -namespace RdcMan { - public class EncryptionSettings : SettingsGroup { - //public const string TabName = ""; +namespace RdcMan +{ + public class EncryptionSettings : SettingsGroup + { + //public const string TabName = "Encryption Settings"; private static Dictionary _settingProperties; @@ -18,20 +20,24 @@ public class EncryptionSettings : SettingsGroup { [Setting("credentialData")] public StringSetting CredentialData { get; private set; } - static EncryptionSettings() { + static EncryptionSettings() + { typeof(EncryptionSettings).GetSettingProperties(out _settingProperties); _settingProperties["CredentialName"].Attribute.DefaultValue = CredentialsUI.GetLoggedInUser(); } public EncryptionSettings() - : base("", "encryptionSettings") { + : base("", "encryptionSettings") + { } - public override TabPage CreateTabPage(TabbedSettingsDialog dialog) { + public override TabPage CreateTabPage(TabbedSettingsDialog dialog) + { return new EncryptionSettingsTabPage(dialog, this); } - protected override void Copy(RdcTreeNode node) { + protected override void Copy(RdcTreeNode node) + { Copy(node.EncryptionSettings); } } diff --git a/RdcMan/EncryptionSettingsTabPage.cs b/RdcMan/EncryptionSettingsTabPage.cs index 0a3ce87..0efbeb8 100644 --- a/RdcMan/EncryptionSettingsTabPage.cs +++ b/RdcMan/EncryptionSettingsTabPage.cs @@ -3,8 +3,10 @@ using System.Security.Cryptography.X509Certificates; using System.Windows.Forms; -namespace RdcMan { - public class EncryptionSettingsTabPage : SettingsTabPage { +namespace RdcMan +{ + public class EncryptionSettingsTabPage : SettingsTabPage + { public InheritanceControl InheritEncryptionSettings; protected ValueComboBox _passwordEncryptionMethodCombo; @@ -18,16 +20,19 @@ public class EncryptionSettingsTabPage : SettingsTabPage { private EncryptionMethod _passwordEncryptionMethodPrevious; public EncryptionSettingsTabPage(TabbedSettingsDialog dialog, EncryptionSettings settings) - : base(dialog, settings) { - int num = 0; + : base(dialog, settings) + { + int tabIndex = 0; int rowIndex = 0; - CreateInheritanceControl(ref rowIndex, ref num); - if (base.InheritanceControl != null) { - base.InheritanceControl.EnabledChanged += delegate { + CreateInheritanceControl(ref rowIndex, ref tabIndex); + if (base.InheritanceControl != null) + { + base.InheritanceControl.EnabledChanged += delegate + { PasswordEncryptionMethodCombo_Changed(null, null); }; } - _passwordEncryptionMethodCombo = FormTools.AddLabeledEnumDropDown(this, "ܣ", base.Settings.EncryptionMethod, ref rowIndex, ref num, Encryption.EncryptionMethodToString); + _passwordEncryptionMethodCombo = FormTools.AddLabeledEnumDropDown(this, "ܣ", base.Settings.EncryptionMethod, ref rowIndex, ref tabIndex, Encryption.EncryptionMethodToString); _passwordEncryptionMethodCombo.Enter += PasswordEncryptionMethodCombo_Enter; _passwordEncryptionMethodCombo.SelectedIndexChanged += PasswordEncryptionMethodCombo_Changed; _passwordEncryptionDataLabel = FormTools.NewLabel(string.Empty, 0, rowIndex); @@ -35,7 +40,7 @@ public EncryptionSettingsTabPage(TabbedSettingsDialog dialog, EncryptionSettings Enabled = false, Location = FormTools.NewLocation(1, rowIndex++), Width = 340, - TabIndex = num++, + TabIndex = tabIndex++, TextAlign = ContentAlignment.MiddleLeft }; _passwordEncryptionDataButton.Click += PasswordEncryptionMethodButton_Click; @@ -44,8 +49,10 @@ public EncryptionSettingsTabPage(TabbedSettingsDialog dialog, EncryptionSettings base.Controls.Add(_passwordEncryptionDataLabel, _passwordEncryptionDataButton, _passwordEncryptionDataInfoLabel); } - protected override void UpdateControls() { - if (base.Settings.EncryptionMethod.Value == EncryptionMethod.Certificate) { + protected override void UpdateControls() + { + if (base.Settings.EncryptionMethod.Value == EncryptionMethod.Certificate) + { X509Certificate2 certificate = Encryption.GetCertificate(base.Settings.CredentialData.Value); _passwordEncryptionDataButton.Tag = certificate; } @@ -54,51 +61,65 @@ protected override void UpdateControls() { PasswordEncryptionMethodCombo_Changed(null, null); } - protected override void UpdateSettings() { + protected override void UpdateSettings() + { base.UpdateSettings(); X509Certificate2 x509Certificate = (X509Certificate2)_passwordEncryptionDataButton.Tag; base.Settings.CredentialData.Value = ((x509Certificate != null) ? x509Certificate.Thumbprint : string.Empty); base.Settings.CredentialName.Value = _passwordEncryptionDataButton.Text; } - private void PasswordEncryptionMethodCombo_Enter(object sender, EventArgs e) { + private void PasswordEncryptionMethodCombo_Enter(object sender, EventArgs e) + { _passwordEncryptionMethodPrevious = _passwordEncryptionMethodCombo.SelectedValue; } - private void PasswordEncryptionMethodCombo_Changed(object sender, EventArgs e) { - switch (_passwordEncryptionMethodCombo.SelectedValue) { - case EncryptionMethod.LogonCredentials: - _passwordEncryptionDataLabel.Text = "û"; - _passwordEncryptionDataButton.Text = CredentialsUI.GetLoggedInUser(); - _passwordEncryptionDataButton.Tag = null; - _passwordEncryptionDataButton.Enabled = false; - _passwordEncryptionDataInfoLabel.Text = string.Empty; - break; - case EncryptionMethod.Certificate: { - X509Certificate2 x509Certificate = _passwordEncryptionDataButton.Tag as X509Certificate2; - if (x509Certificate == null) { - try { - base.Enabled = false; - x509Certificate = Encryption.SelectCertificate(); - } - finally { - base.Enabled = true; - } + private void PasswordEncryptionMethodCombo_Changed(object sender, EventArgs e) + { + switch (_passwordEncryptionMethodCombo.SelectedValue) + { + case EncryptionMethod.LogonCredentials: + _passwordEncryptionDataLabel.Text = "û"; + _passwordEncryptionDataButton.Text = CredentialsUI.GetLoggedInUser(); + _passwordEncryptionDataButton.Tag = null; + _passwordEncryptionDataButton.Enabled = false; + _passwordEncryptionDataInfoLabel.Text = string.Empty; + break; + case EncryptionMethod.Certificate: + { + X509Certificate2 x509Certificate = _passwordEncryptionDataButton.Tag as X509Certificate2; + if (x509Certificate == null) + { + try + { + base.Enabled = false; + x509Certificate = Encryption.SelectCertificate(); } - if (x509Certificate != null) - SetSelectedCertificate(x509Certificate); - else - _passwordEncryptionMethodCombo.SelectedValue = _passwordEncryptionMethodPrevious; - break; + finally + { + base.Enabled = true; + } + } + if (x509Certificate != null) + { + SetSelectedCertificate(x509Certificate); } - default: + else + { + _passwordEncryptionMethodCombo.SelectedValue = _passwordEncryptionMethodPrevious; + } + break; + } + default: throw new NotImplementedException("ļܷ{0}".InvariantFormat(_passwordEncryptionMethodCombo.SelectedValue.ToString())); } _passwordEncryptionMethodPrevious = _passwordEncryptionMethodCombo.SelectedValue; } - protected void SetSelectedCertificate(X509Certificate2 cert) { - if (cert != null) { + protected void SetSelectedCertificate(X509Certificate2 cert) + { + if (cert != null) + { _passwordEncryptionDataButton.Text = cert.SimpleName(); _passwordEncryptionDataButton.Tag = cert; _passwordEncryptionDataButton.Enabled = _passwordEncryptionMethodCombo.Enabled; @@ -107,13 +128,16 @@ protected void SetSelectedCertificate(X509Certificate2 cert) { } } - private void PasswordEncryptionMethodButton_Click(object sender, EventArgs e) { + private void PasswordEncryptionMethodButton_Click(object sender, EventArgs e) + { X509Certificate2 selectedCertificate; - try { + try + { base.Enabled = false; selectedCertificate = Encryption.SelectCertificate(); } - finally { + finally + { base.Enabled = true; } SetSelectedCertificate(selectedCertificate); diff --git a/RdcMan/EnumMenuItem.cs b/RdcMan/EnumMenuItem.cs index 1907eef..7f9c686 100644 --- a/RdcMan/EnumMenuItem.cs +++ b/RdcMan/EnumMenuItem.cs @@ -1,19 +1,24 @@ -namespace RdcMan { - internal abstract class EnumMenuItem : RdcMenuItem { +namespace RdcMan +{ + internal abstract class EnumMenuItem : RdcMenuItem + { protected abstract T Value { get; set; } - protected EnumMenuItem(string text, T value) { + protected EnumMenuItem(string text, T value) + { Text = text; base.Tag = value; } - protected override void OnClick() { + protected override void OnClick() + { Value = (T)base.Tag; Program.Preferences.NeedToSave = true; } - public override void Update() { + public override void Update() + { base.Checked = base.Tag.Equals(Value); } } -} \ No newline at end of file +} diff --git a/RdcMan/EnumSetting.cs b/RdcMan/EnumSetting.cs index a18edcb..6cd9ba1 100644 --- a/RdcMan/EnumSetting.cs +++ b/RdcMan/EnumSetting.cs @@ -1,22 +1,33 @@ using System; using System.Xml; -namespace RdcMan { - public class EnumSetting : Setting where TEnum : struct { +namespace RdcMan +{ + public class EnumSetting : Setting where TEnum : struct + { public EnumSetting(object o) - : base(o) { + : base(o) + { } - public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) { + public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) + { if (int.TryParse(xmlNode.InnerText, out var result)) + { base.Value = (TEnum)(object)result; + } else if (bool.TryParse(xmlNode.InnerText, out bool result2)) + { base.Value = (TEnum)(object)(result2 ? 1 : 0); + } else + { base.Value = (TEnum)Enum.Parse(typeof(TEnum), xmlNode.InnerText); + } } - public override void WriteXml(XmlTextWriter tw, RdcTreeNode node) { + public override void WriteXml(XmlTextWriter tw, RdcTreeNode node) + { tw.WriteString(base.Value.ToString()); } } diff --git a/RdcMan/FavoriteServerRef.cs b/RdcMan/FavoriteServerRef.cs index 42082f2..a32690f 100644 --- a/RdcMan/FavoriteServerRef.cs +++ b/RdcMan/FavoriteServerRef.cs @@ -1,10 +1,14 @@ -namespace RdcMan { - internal class FavoriteServerRef : ServerRef { +namespace RdcMan +{ + internal class FavoriteServerRef : ServerRef + { public FavoriteServerRef(Server server) - : base(server) { + : base(server) + { } - public override bool CanRemove(bool popUI) { + public override bool CanRemove(bool popUI) + { return AllowEdit(popUI); } } diff --git a/RdcMan/FavoritesGroup.cs b/RdcMan/FavoritesGroup.cs index 168f6b9..299442f 100644 --- a/RdcMan/FavoritesGroup.cs +++ b/RdcMan/FavoritesGroup.cs @@ -1,32 +1,39 @@ using System.ComponentModel.Composition; -namespace RdcMan { +namespace RdcMan +{ [Export(typeof(IBuiltInVirtualGroup))] - internal class FavoritesGroup : BuiltInVirtualGroup, IServerRefFactory { + internal class FavoritesGroup : BuiltInVirtualGroup, IServerRefFactory + { public static FavoritesGroup Instance { get; private set; } protected override string XmlNodeName => "favorites"; - private FavoritesGroup() { + private FavoritesGroup() + { base.Text = "ղؼ"; Instance = this; } - public override FavoriteServerRef AddReference(ServerBase serverBase) { + public override FavoriteServerRef AddReference(ServerBase serverBase) + { base.IsInTree = true; return base.AddReference(serverBase); } - public override bool CanDropServers() { + public override bool CanDropServers() + { return true; } - public override bool HandleMove(RdcTreeNode childNode) { + public override bool HandleMove(RdcTreeNode childNode) + { AddReference(childNode as ServerBase); return true; } - public ServerRef Create(Server server) { + public ServerRef Create(Server server) + { return new FavoriteServerRef(server); } } diff --git a/RdcMan/FileGroup.cs b/RdcMan/FileGroup.cs index 7217d2e..f0b0e3d 100644 --- a/RdcMan/FileGroup.cs +++ b/RdcMan/FileGroup.cs @@ -5,8 +5,10 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { - public class FileGroup : GroupBase { +namespace RdcMan +{ + public class FileGroup : GroupBase + { internal const string XmlNodeName = "file"; protected new static Dictionary NodeActions; @@ -21,37 +23,50 @@ public class FileGroup : GroupBase { public string Pathname { get; set; } - static FileGroup() { + static FileGroup() + { NodeActions = new Dictionary(GroupBase.NodeActions); - NodeActions["credentialsProfiles"] = delegate (XmlNode childNode, RdcTreeNode parent, ICollection errors) { + NodeActions["credentialsProfiles"] = delegate(XmlNode childNode, RdcTreeNode parent, ICollection errors) + { (parent as FileGroup).CredentialsProfiles.ReadXml(childNode, ProfileScope.File, parent, errors); }; ServerTree.Instance.GroupChanged += OnGroupChanged; ServerTree.Instance.ServerChanged += OnServerChanged; } - private static void OnServerChanged(ServerChangedEventArgs e) { - if (e.ChangeType.HasFlag(ChangeType.TreeChanged) || e.ChangeType.HasFlag(ChangeType.PropertyChanged)) { + private static void OnServerChanged(ServerChangedEventArgs e) + { + if (e.ChangeType.HasFlag(ChangeType.TreeChanged) || e.ChangeType.HasFlag(ChangeType.PropertyChanged)) + { FileGroup fileGroup = e.Server.FileGroup; if (fileGroup != null) + { fileGroup.HasChangedSinceWrite = true; + } } } - private static void OnGroupChanged(GroupChangedEventArgs e) { - if (e.ChangeType.HasFlag(ChangeType.TreeChanged) || e.ChangeType.HasFlag(ChangeType.PropertyChanged)) { + private static void OnGroupChanged(GroupChangedEventArgs e) + { + if (e.ChangeType.HasFlag(ChangeType.TreeChanged) || e.ChangeType.HasFlag(ChangeType.PropertyChanged)) + { FileGroup fileGroup = e.Group.FileGroup; if (fileGroup != null) + { fileGroup.HasChangedSinceWrite = true; + } } } - internal FileGroup(string pathname) { + internal FileGroup(string pathname) + { Pathname = Path.GetFullPath(pathname); - if (File.Exists(Pathname)) { + if (File.Exists(Pathname)) + { base.IsReadOnly = File.GetAttributes(Pathname).HasFlag(FileAttributes.ReadOnly); } - else { + else + { base.Properties.GroupName.Value = Path.GetFileNameWithoutExtension(Pathname); base.Text = base.Properties.GroupName.Value; } @@ -62,55 +77,67 @@ internal FileGroup(string pathname) { base.AllSettingsGroups.Add(EncryptionSettings); } - public string GetFilename() { + public string GetFilename() + { return Path.GetFileName(Pathname); } - public string GetDirectory() { + public string GetDirectory() + { return Path.GetDirectoryName(Pathname); } - protected override void InitSettings() { + protected override void InitSettings() + { ((RdcTreeNode)this).Properties = new FileGroupSettings(); base.InitSettings(); } - internal override void ReadXml(XmlNode xmlNode, ICollection errors) { + internal override void ReadXml(XmlNode xmlNode, ICollection errors) + { ReadXml(NodeActions, xmlNode, errors); base.Text = base.Properties.GroupName.Value; - if (base.IsReadOnly) { + if (base.IsReadOnly) + { base.Text += " {RO}"; } } - internal override void WriteXml(XmlTextWriter tw) { + internal override void WriteXml(XmlTextWriter tw) + { tw.WriteStartElement("file"); CredentialsProfiles.WriteXml(tw, this); base.WriteXml(tw); tw.WriteEndElement(); } - public sealed override bool ConfirmRemove(bool askUser) { + public sealed override bool ConfirmRemove(bool askUser) + { FormTools.InformationDialog("ʹļ˵ر " + base.Text + " "); return false; } - public override void DoPropertiesDialog(Form parentForm, string activeTabName) { + public override void DoPropertiesDialog(Form parentForm, string activeTabName) + { using FileGroupPropertiesDialog fileGroupPropertiesDialog = FileGroupPropertiesDialog.NewPropertiesDialog(this, parentForm); fileGroupPropertiesDialog.SetActiveTab(activeTabName); - if (fileGroupPropertiesDialog.ShowDialog() == DialogResult.OK) { + if (fileGroupPropertiesDialog.ShowDialog() == DialogResult.OK) + { UpdateSettings(fileGroupPropertiesDialog); ServerTree.Instance.OnNodeChanged(this, ChangeType.PropertyChanged); } } - internal void CheckCredentials() { + internal void CheckCredentials() + { Dictionary> missingProfiles = new Dictionary>(StringComparer.OrdinalIgnoreCase); - this.VisitNodes(delegate (RdcTreeNode node) { + this.VisitNodes(delegate(RdcTreeNode node) + { CheckCredentials(node, node.LogonCredentials, "¼ƾ֤", missingProfiles); CheckCredentials(node, node.GatewaySettings, "", missingProfiles); }); - if (missingProfiles.Count <= 0) { + if (missingProfiles.Count <= 0) + { return; } StringBuilder stringBuilder = new StringBuilder(); @@ -118,24 +145,30 @@ internal void CheckCredentials() { .AppendLine("ӵ༭Ե֮ǰȱٵļοʧ") .AppendLine(" ȷ ϸϢƵ塣") .AppendLine(); - foreach (KeyValuePair> item in missingProfiles) { + foreach (KeyValuePair> item in missingProfiles) + { stringBuilder.AppendLine("ļƣ" + item.Key); stringBuilder.AppendFormat("ڣ"); - foreach (string item2 in item.Value) { + foreach (string item2 in item.Value) + { stringBuilder.Append(" " + item2); } stringBuilder.AppendLine().AppendLine(); } DialogResult dialogResult = FormTools.ExclamationDialog(stringBuilder.ToString(), MessageBoxButtons.OKCancel); - if (dialogResult == DialogResult.OK) { + if (dialogResult == DialogResult.OK) + { Clipboard.SetText(stringBuilder.ToString()); } } - private void CheckCredentials(RdcTreeNode node, LogonCredentials credentials, string name, Dictionary> missingProfiles) { - if (credentials != null && credentials.InheritSettingsType.Mode != 0 && !node.ResolveCredentials(credentials)) { + private void CheckCredentials(RdcTreeNode node, LogonCredentials credentials, string name, Dictionary> missingProfiles) + { + if (credentials != null && credentials.InheritSettingsType.Mode != 0 && !node.ResolveCredentials(credentials)) + { string key = LogonCredentials.ConstructQualifiedName(credentials); - if (!missingProfiles.TryGetValue(key, out var value)) { + if (!missingProfiles.TryGetValue(key, out var value)) + { List list2 = (missingProfiles[key] = new List()); value = list2; } diff --git a/RdcMan/FileGroupPropertiesDialog.cs b/RdcMan/FileGroupPropertiesDialog.cs index cd719a0..d81a2cd 100644 --- a/RdcMan/FileGroupPropertiesDialog.cs +++ b/RdcMan/FileGroupPropertiesDialog.cs @@ -1,18 +1,23 @@ using System.Windows.Forms; -namespace RdcMan { - internal class FileGroupPropertiesDialog : GroupBasePropertiesDialog { +namespace RdcMan +{ + internal class FileGroupPropertiesDialog : GroupBasePropertiesDialog + { protected FileGroupPropertiesDialog(FileGroup group, string dialogTitle, string acceptButtonText, Form parentForm) - : base(group, dialogTitle, acceptButtonText, parentForm) { + : base(group, dialogTitle, acceptButtonText, parentForm) + { } - public static FileGroupPropertiesDialog NewPropertiesDialog(FileGroup group, Form parentForm) { + public static FileGroupPropertiesDialog NewPropertiesDialog(FileGroup group, Form parentForm) + { FileGroupPropertiesDialog fileGroupPropertiesDialog = new FileGroupPropertiesDialog(group, group.Text + " ļ", "ȷ", parentForm); fileGroupPropertiesDialog.CreateControls(group); return fileGroupPropertiesDialog; } - public override void CreateControls(RdcTreeNode settings) { + public override void CreateControls(RdcTreeNode settings) + { FileGroupPropertiesTabPage page = (FileGroupPropertiesTabPage)(base.PropertiesPage = settings.Properties.CreateTabPage(this) as FileGroupPropertiesTabPage); AddTabPage(page); base.PropertiesPage.ParentGroupChanged += base.PopulateCredentialsProfiles; diff --git a/RdcMan/FileGroupPropertiesTabPage.cs b/RdcMan/FileGroupPropertiesTabPage.cs index 4f954e2..20d29ad 100644 --- a/RdcMan/FileGroupPropertiesTabPage.cs +++ b/RdcMan/FileGroupPropertiesTabPage.cs @@ -1,19 +1,23 @@ using System.Windows.Forms; -namespace RdcMan { - internal class FileGroupPropertiesTabPage : GroupBasePropertiesTabPage { +namespace RdcMan +{ + internal class FileGroupPropertiesTabPage : GroupBasePropertiesTabPage + { private readonly TextBox _pathnameTextBox; public FileGroupPropertiesTabPage(TabbedSettingsDialog dialog, FileGroupSettings settings) - : base(dialog, settings, settings.Name) { + : base(dialog, settings, settings.Name) + { int rowIndex = 0; - int num = 0; - AddGroupName(ref rowIndex, ref num); - _pathnameTextBox = FormTools.AddLabeledTextBox(this, "·ƣ", ref rowIndex, ref num); - AddComment(ref rowIndex, ref num).Setting = base.Settings.Comment; + int tabIndex = 0; + AddGroupName(ref rowIndex, ref tabIndex); + _pathnameTextBox = FormTools.AddLabeledTextBox(this, "·ƣ", ref rowIndex, ref tabIndex); + AddComment(ref rowIndex, ref tabIndex).Setting = base.Settings.Comment; } - protected override void UpdateControls() { + protected override void UpdateControls() + { base.UpdateControls(); _pathnameTextBox.Enabled = false; _pathnameTextBox.Text = ((base.Dialog as FileGroupPropertiesDialog).AssociatedNode as FileGroup).Pathname; diff --git a/RdcMan/FileGroupSettings.cs b/RdcMan/FileGroupSettings.cs index 2e4a298..56c2b92 100644 --- a/RdcMan/FileGroupSettings.cs +++ b/RdcMan/FileGroupSettings.cs @@ -2,35 +2,43 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { - public class FileGroupSettings : GroupSettings { +namespace RdcMan +{ + public class FileGroupSettings : GroupSettings + { //internal new const string TabName = "File Settings"; private static Dictionary _settingProperties; protected override Dictionary SettingProperties => _settingProperties; - static FileGroupSettings() { + static FileGroupSettings() + { typeof(FileGroupSettings).GetSettingProperties(out _settingProperties); } public FileGroupSettings() - : base("ļ") { + : base("ļ") + { } protected FileGroupSettings(string name) - : base(name) { + : base(name) + { } - public override TabPage CreateTabPage(TabbedSettingsDialog dialog) { + public override TabPage CreateTabPage(TabbedSettingsDialog dialog) + { return new FileGroupPropertiesTabPage(dialog, this); } - protected override void WriteSettings(XmlTextWriter tw, RdcTreeNode node) { + protected override void WriteSettings(XmlTextWriter tw, RdcTreeNode node) + { HashSet hashSet = new HashSet(); if (string.IsNullOrEmpty(base.Comment.Value)) + { hashSet.Add(base.Comment); - + } base.WriteSettings(tw, node, hashSet); } diff --git a/RdcMan/FileRequiredMenuItem.cs b/RdcMan/FileRequiredMenuItem.cs index 986f6db..07f8f2f 100644 --- a/RdcMan/FileRequiredMenuItem.cs +++ b/RdcMan/FileRequiredMenuItem.cs @@ -1,25 +1,31 @@ using System; -namespace RdcMan { - internal class FileRequiredMenuItem : RdcMenuItem { +namespace RdcMan +{ + internal class FileRequiredMenuItem : RdcMenuItem + { private readonly Action _clickDelegate; public FileRequiredMenuItem(string text, MenuNames name, Action clickDelegate) - : base(text) { + : base(text) + { base.Name = name.ToString(); _clickDelegate = clickDelegate; } public FileRequiredMenuItem(string text, MenuNames name, string shortcut, Action clickDelegate) - : this(text, name, clickDelegate) { + : this(text, name, clickDelegate) + { base.ShortcutKeyDisplayString = shortcut; } - public override void Update() { + public override void Update() + { Enabled = ServerTree.Instance.AnyOpenedEditableFiles(); } - protected override void OnClick() { + protected override void OnClick() + { _clickDelegate(); } } diff --git a/RdcMan/FindServersDialog.cs b/RdcMan/FindServersDialog.cs index fd674cd..98522ca 100644 --- a/RdcMan/FindServersDialog.cs +++ b/RdcMan/FindServersDialog.cs @@ -4,8 +4,10 @@ using System.Text.RegularExpressions; using System.Windows.Forms; -namespace RdcMan { - internal class FindServersDialog : SelectServersDialogBase { +namespace RdcMan +{ + internal class FindServersDialog : SelectServersDialogBase + { private string _previousFilterText; private List _servers; @@ -13,13 +15,14 @@ internal class FindServersDialog : SelectServersDialogBase { private TextBox _filterTextBox; public FindServersDialog() - : base("ҷ", "Select") { + : base("ҷ", "ѡ ") + { int rowIndex = 0; int num = 0; - AddLabel("Թ˷", ref rowIndex, ref num); + AddLabel("Թ˷", ref rowIndex, ref num); _filterTextBox = FormTools.NewTextBox(0, rowIndex++, num++); _filterTextBox.Enabled = true; - _filterTextBox.Width = 500; + _filterTextBox.Width = DialogWidth; _filterTextBox.TextChanged += Filter_TextChanged; base.Controls.Add(_filterTextBox); AddListView(ref rowIndex, ref num); @@ -32,92 +35,123 @@ public FindServersDialog() PopulateList(); } - protected override void OnClosed(EventArgs e) { - if (base.ListView.CheckedItems.Count == 0 && base.ListView.Items.Count > 0) { + protected override void OnClosed(EventArgs e) + { + if (base.ListView.CheckedItems.Count == 0 && base.ListView.Items.Count > 0) + { if (base.ListView.FocusedItem == null) + { base.ListView.FocusedItem = base.ListView.Items[0]; - + } base.ListView.FocusedItem.Checked = true; } } - private void CollectServers() { + private void CollectServers() + { _servers = new List(); - ServerTree.Instance.Nodes.VisitNodes(delegate (RdcTreeNode node) { + ServerTree.Instance.Nodes.VisitNodes(delegate(RdcTreeNode node) + { if (node is Server item) + { _servers.Add(item); + } }); } - private void PopulateList() { - try { + private void PopulateList() + { + try + { Regex regex = new Regex(_filterTextBox.Text, RegexOptions.IgnoreCase | RegexOptions.Compiled); base.ListView.BeginUpdate(); SuspendItemChecked(); base.ListView.Items.Clear(); - foreach (Server server in _servers) { - if (regex.IsMatch(server.FullPath)) + foreach (Server server in _servers) + { + if (regex.IsMatch(server.FullPath) || regex.IsMatch(server.ServerName)) + { base.ListView.Items.Add(CreateListViewItem(server)); + } } } - catch (Exception) { + catch (Exception) + { } - finally { + finally + { ResumeItemChecked(); base.ListView.EndUpdate(); } } - private void FilterList() { - try { + private void FilterList() + { + try + { Regex regex = new Regex(_filterTextBox.Text, RegexOptions.IgnoreCase | RegexOptions.Compiled); int num = 0; - while (num < base.ListView.Items.Count) { + while (num < base.ListView.Items.Count) + { Server server = base.ListView.Items[num].Tag as Server; - if (!regex.IsMatch(server.FullPath)) + if (!(regex.IsMatch(server.FullPath) || regex.IsMatch(server.ServerName))) + { base.ListView.Items.RemoveAt(num); + } else + { num++; + } } } - catch (Exception) { + catch (Exception) + { } } - private void ContextMenuPopup(object menuSender, EventArgs args) { + private void ContextMenuPopup(object menuSender, EventArgs args) + { ContextMenuStrip contextMenuStrip = menuSender as ContextMenuStrip; List selectedServers = base.SelectedServers.ToList(); - if (selectedServers.Count == 0) { + if (selectedServers.Count == 0) + { if (base.ListView.FocusedItem == null) + { return; - + } selectedServers.Add(base.ListView.FocusedItem.Tag as ServerBase); } contextMenuStrip.Items.Clear(); NodeHelper.AnyOrAllConnected(selectedServers, out var anyConnected, out var allConnected); - ToolStripMenuItem toolStripMenuItem = new DelegateMenuItem("(&C)", MenuNames.SessionConnect, delegate { + ToolStripMenuItem toolStripMenuItem = new DelegateMenuItem("(&C)", MenuNames.SessionConnect, delegate + { NodeHelper.ThrottledConnect(selectedServers); OK(); }); toolStripMenuItem.Enabled = !allConnected; contextMenuStrip.Items.Add(toolStripMenuItem); - toolStripMenuItem = new DelegateMenuItem("(&R)", MenuNames.SessionReconnect, delegate { - selectedServers.ForEach(delegate (ServerBase server) { + toolStripMenuItem = new DelegateMenuItem("(&R)", MenuNames.SessionReconnect, delegate + { + selectedServers.ForEach(delegate(ServerBase server) + { server.Reconnect(); }); OK(); }); toolStripMenuItem.Enabled = anyConnected; contextMenuStrip.Items.Add(toolStripMenuItem); - toolStripMenuItem = new DelegateMenuItem("Ͽ(&D)", MenuNames.SessionDisconnect, delegate { + toolStripMenuItem = new DelegateMenuItem("Ͽ(&D)", MenuNames.SessionDisconnect, delegate + { NodeHelper.ThrottledDisconnect(selectedServers); OK(); }); toolStripMenuItem.Enabled = anyConnected; contextMenuStrip.Items.Add(toolStripMenuItem); contextMenuStrip.Items.Add("-"); - toolStripMenuItem = new DelegateMenuItem("ע(%L)", MenuNames.SessionLogOff, delegate { - selectedServers.ForEach(delegate (ServerBase server) { + toolStripMenuItem = new DelegateMenuItem("ע(%L)", MenuNames.SessionLogOff, delegate + { + selectedServers.ForEach(delegate(ServerBase server) + { server.LogOff(); }); OK(); @@ -125,9 +159,12 @@ private void ContextMenuPopup(object menuSender, EventArgs args) { toolStripMenuItem.Enabled = !Policies.DisableLogOff && anyConnected; contextMenuStrip.Items.Add(toolStripMenuItem); contextMenuStrip.Items.Add("-"); - toolStripMenuItem = new DelegateMenuItem("ɾ(&V)", MenuNames.EditRemove, delegate { - if (!anyConnected || FormTools.YesNoDialog("лԾĻỰ ȷɾ") == DialogResult.Yes) { - selectedServers.ForEach(delegate (ServerBase server) { + toolStripMenuItem = new DelegateMenuItem("ɾ(&V)", MenuNames.EditRemove, delegate + { + if (!anyConnected || FormTools.YesNoDialog("лԾĻỰ ȷɾ") == DialogResult.Yes) + { + selectedServers.ForEach(delegate(ServerBase server) + { ServerTree.Instance.ConfirmRemove(server, askUser: false); }); Cancel(); @@ -135,20 +172,26 @@ private void ContextMenuPopup(object menuSender, EventArgs args) { }); contextMenuStrip.Items.Add(toolStripMenuItem); contextMenuStrip.Items.Add("-"); - contextMenuStrip.Items.Add(new DelegateMenuItem("ӵղؼ(&F)", MenuNames.EditAddToFavorites, delegate { - selectedServers.ForEach(delegate (ServerBase server) { + contextMenuStrip.Items.Add(new DelegateMenuItem("ӵղؼ(&F)", MenuNames.EditAddToFavorites, delegate + { + selectedServers.ForEach(delegate(ServerBase server) + { FavoritesGroup.Instance.AddReference(server); }); OK(); })); } - private void Filter_TextChanged(object sender, EventArgs e) { + private void Filter_TextChanged(object sender, EventArgs e) + { if (_filterTextBox.Text.StartsWith(_previousFilterText)) + { FilterList(); + } else + { PopulateList(); - + } _previousFilterText = _filterTextBox.Text; } } diff --git a/RdcMan/FormTools.cs b/RdcMan/FormTools.cs index 2563337..96a1cc9 100644 --- a/RdcMan/FormTools.cs +++ b/RdcMan/FormTools.cs @@ -3,11 +3,13 @@ using System.Drawing; using System.Windows.Forms; -namespace RdcMan { - public static class FormTools { +namespace RdcMan +{ + public static class FormTools + { public const int TabControlWidth = 520; - public const int TabControlHeight = 355; + public const int TabControlHeight = 350; public const int ControlHeight = 20; @@ -43,31 +45,38 @@ public static class FormTools { public const int GroupBoxWidth = 496; - public static int XPos(int colIndex) { + public static int XPos(int colIndex) + { return HorizontalMargin + IndexIndent * colIndex; } - public static int YPos(int rowIndex) { + public static int YPos(int rowIndex) + { return TopMargin + Indent * rowIndex; } - public static int YPosNoMargin(int rowIndex) { + public static int YPosNoMargin(int rowIndex) + { return Indent * rowIndex; } - public static Point TopLeftLocation() { + public static Point TopLeftLocation() + { return new Point(VerticalSpace, HorizontalSpace); } - public static Point NewLocation(int colIndex, int rowIndex) { + public static Point NewLocation(int colIndex, int rowIndex) + { return new Point(XPos(colIndex), YPos(rowIndex)); } - public static Point NewUngroupedLocation(int colIndex, int rowIndex) { + public static Point NewUngroupedLocation(int colIndex, int rowIndex) + { return new Point(TopMargin + LabelWidth * colIndex, YPos(rowIndex)); } - public static Label NewLabel(string text, int colIndex, int rowIndex) { + public static Label NewLabel(string text, int colIndex, int rowIndex) + { Label label = new Label { Location = NewLocation(colIndex, rowIndex), Text = text, @@ -77,7 +86,8 @@ public static Label NewLabel(string text, int colIndex, int rowIndex) { return label; } - public static RdcTextBox NewTextBox(int colIndex, int rowIndex, int tabIndex) { + public static RdcTextBox NewTextBox(int colIndex, int rowIndex, int tabIndex) + { RdcTextBox rdcTextBox = new RdcTextBox { Enabled = false, Location = NewLocation(colIndex, rowIndex), @@ -87,7 +97,8 @@ public static RdcTextBox NewTextBox(int colIndex, int rowIndex, int tabIndex) { return rdcTextBox; } - public static RdcTextBox NewTextBox(int colIndex, int rowIndex, int tabIndex, int height) { + public static RdcTextBox NewTextBox(int colIndex, int rowIndex, int tabIndex, int height) + { RdcTextBox rdcTextBox = new RdcTextBox { Location = NewLocation(colIndex, rowIndex), Size = new Size(TextBoxWidth, ControlHeight * height), @@ -99,7 +110,8 @@ public static RdcTextBox NewTextBox(int colIndex, int rowIndex, int tabIndex, in return rdcTextBox; } - public static RdcTextBox AddLabeledTextBox(Control parent, string text, ref int rowIndex, ref int tabIndex) { + public static RdcTextBox AddLabeledTextBox(Control parent, string text, ref int rowIndex, ref int tabIndex) + { Label value = NewLabel(text, 0, rowIndex); RdcTextBox rdcTextBox = NewTextBox(1, rowIndex++, tabIndex++); parent.Controls.Add(value); @@ -107,17 +119,20 @@ public static RdcTextBox AddLabeledTextBox(Control parent, string text, ref int return rdcTextBox; } - public static RdcTextBox AddLabeledTextBox(Control parent, string text, StringSetting setting, ref int rowIndex, ref int tabIndex) { + public static RdcTextBox AddLabeledTextBox(Control parent, string text, StringSetting setting, ref int rowIndex, ref int tabIndex) + { RdcTextBox rdcTextBox = AddLabeledTextBox(parent, text, ref rowIndex, ref tabIndex); rdcTextBox.Setting = setting; return rdcTextBox; } - public static RdcCheckBox NewCheckBox(string text, int colIndex, int rowIndex, int tabIndex) { + public static RdcCheckBox NewCheckBox(string text, int colIndex, int rowIndex, int tabIndex) + { return NewCheckBox(text, colIndex, rowIndex, tabIndex, TextBoxWidth); } - public static RdcCheckBox NewCheckBox(string text, int colIndex, int rowIndex, int tabIndex, int width) { + public static RdcCheckBox NewCheckBox(string text, int colIndex, int rowIndex, int tabIndex, int width) + { RdcCheckBox rdcCheckBox = new() { Location = NewLocation(colIndex, rowIndex), Size = new Size(width, ControlHeight), @@ -127,8 +142,10 @@ public static RdcCheckBox NewCheckBox(string text, int colIndex, int rowIndex, i return rdcCheckBox; } - public static RdcCheckBox AddCheckBox(Control parent, string text, BoolSetting setting, int colIndex, ref int rowIndex, ref int tabIndex) { - RdcCheckBox rdcCheckBox = new RdcCheckBox { + public static RdcCheckBox AddCheckBox(Control parent, string text, BoolSetting setting, int colIndex, ref int rowIndex, ref int tabIndex) + { + RdcCheckBox rdcCheckBox = new RdcCheckBox + { Setting = setting, Location = NewLocation(colIndex, rowIndex++), Size = new Size(TextBoxWidth, ControlHeight), @@ -139,11 +156,13 @@ public static RdcCheckBox AddCheckBox(Control parent, string text, BoolSetting s return rdcCheckBox; } - public static ValueComboBox AddLabeledEnumDropDown(Control parent, string text, ref int rowIndex, ref int tabIndex, Func toString) where TEnum : struct { + public static ValueComboBox AddLabeledEnumDropDown(Control parent, string text, ref int rowIndex, ref int tabIndex, Func toString) where TEnum : struct + { return AddLabeledValueDropDown(parent, text, ref rowIndex, ref tabIndex, toString, Helpers.EnumValues()); } - public static ValueComboBox AddLabeledValueDropDown(Control parent, string text, ref int rowIndex, ref int tabIndex, Func toString, IEnumerable values) { + public static ValueComboBox AddLabeledValueDropDown(Control parent, string text, ref int rowIndex, ref int tabIndex, Func toString, IEnumerable values) + { Label value = NewLabel(text, 0, rowIndex); ValueComboBox valueComboBox = new ValueComboBox(values, toString); SetDropDownProperties(valueComboBox, 1, rowIndex++, tabIndex++); @@ -152,7 +171,8 @@ public static ValueComboBox AddLabeledValueDropDown(Control pare return valueComboBox; } - public static ValueComboBox AddLabeledValueDropDown(Control parent, string text, Setting setting, ref int rowIndex, ref int tabIndex, Func toString, IEnumerable values) { + public static ValueComboBox AddLabeledValueDropDown(Control parent, string text, Setting setting, ref int rowIndex, ref int tabIndex, Func toString, IEnumerable values) + { Label value = NewLabel(text, 0, rowIndex); ValueComboBox valueComboBox = new ValueComboBox(setting, values, toString); SetDropDownProperties(valueComboBox, 1, rowIndex++, tabIndex++); @@ -161,7 +181,8 @@ public static ValueComboBox AddLabeledValueDropDown(Control pare return valueComboBox; } - public static ValueComboBox AddLabeledEnumDropDown(Control parent, string text, EnumSetting setting, ref int rowIndex, ref int tabIndex, Func toString) where TEnum : struct { + public static ValueComboBox AddLabeledEnumDropDown(Control parent, string text, EnumSetting setting, ref int rowIndex, ref int tabIndex, Func toString) where TEnum : struct + { Label value = NewLabel(text, 0, rowIndex); ValueComboBox valueComboBox = new ValueComboBox(setting, Helpers.EnumValues(), toString); SetDropDownProperties(valueComboBox, 1, rowIndex++, tabIndex++); @@ -170,29 +191,36 @@ public static ValueComboBox AddLabeledEnumDropDown(Control parent, return valueComboBox; } - private static void SetDropDownProperties(ComboBox comboBox, int colIndex, int rowIndex, int tabIndex) { + private static void SetDropDownProperties(ComboBox comboBox, int colIndex, int rowIndex, int tabIndex) + { comboBox.Location = NewLocation(colIndex, rowIndex); comboBox.Size = new Size(DropDownWidth, ControlHeight); comboBox.TabIndex = tabIndex; } - public static void LayoutGroupBox(GroupBox groupBox, int numCols, Control previousGroupBox) { + public static void LayoutGroupBox(GroupBox groupBox, int numCols, Control previousGroupBox) + { LayoutGroupBox(groupBox, numCols, previousGroupBox, 0, 0); } - public static void LayoutGroupBox(GroupBox groupBox, int numCols, Control previousControl, int rowIndex, int tabIndex) { + public static void LayoutGroupBox(GroupBox groupBox, int numCols, Control previousControl, int rowIndex, int tabIndex) + { int num = 0; - foreach (Control control in groupBox.Controls) { + foreach (Control control in groupBox.Controls) + { if (num == 1 && control.Width == TextBoxWidth) + { control.Width -= HorizontalMargin; - + } control.Location = NewLocation(num++, rowIndex); control.TabIndex = tabIndex; tabIndex += 2; if (!(control is Label)) + { control.TabStop = true; - - if (num == numCols) { + } + if (num == numCols) + { num = 0; rowIndex++; } @@ -200,34 +228,44 @@ public static void LayoutGroupBox(GroupBox groupBox, int numCols, Control previo groupBox.SizeAndLocate(previousControl); } - public static void AddControlsAndSizeGroup(this GroupBox groupBox, params Control[] controls) { + public static void AddControlsAndSizeGroup(this GroupBox groupBox, params Control[] controls) + { groupBox.Controls.AddRange(controls); - foreach (Control control in groupBox.Controls) { + foreach (Control control in groupBox.Controls) + { if (control.Width == TextBoxWidth) + { control.Width -= HorizontalMargin; + } } } - public static void SizeAndLocate(this GroupBox groupBox, Control previousControl) { - int num = HorizontalMargin; - if (previousControl != null) { + public static void SizeAndLocate(this GroupBox groupBox, Control previousControl) + { + int num = 8; + if (previousControl != null) + { groupBox.TabIndex = previousControl.TabIndex + 1; num += previousControl.Bottom; } else + { groupBox.TabIndex = 1; - + } groupBox.Location = new Point(HorizontalMargin, num); ResizeGroupBox(groupBox); } - public static void ResizeGroupBox(GroupBox groupBox) { + public static void ResizeGroupBox(GroupBox groupBox) + { int num = ComputeControlHeightFromChildren(groupBox); groupBox.Size = new Size(GroupBoxWidth, num + HorizontalMargin); } - public static TabPage NewTabPage(string name) { - TabPage tabPage = new TabPage { + public static TabPage NewTabPage(string name) + { + TabPage tabPage = new TabPage + { Location = TopLeftLocation(), Size = new Size(TabPageWidth, TabPageHeight), Text = name @@ -236,18 +274,22 @@ public static TabPage NewTabPage(string name) { return tabPage; } - public static TabPage NewTabPage(this TabControl parent, string name) { + public static TabPage NewTabPage(this TabControl parent, string name) + { TabPage tabPage = NewTabPage(name); parent.Controls.Add(tabPage); return tabPage; } - public static Control[] NewSizeRadios() { + public static Control[] NewSizeRadios() + { Control[] array = new Control[SizeHelper.StockSizes.Length]; int num = 0; Size[] stockSizes = SizeHelper.StockSizes; - foreach (Size size in stockSizes) { - array[num++] = new RadioButton { + foreach (Size size in stockSizes) + { + array[num++] = new RadioButton + { Tag = size, Text = size.ToFormattedString() }; @@ -255,10 +297,12 @@ public static Control[] NewSizeRadios() { return array; } - public static void AddButtonsAndSizeForm(Form form, Button okButton, Button cancelButton) { + public static void AddButtonsAndSizeForm(Form form, Button okButton, Button cancelButton) + { int num = 0; int num2 = 0; - foreach (Control control in form.Controls) { + foreach (Control control in form.Controls) + { num = Math.Max(num, control.Right); num2 = Math.Max(num2, control.Bottom); } @@ -272,51 +316,63 @@ public static void AddButtonsAndSizeForm(Form form, Button okButton, Button canc form.ClientSize = new Size(num, okButton.Location.Y + okButton.Height + TopMargin); } - public static int ComputeControlHeightFromChildren(Control control) { + public static int ComputeControlHeightFromChildren(Control control) + { int num = 0; - foreach (Control control2 in control.Controls) { + foreach (Control control2 in control.Controls) + { num = Math.Max(num, control2.Bottom); } return num; } - public static void ErrorDialog(string text) { + public static void ErrorDialog(string text) + { MessageBox.Show(Program.TheForm, text, "RDCMan Error", MessageBoxButtons.OK, MessageBoxIcon.Hand); } - public static void InformationDialog(string text) { + public static void InformationDialog(string text) + { MessageBox.Show(Program.TheForm, text, "RDCMan", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } - public static DialogResult ExclamationDialog(string text, MessageBoxButtons buttons) { + public static DialogResult ExclamationDialog(string text, MessageBoxButtons buttons) + { return MessageBox.Show(Program.TheForm, text, "RDCMan", buttons, MessageBoxIcon.Exclamation); } - public static DialogResult YesNoDialog(string text) { + public static DialogResult YesNoDialog(string text) + { return YesNoDialog(Program.TheForm, text, MessageBoxDefaultButton.Button2); } - public static DialogResult YesNoDialog(string text, MessageBoxDefaultButton defaultButton) { + public static DialogResult YesNoDialog(string text, MessageBoxDefaultButton defaultButton) + { return YesNoDialog(Program.TheForm, text, defaultButton); } - public static DialogResult YesNoDialog(Form owner, string text) { + public static DialogResult YesNoDialog(Form owner, string text) + { return YesNoDialog(owner, text, MessageBoxDefaultButton.Button2); } - public static DialogResult YesNoDialog(Form owner, string text, MessageBoxDefaultButton defaultButton) { + public static DialogResult YesNoDialog(Form owner, string text, MessageBoxDefaultButton defaultButton) + { return MessageBox.Show(owner, text, "RDCMan", MessageBoxButtons.YesNo, MessageBoxIcon.Question, defaultButton); } - public static DialogResult YesNoCancelDialog(string text) { + public static DialogResult YesNoCancelDialog(string text) + { return YesNoCancelDialog(text, MessageBoxDefaultButton.Button2); } - public static DialogResult YesNoCancelDialog(string text, MessageBoxDefaultButton defaultButton) { + public static DialogResult YesNoCancelDialog(string text, MessageBoxDefaultButton defaultButton) + { return MessageBox.Show(Program.TheForm, text, "RDCMan", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, defaultButton); } - public static void ScaleAndLayout(this Form form) { + public static void ScaleAndLayout(this Form form) + { form.PerformAutoScale(); form.ResumeLayout(performLayout: false); form.PerformLayout(); diff --git a/RdcMan/GatewaySettings.cs b/RdcMan/GatewaySettings.cs index 49071a7..fbd9f61 100644 --- a/RdcMan/GatewaySettings.cs +++ b/RdcMan/GatewaySettings.cs @@ -1,11 +1,13 @@ using System.Collections.Generic; using System.Windows.Forms; -namespace RdcMan { - public class GatewaySettings : LogonCredentials { - //public new const string TabName = ""; +namespace RdcMan +{ + public class GatewaySettings : LogonCredentials + { + //public new const string TabName = "Gateway Settings"; - private static readonly Dictionary _settingProperties; + private static Dictionary _settingProperties; protected override Dictionary SettingProperties => _settingProperties; @@ -27,19 +29,23 @@ public class GatewaySettings : LogonCredentials { [Setting("enableCredSspSupport", DefaultValue = true, IsObsolete = true)] public BoolSetting EnableCredentialSspSupport { get; private set; } - static GatewaySettings() { + static GatewaySettings() + { typeof(GatewaySettings).GetSettingProperties(out _settingProperties); } public GatewaySettings() - : base("", "gatewaySettings") { + : base("", "gatewaySettings") + { } - public override TabPage CreateTabPage(TabbedSettingsDialog dialog) { + public override TabPage CreateTabPage(TabbedSettingsDialog dialog) + { return new GatewaySettingsTabPage(dialog, this); } - protected override void Copy(RdcTreeNode node) { + protected override void Copy(RdcTreeNode node) + { Copy(node.GatewaySettings); } } diff --git a/RdcMan/GatewaySettingsTabPage.cs b/RdcMan/GatewaySettingsTabPage.cs index 11d5208..8ed7790 100644 --- a/RdcMan/GatewaySettingsTabPage.cs +++ b/RdcMan/GatewaySettingsTabPage.cs @@ -1,8 +1,10 @@ using System; using System.Windows.Forms; -namespace RdcMan { - public class GatewaySettingsTabPage : CredentialsTabPage { +namespace RdcMan +{ + public class GatewaySettingsTabPage : CredentialsTabPage + { private CheckBox _useGatewayServerCheckBox; private ValueComboBox _gatewayLogonMethodCombo; @@ -14,22 +16,24 @@ public class GatewaySettingsTabPage : CredentialsTabPage { private CheckBox _gatewayCredSharingCheckBox; public GatewaySettingsTabPage(TabbedSettingsDialog dialog, GatewaySettings settings) - : base(dialog, settings) { + : base(dialog, settings) + { } - public void CreateControls(LogonCredentialsDialogOptions options) { - int num = 0; + public void CreateControls(LogonCredentialsDialogOptions options) + { + int tabIndex = 0; int rowIndex = 0; - CreateInheritanceControl(ref rowIndex, ref num); + CreateInheritanceControl(ref rowIndex, ref tabIndex); if (base.InheritanceControl != null) { base.InheritanceControl.EnabledChanged += delegate (bool enabled) { _useGatewayServerCheckBox.Enabled = enabled; UseGatewayServerCheckBox_CheckedChanged(null, null); }; } - _useGatewayServerCheckBox = FormTools.AddCheckBox(this, "ʹ TS ط(&U)", base.Settings.UseGatewayServer, 1, ref rowIndex, ref num); + _useGatewayServerCheckBox = FormTools.AddCheckBox(this, "ʹ TS ط(&U)", base.Settings.UseGatewayServer, 1, ref rowIndex, ref tabIndex); _useGatewayServerCheckBox.CheckedChanged += UseGatewayServerCheckBox_CheckedChanged; - _gatewayHostNameTextBox = FormTools.AddLabeledTextBox(this, "(&S)", base.Settings.HostName, ref rowIndex, ref num); + _gatewayHostNameTextBox = FormTools.AddLabeledTextBox(this, "(&S)", base.Settings.HostName, ref rowIndex, ref tabIndex); _gatewayHostNameTextBox.Validate = delegate { if (_gatewayHostNameTextBox.Enabled) { _gatewayHostNameTextBox.Text = _gatewayHostNameTextBox.Text.Trim(); @@ -39,42 +43,51 @@ public void CreateControls(LogonCredentialsDialogOptions options) { } return null; }; - _gatewayLocalBypassCheckBox = FormTools.AddCheckBox(this, "ƹصַ(&B)", base.Settings.BypassGatewayForLocalAddresses, 1, ref rowIndex, ref num); - _gatewayLogonMethodCombo = FormTools.AddLabeledEnumDropDown(this, "¼ʽ(&L)", base.Settings.LogonMethod, ref rowIndex, ref num, RdpClient.GatewayLogonMethodToString); + _gatewayLocalBypassCheckBox = FormTools.AddCheckBox(this, "ƹصַ(&B)", base.Settings.BypassGatewayForLocalAddresses, 1, ref rowIndex, ref tabIndex); + _gatewayLogonMethodCombo = FormTools.AddLabeledEnumDropDown(this, "¼ʽ(&L)", base.Settings.LogonMethod, ref rowIndex, ref tabIndex, RdpClient.GatewayLogonMethodToString); _gatewayLogonMethodCombo.SelectedValueChanged += GatewayLogonMethodComboBox_SelectedValueChanged; if (RdpClient.SupportsGatewayCredentials) { - _gatewayCredSharingCheckBox = FormTools.AddCheckBox(this, "Զ̼ƾ֤(&C)", base.Settings.CredentialSharing, 1, ref rowIndex, ref num); + _gatewayCredSharingCheckBox = FormTools.AddCheckBox(this, "Զ̼ƾ֤(&C)", base.Settings.CredentialSharing, 1, ref rowIndex, ref tabIndex); _gatewayCredSharingCheckBox.CheckedChanged += GatewayCredSharingCheckBox_CheckedChanged; _credentialsUI = new CredentialsUI(base.InheritanceControl); - _credentialsUI.AddControlsToParent(this, options, ref rowIndex, ref num); + _credentialsUI.AddControlsToParent(this, options, ref rowIndex, ref tabIndex); } } - protected override void UpdateControls() { + protected override void UpdateControls() + { base.UpdateControls(); if (base.InheritanceControl == null) + { UseGatewayServerCheckBox_CheckedChanged(null, null); + } } - private void GatewayCredSharingCheckBox_CheckedChanged(object sender, EventArgs e) { + private void GatewayCredSharingCheckBox_CheckedChanged(object sender, EventArgs e) + { GatewayLogonMethodComboBox_SelectedValueChanged(null, null); } - private void UseGatewayServerCheckBox_CheckedChanged(object sender, EventArgs e) { + private void UseGatewayServerCheckBox_CheckedChanged(object sender, EventArgs e) + { bool enabled = _useGatewayServerCheckBox.Enabled && _useGatewayServerCheckBox.Checked; _gatewayHostNameTextBox.Enabled = enabled; _gatewayLogonMethodCombo.Enabled = enabled; _gatewayLocalBypassCheckBox.Enabled = enabled; if (RdpClient.SupportsGatewayCredentials) + { _gatewayCredSharingCheckBox.Enabled = enabled; - + } GatewayLogonMethodComboBox_SelectedValueChanged(null, null); } - private void GatewayLogonMethodComboBox_SelectedValueChanged(object sender, EventArgs e) { + private void GatewayLogonMethodComboBox_SelectedValueChanged(object sender, EventArgs e) + { bool enable = _gatewayLogonMethodCombo.Enabled && _gatewayLogonMethodCombo.SelectedValue == RdpClient.GatewayLogonMethod.NTLM; if (RdpClient.SupportsGatewayCredentials) + { _credentialsUI.EnableDisableControls(enable); + } } } } diff --git a/RdcMan/GlobalOptionsDialog.cs b/RdcMan/GlobalOptionsDialog.cs index 50e506a..f3f43ce 100644 --- a/RdcMan/GlobalOptionsDialog.cs +++ b/RdcMan/GlobalOptionsDialog.cs @@ -3,14 +3,18 @@ using System.Linq; using System.Windows.Forms; -namespace RdcMan { - public class GlobalOptionsDialog : TabbedSettingsDialog { - private class BandwidthItem { +namespace RdcMan +{ + public class GlobalOptionsDialog : TabbedSettingsDialog + { + private class BandwidthItem + { public string Text; public int Flags; - public BandwidthItem(string text, int flags) { + public BandwidthItem(string text, int flags) + { Text = text; Flags = flags; } @@ -64,7 +68,9 @@ public BandwidthItem(string text, int flags) { private readonly BandwidthItem[] _bandwidthItems; - protected GlobalOptionsDialog(Form parentForm) : base("ѡ", "ȷ", parentForm) { + protected GlobalOptionsDialog(Form parentForm) + : base("ѡ", "ȷ", parentForm) + { _bandwidthItems = new BandwidthItem[5] { new BandwidthItem("Modem (28.8 Kbps)", 15), @@ -76,15 +82,18 @@ public BandwidthItem(string text, int flags) { InitializeComponent(); } - public static GlobalOptionsDialog New() { + public static GlobalOptionsDialog New() + { GlobalOptionsDialog globalOptionsDialog = new GlobalOptionsDialog(Program.TheForm); globalOptionsDialog.InitializeControlsFromPreferences(); return globalOptionsDialog; } - private void InitializeControlsFromPreferences() { + private void InitializeControlsFromPreferences() + { MainForm theForm = Program.TheForm; - foreach (CheckBox control in _virtualGroupsGroup.Controls) { + foreach (CheckBox control in _virtualGroupsGroup.Controls) + { control.Checked = (control.Tag as IBuiltInVirtualGroup).IsInTree; } _treeLocationCombo.SelectedValue = Program.TheForm.ServerTreeLocation; @@ -93,32 +102,41 @@ private void InitializeControlsFromPreferences() { _connectionBarAutoHiddenCheckBox.Checked = Program.Preferences.ConnectionBarState == RdpClient.ConnectionBarState.AutoHide; _connectionBarAutoHiddenCheckBox.Enabled = _connectionBarEnabledCheckBox.Enabled; if (RdpClient.SupportsPanning) + { _panningAccelerationUpDown.Enabled = Program.Preferences.EnablePanning; - + } Size clientSize = theForm.GetClientSize(); - RadioButton radioButton = _casSizeGroup.Controls.OfType().Where(delegate (RadioButton r) { + RadioButton radioButton = _casSizeGroup.Controls.OfType().Where(delegate(RadioButton r) + { Size? size = (Size?)r.Tag; Size size2 = clientSize; return !size.HasValue ? false : !size.HasValue || size.GetValueOrDefault() == size2; }).FirstOrDefault(); if (radioButton != null) + { radioButton.Checked = true; + } else + { _casCustomRadio.Checked = true; - + } _casCustomButton.Text = clientSize.ToFormattedString(); _thumbnailPixelsButton.Text = Program.Preferences.ThumbnailSize.ToFormattedString(); _thumbnailPercentageTextBox.Text = Program.Preferences.ThumbnailPercentage.ToString(); if (Program.Preferences.ThumbnailSizeIsInPixels) + { _thumbnailPixelsRadio.Checked = true; + } else + { _thumbnailPercentageRadio.Checked = true; - + } SetBandwidthCheckBoxes(Program.Preferences.PerformanceFlags); _persistentBitmapCachingCheckBox.Checked = Program.Preferences.PersistentBitmapCaching; } - public void UpdatePreferences() { + public void UpdatePreferences() + { UpdateSettings(); MainForm theForm = Program.TheForm; foreach (CheckBox control in _virtualGroupsGroup.Controls) { @@ -147,7 +165,8 @@ where r.Checked Program.Preferences.ThumbnailPercentage = thumbnailPercentage; } - private void InitializeComponent() { + private void InitializeComponent() + { this.CreateGeneralPage(); this.CreateServerTreePage(); this.CreateClientAreaPage(); @@ -158,7 +177,8 @@ private void InitializeComponent() { this.ScaleAndLayout(); } - private TabPage NewTabPage(string name) { + private TabPage NewTabPage(string name) + { TabPage tabPage = new SettingsTabPage { Location = FormTools.TopLeftLocation(), Size = new Size(FormTools.TabControlWidth-8, FormTools.TabControlHeight-14), @@ -169,20 +189,21 @@ private TabPage NewTabPage(string name) { return tabPage; } - private TabPage CreateFullScreenPage() { + private TabPage CreateFullScreenPage() + { int rowIndex = 0; - int num = 0; + int tabIndex = 0; TabPage tabPage = NewTabPage("ȫ"); - _connectionBarEnabledCheckBox = FormTools.NewCheckBox("ʾȫ", 0, rowIndex++, num++); + _connectionBarEnabledCheckBox = FormTools.NewCheckBox("ʾȫ", 0, rowIndex++, tabIndex++); _connectionBarEnabledCheckBox.CheckedChanged += ConnectionBarEnabledCheckedChanged; - _connectionBarAutoHiddenCheckBox = FormTools.NewCheckBox("Զ", 0, rowIndex++, num++); + _connectionBarAutoHiddenCheckBox = FormTools.NewCheckBox("Զ", 0, rowIndex++, tabIndex++); _connectionBarAutoHiddenCheckBox.Location = new Point(_connectionBarEnabledCheckBox.Left + 24, _connectionBarAutoHiddenCheckBox.Top); - FormTools.AddCheckBox(tabPage, "ȫʼλ", Program.Preferences.Settings.FullScreenWindowIsTopMost, 0, ref rowIndex, ref num); + FormTools.AddCheckBox(tabPage, "ȫʼλ", Program.Preferences.Settings.FullScreenWindowIsTopMost, 0, ref rowIndex, ref tabIndex); if (RdpClient.SupportsMonitorSpanning) { - FormTools.AddCheckBox(tabPage, "Ҫʱʹǫ̈ʾ", Program.Preferences.Settings.UseMultipleMonitors, 0, ref rowIndex, ref num); + FormTools.AddCheckBox(tabPage, "Ҫʱʹǫ̈ʾ", Program.Preferences.Settings.UseMultipleMonitors, 0, ref rowIndex, ref tabIndex); } if (RdpClient.SupportsPanning) { - _enablePanningCheckBox = FormTools.NewCheckBox("ʹûǹ", 0, rowIndex++, num++); + _enablePanningCheckBox = FormTools.NewCheckBox("ʹûǹ", 0, rowIndex++, tabIndex++); _enablePanningCheckBox.Setting = Program.Preferences.Settings.EnablePanning; _enablePanningCheckBox.CheckedChanged += EnablePanningCheckedChanged; Label label = FormTools.NewLabel("ٶ", 0, rowIndex); @@ -193,7 +214,7 @@ private TabPage CreateFullScreenPage() { Minimum = 1m, Maximum = 9m, Size = new Size(40, FormTools.ControlHeight), - TabIndex = num++, + TabIndex = tabIndex++, Setting = Program.Preferences.Settings.PanningAcceleration }; tabPage.Controls.Add(_enablePanningCheckBox, label, _panningAccelerationUpDown); @@ -202,60 +223,63 @@ private TabPage CreateFullScreenPage() { return tabPage; } - private TabPage CreateExperiencePage() { + private TabPage CreateExperiencePage() + { TabPage tabPage = NewTabPage(""); int rowIndex = 0; - int num = 0; - _bandwidthComboBox = FormTools.AddLabeledValueDropDown(tabPage, "ٶ(&S)", ref rowIndex, ref num, (BandwidthItem v) => v.Text, _bandwidthItems); + int tabIndex = 0; + _bandwidthComboBox = FormTools.AddLabeledValueDropDown(tabPage, "ٶ(&S)", ref rowIndex, ref tabIndex, (BandwidthItem v) => v.Text, _bandwidthItems); _bandwidthComboBox.SelectedIndexChanged += BandwidthCombo_ControlChanged; Label label = FormTools.NewLabel("£", 0, rowIndex); - _desktopBackgroundCheckBox = FormTools.NewCheckBox("汳", 1, rowIndex++, num++); + _desktopBackgroundCheckBox = FormTools.NewCheckBox("汳", 1, rowIndex++, tabIndex++); _desktopBackgroundCheckBox.CheckedChanged += PerfCheckBox_CheckedChanged; - _fontSmoothingCheckBox = FormTools.NewCheckBox("ƽ", 1, rowIndex++, num++); + _fontSmoothingCheckBox = FormTools.NewCheckBox("ƽ", 1, rowIndex++, tabIndex++); _fontSmoothingCheckBox.CheckedChanged += PerfCheckBox_CheckedChanged; - _desktopCompositionCheckBox = FormTools.NewCheckBox("ƴ", 1, rowIndex++, num++); + _desktopCompositionCheckBox = FormTools.NewCheckBox("ƴ", 1, rowIndex++, tabIndex++); _desktopCompositionCheckBox.CheckedChanged += PerfCheckBox_CheckedChanged; - _windowDragCheckBox = FormTools.NewCheckBox("϶ʱʾ", 1, rowIndex++, num++); + _windowDragCheckBox = FormTools.NewCheckBox("϶ʱʾ", 1, rowIndex++, tabIndex++); _windowDragCheckBox.CheckedChanged += PerfCheckBox_CheckedChanged; - _menuAnimationCheckBox = FormTools.NewCheckBox("˵ʹڶ", 1, rowIndex++, num++); + _menuAnimationCheckBox = FormTools.NewCheckBox("˵ʹڶ", 1, rowIndex++, tabIndex++); _menuAnimationCheckBox.CheckedChanged += PerfCheckBox_CheckedChanged; - _themesCheckBox = FormTools.NewCheckBox("", 1, rowIndex++, num++); + _themesCheckBox = FormTools.NewCheckBox("", 1, rowIndex++, tabIndex++); _themesCheckBox.CheckedChanged += PerfCheckBox_CheckedChanged; rowIndex++; - _persistentBitmapCachingCheckBox = FormTools.NewCheckBox("־λͼ", 1, rowIndex++, num++); + _persistentBitmapCachingCheckBox = FormTools.NewCheckBox("־λͼ", 1, rowIndex++, tabIndex++); tabPage.Controls.Add(label, _desktopBackgroundCheckBox, _fontSmoothingCheckBox, _desktopCompositionCheckBox, _windowDragCheckBox, _menuAnimationCheckBox, _themesCheckBox, _persistentBitmapCachingCheckBox); return tabPage; } - private TabPage CreateHotKeysPage() { + private TabPage CreateHotKeysPage() + { GlobalSettings settings = Program.Preferences.Settings; TabPage tabPage = NewTabPage("ȼ"); GroupBox groupBox = new GroupBox { Text = "ALT ȼ Windows ϼδضʱЧ" }; int rowIndex = 0; - int num = 0; - AddHotKeyBox(groupBox, "ALT+TAB", "ALT+", settings.HotKeyAltTab, ref rowIndex, ref num); - AddHotKeyBox(groupBox, "ALT+SHIFT+TAB", "ALT+", settings.HotKeyAltShiftTab, ref rowIndex, ref num); - AddHotKeyBox(groupBox, "ALT+ESC", "ALT+", settings.HotKeyAltEsc, ref rowIndex, ref num); - AddHotKeyBox(groupBox, "ALT+SPACE", "ALT+", settings.HotKeyAltSpace, ref rowIndex, ref num); - AddHotKeyBox(groupBox, "CTRL+ESC", "ALT+", settings.HotKeyCtrlEsc, ref rowIndex, ref num); + int tabIndex = 0; + AddHotKeyBox(groupBox, "ALT+TAB", "ALT+", settings.HotKeyAltTab, ref rowIndex, ref tabIndex); + AddHotKeyBox(groupBox, "ALT+SHIFT+TAB", "ALT+", settings.HotKeyAltShiftTab, ref rowIndex, ref tabIndex); + AddHotKeyBox(groupBox, "ALT+ESC", "ALT+", settings.HotKeyAltEsc, ref rowIndex, ref tabIndex); + AddHotKeyBox(groupBox, "ALT+SPACE", "ALT+", settings.HotKeyAltSpace, ref rowIndex, ref tabIndex); + AddHotKeyBox(groupBox, "CTRL+ESC", "ALT+", settings.HotKeyCtrlEsc, ref rowIndex, ref tabIndex); groupBox.SizeAndLocate(null); GroupBox groupBox2 = new GroupBox { Text = "CTRL+ALT ȼʼЧ" }; rowIndex = 0; - num = 0; - AddHotKeyBox(groupBox2, "CTRL+ALT+DEL", "CTRL+ALT+", settings.HotKeyCtrlAltDel, ref rowIndex, ref num); - AddHotKeyBox(groupBox2, "ȫ", "CTRL+ALT+", settings.HotKeyFullScreen, ref rowIndex, ref num); - AddHotKeyBox(groupBox2, "һỰ", "CTRL+ALT+", settings.HotKeyFocusReleaseLeft, ref rowIndex, ref num); - AddHotKeyBox(groupBox2, "ѡỰ", "CTRL+ALT+", settings.HotKeyFocusReleaseRight, ref rowIndex, ref num); + tabIndex = 0; + AddHotKeyBox(groupBox2, "CTRL+ALT+DEL", "CTRL+ALT+", settings.HotKeyCtrlAltDel, ref rowIndex, ref tabIndex); + AddHotKeyBox(groupBox2, "ȫ", "CTRL+ALT+", settings.HotKeyFullScreen, ref rowIndex, ref tabIndex); + AddHotKeyBox(groupBox2, "һỰ", "CTRL+ALT+", settings.HotKeyFocusReleaseLeft, ref rowIndex, ref tabIndex); + AddHotKeyBox(groupBox2, "ѡỰ", "CTRL+ALT+", settings.HotKeyFocusReleaseRight, ref rowIndex, ref tabIndex); groupBox2.SizeAndLocate(groupBox); tabPage.Controls.Add(groupBox, groupBox2); return tabPage; } - private void AddHotKeyBox(Control parent, string label, string prefix, EnumSetting setting, ref int rowIndex, ref int tabIndex) { + private void AddHotKeyBox(Control parent, string label, string prefix, EnumSetting setting, ref int rowIndex, ref int tabIndex) + { parent.Controls.Add(FormTools.NewLabel(label, 0, rowIndex)); HotKeyBox value = new HotKeyBox { Prefix = prefix, @@ -328,21 +352,22 @@ private TabPage CreateClientAreaPage() { return tabPage; } - private TabPage CreateServerTreePage() { + private TabPage CreateServerTreePage() + { int rowIndex = 0; - int num = 0; + int tabIndex = 0; TabPage tabPage = NewTabPage(""); GroupBox groupBox = new GroupBox { Text = "" }; - FormTools.AddCheckBox(groupBox, "ѡ񽫽תƵԶ̿ͻ", Program.Preferences.Settings.FocusOnClick, 0, ref rowIndex, ref num); - FormTools.AddCheckBox(groupBox, "ؼڷǻ״̬ʱʹڵ䰵", Program.Preferences.Settings.DimNodesWhenInactive, 0, ref rowIndex, ref num); - _treeLocationCombo = FormTools.AddLabeledValueDropDown(groupBox, "λã", ref rowIndex, ref num, (DockStyle v) => v.ToString(), new DockStyle[2] + FormTools.AddCheckBox(groupBox, "ѡ񽫽תƵԶ̿ͻ", Program.Preferences.Settings.FocusOnClick, 0, ref rowIndex, ref tabIndex); + FormTools.AddCheckBox(groupBox, "ؼڷǻ״̬ʱʹڵ䰵", Program.Preferences.Settings.DimNodesWhenInactive, 0, ref rowIndex, ref tabIndex); + _treeLocationCombo = FormTools.AddLabeledValueDropDown(groupBox, "λã", ref rowIndex, ref tabIndex, (DockStyle v) => v.ToString(), new DockStyle[2] { DockStyle.Left, DockStyle.Right }); - _treeVisibilityCombo = FormTools.AddLabeledValueDropDown(groupBox, "ɼԣ", ref rowIndex, ref num, (ControlVisibility v) => v.ToString(), new ControlVisibility[3] + _treeVisibilityCombo = FormTools.AddLabeledValueDropDown(groupBox, "ɼԣ", ref rowIndex, ref tabIndex, (ControlVisibility v) => v.ToString(), new ControlVisibility[3] { ControlVisibility.Dock, ControlVisibility.AutoHide, @@ -357,7 +382,7 @@ private TabPage CreateServerTreePage() { Size = new Size(40, 24), Setting = Program.Preferences.Settings.ServerTreeAutoHidePopUpDelay, TabStop = true, - TabIndex = num++ + TabIndex = tabIndex++ }; _treeVisibilityCombo.SelectedIndexChanged += delegate { serverTreeAutoHidePopUpDelay.Enabled = _treeVisibilityCombo.SelectedValue == ControlVisibility.AutoHide; @@ -384,31 +409,32 @@ private TabPage CreateServerTreePage() { FormTools.LayoutGroupBox(_virtualGroupsGroup, 2, groupBox); _virtualGroupsGroup.Height -= 6; rowIndex = 0; - num = 0; + tabIndex = 0; GroupBox groupBox2 = new GroupBox { Text = "" }; - FormTools.AddLabeledValueDropDown(groupBox2, "˳", Program.Preferences.Settings.GroupSortOrder, ref rowIndex, ref num, Helpers.SortOrderToString, new SortOrder[2] { + FormTools.AddLabeledValueDropDown(groupBox2, "˳", Program.Preferences.Settings.GroupSortOrder, ref rowIndex, ref tabIndex, Helpers.SortOrderToString, new SortOrder[2] { SortOrder.ByName, SortOrder.None }); - FormTools.AddLabeledEnumDropDown(groupBox2, "˳", Program.Preferences.Settings.ServerSortOrder, ref rowIndex, ref num, Helpers.SortOrderToString); + FormTools.AddLabeledEnumDropDown(groupBox2, "˳", Program.Preferences.Settings.ServerSortOrder, ref rowIndex, ref tabIndex, Helpers.SortOrderToString); FormTools.LayoutGroupBox(groupBox2, 2, _virtualGroupsGroup); tabPage.Controls.Add(groupBox, _virtualGroupsGroup, groupBox2); return tabPage; } - private TabPage CreateGeneralPage() { + private TabPage CreateGeneralPage() + { int rowIndex = 0; - int num = 0; + int tabIndex = 0; TabPage tabPage = NewTabPage(""); - FormTools.AddCheckBox(tabPage, "˵ֱ ALT", Program.Preferences.Settings.HideMainMenu, 0, ref rowIndex, ref num); - RdcCheckBox autoSaveCheckBox = FormTools.AddCheckBox(tabPage, "Զ", Program.Preferences.Settings.AutoSaveFiles, 0, ref rowIndex, ref num); + FormTools.AddCheckBox(tabPage, "˵ֱ ALT", Program.Preferences.Settings.HideMainMenu, 0, ref rowIndex, ref tabIndex); + RdcCheckBox autoSaveCheckBox = FormTools.AddCheckBox(tabPage, "Զ", Program.Preferences.Settings.AutoSaveFiles, 0, ref rowIndex, ref tabIndex); autoSaveCheckBox.Size = new Size(120, 24); NumericTextBox autoSaveInterval = new NumericTextBox(0, 60, "ԶΪ 0 60 ӣ") { Location = new Point(autoSaveCheckBox.Right + 1, autoSaveCheckBox.Top + 2), Size = new Size(FormTools.ControlHeight, 24), - TabIndex = num++, + TabIndex = tabIndex++, TabStop = true, Enabled = false }; @@ -421,10 +447,10 @@ private TabPage CreateGeneralPage() { Size = new Size(60, 24), Text = "" }; - RdcCheckBox rdcCheckBox = FormTools.AddCheckBox(tabPage, "ʱʾӵķ", Program.Preferences.Settings.ReconnectOnStartup, 0, ref rowIndex, ref num); + RdcCheckBox rdcCheckBox = FormTools.AddCheckBox(tabPage, "ʱʾӵķ", Program.Preferences.Settings.ReconnectOnStartup, 0, ref rowIndex, ref tabIndex); Button button = new Button { Location = new Point(8, rdcCheckBox.Bottom + 8), - TabIndex = num++, + TabIndex = tabIndex++, Text = "Ĭ...", Width = 140 }; @@ -435,42 +461,51 @@ private TabPage CreateGeneralPage() { return tabPage; } - private void EnablePanningCheckedChanged(object sender, EventArgs e) { + private void EnablePanningCheckedChanged(object sender, EventArgs e) + { _panningAccelerationUpDown.Enabled = _enablePanningCheckBox.Checked; } - private void ConnectionBarEnabledCheckedChanged(object sender, EventArgs e) { + private void ConnectionBarEnabledCheckedChanged(object sender, EventArgs e) + { _connectionBarAutoHiddenCheckBox.Enabled = _connectionBarEnabledCheckBox.Checked; } - private void CustomSizeClick(object sender, EventArgs e) { + private void CustomSizeClick(object sender, EventArgs e) + { Button button = sender as Button; Size size = SizeHelper.Parse(button.Text); using CustomSizeDialog customSizeDialog = new CustomSizeDialog(size); - if (customSizeDialog.ShowDialog() == DialogResult.OK) { + if (customSizeDialog.ShowDialog() == DialogResult.OK) + { button.Text = customSizeDialog.WidthText + SizeHelper.Separator + customSizeDialog.HeightText; _thumbnailPixelsRadio.Checked = true; } } - private void ThumbnailPercentageRadioCheckedChanged(object sender, EventArgs e) { + private void ThumbnailPercentageRadioCheckedChanged(object sender, EventArgs e) + { _thumbnailPercentageTextBox.Enabled = (sender as RadioButton).Checked; _thumbnailPixelsButton.Enabled = !_thumbnailPercentageTextBox.Enabled; } - private void BandwidthCombo_ControlChanged(object sender, EventArgs e) { + private void BandwidthCombo_ControlChanged(object sender, EventArgs e) + { BandwidthSettingsChanged(); } - private void BandwidthSettingsChanged() { - if (!_inHandler) { + private void BandwidthSettingsChanged() + { + if (!_inHandler) + { _inHandler = true; SetBandwidthCheckBoxes(_bandwidthComboBox.SelectedValue.Flags); _inHandler = false; } } - private void SetBandwidthCheckBoxes(int flags) { + private void SetBandwidthCheckBoxes(int flags) + { _desktopBackgroundCheckBox.Checked = (flags & 1) == 0; _fontSmoothingCheckBox.Checked = (flags & 0x80) != 0; _desktopCompositionCheckBox.Checked = (flags & 0x100) != 0; @@ -479,8 +514,10 @@ private void SetBandwidthCheckBoxes(int flags) { _themesCheckBox.Checked = (flags & 8) == 0; } - private void PerfCheckBox_CheckedChanged(object sender, EventArgs e) { - if (!_inHandler) { + private void PerfCheckBox_CheckedChanged(object sender, EventArgs e) + { + if (!_inHandler) + { _inHandler = true; int flags = ComputeFlagsFromCheckBoxes(); BandwidthItem selectedValue = _bandwidthItems.Where((BandwidthItem i) => i.Flags == flags).FirstOrDefault() ?? _bandwidthItems.First((BandwidthItem i) => i.Text.Equals("Զ")); @@ -489,7 +526,8 @@ private void PerfCheckBox_CheckedChanged(object sender, EventArgs e) { } } - private int ComputeFlagsFromCheckBoxes() { + private int ComputeFlagsFromCheckBoxes() + { int num = 0; if (!_desktopBackgroundCheckBox.Checked) num |= 1; diff --git a/RdcMan/GlobalSettings.cs b/RdcMan/GlobalSettings.cs index 337aa1d..5211899 100644 --- a/RdcMan/GlobalSettings.cs +++ b/RdcMan/GlobalSettings.cs @@ -4,8 +4,10 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { - public sealed class GlobalSettings : SettingsGroup { +namespace RdcMan +{ + public sealed class GlobalSettings : SettingsGroup + { //public const string TabName = "Preferences"; private static Dictionary _settingProperties; @@ -156,7 +158,8 @@ public sealed class GlobalSettings : SettingsGroup { [Setting("WindowSize")] public SizeSetting WindowSize { get; private set; } - static GlobalSettings() { + static GlobalSettings() + { typeof(GlobalSettings).GetSettingProperties(out _settingProperties); _settingProperties["ThumbnailSize"].Attribute.DefaultValue = new Size(160, 120); _settingProperties["WindowPosition"].Attribute.DefaultValue = new Point(200, 200); @@ -164,13 +167,17 @@ static GlobalSettings() { } public GlobalSettings() - : base("ѡ", "Settings") { + : base("ѡ", "Settings") + { base.InheritSettingsType.Mode = InheritanceMode.Disabled; } - public void TransferPreferences(Preferences prefs) { - foreach (string key in _settingProperties.Keys) { - try { + public void TransferPreferences(Preferences prefs) + { + foreach (string key in _settingProperties.Keys) + { + try + { object transferValue = prefs.GetTransferValue(key); SetValue(key, transferValue); } @@ -178,26 +185,31 @@ public void TransferPreferences(Preferences prefs) { } } - public object GetValue(string name) { + public object GetValue(string name) + { object value = _settingProperties[name].Property.GetValue(this, null); return value.GetType().GetProperty("Value").GetValue(value, null); } - public void SetValue(string name, object value) { + public void SetValue(string name, object value) + { object value2 = _settingProperties[name].Property.GetValue(this, null); value2.GetType().GetProperty("Value").SetValue(value2, value, null); } - public override TabPage CreateTabPage(TabbedSettingsDialog dialog) { + public override TabPage CreateTabPage(TabbedSettingsDialog dialog) + { throw new NotImplementedException(); } - protected override void WriteSettings(XmlTextWriter tw, RdcTreeNode node) { + protected override void WriteSettings(XmlTextWriter tw, RdcTreeNode node) + { tw.WriteAttributeString("programVersion", Program.TheForm.VersionText); base.WriteSettings(tw, node); } - protected override void Copy(RdcTreeNode node) { + protected override void Copy(RdcTreeNode node) + { throw new InvalidOperationException("GlobalSettings should never be copied"); } } diff --git a/RdcMan/Group.cs b/RdcMan/Group.cs index b0bc457..6e9ea36 100644 --- a/RdcMan/Group.cs +++ b/RdcMan/Group.cs @@ -2,58 +2,71 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { - public class Group : GroupBase { +namespace RdcMan +{ + public class Group : GroupBase + { //public const string XmlNodeName = "group"; - protected Group() { } + protected Group() + { + } - internal static Group CreateForAddDialog() { + internal static Group CreateForAddDialog() + { return new Group(); } - public static Group Create(string name, GroupBase parent) { + public static Group Create(string name, GroupBase parent) + { Group group = new Group(); group.Properties.GroupName.Value = name; group.FinishConstruction(parent); return group; } - internal static Group Create(GroupPropertiesDialog dlg) { + internal static Group Create(GroupPropertiesDialog dlg) + { Group group = dlg.AssociatedNode as Group; group.UpdateSettings(dlg); group.FinishConstruction(dlg.PropertiesPage.ParentGroup); return group; } - internal static Group Create(XmlNode xmlNode, GroupBase parent, ICollection errors) { + internal static Group Create(XmlNode xmlNode, GroupBase parent, ICollection errors) + { Group group = new Group(); group.ReadXml(xmlNode, errors); group.FinishConstruction(parent); return group; } - protected override void InitSettings() { + protected override void InitSettings() + { ((RdcTreeNode)this).Properties = new GroupSettings(); base.InitSettings(); } - internal override void WriteXml(XmlTextWriter tw) { + internal override void WriteXml(XmlTextWriter tw) + { tw.WriteStartElement("group"); base.WriteXml(tw); tw.WriteEndElement(); } - public override void DoPropertiesDialog(Form parentForm, string activeTabName) { + public override void DoPropertiesDialog(Form parentForm, string activeTabName) + { using GroupPropertiesDialog groupPropertiesDialog = GroupPropertiesDialog.NewPropertiesDialog(this, parentForm); groupPropertiesDialog.SetActiveTab(activeTabName); - if (groupPropertiesDialog.ShowDialog() == DialogResult.OK) { + if (groupPropertiesDialog.ShowDialog() == DialogResult.OK) + { UpdateSettings(groupPropertiesDialog); ServerTree.Instance.OnNodeChanged(this, ChangeType.PropertyChanged); } } - private void FinishConstruction(GroupBase parent) { + private void FinishConstruction(GroupBase parent) + { base.Text = base.Properties.GroupName.Value; ServerTree.Instance.AddNode(this, parent); ChangeImageIndex(ImageConstants.Group); diff --git a/RdcMan/GroupBase.cs b/RdcMan/GroupBase.cs index 681b8a1..bf0ceff 100644 --- a/RdcMan/GroupBase.cs +++ b/RdcMan/GroupBase.cs @@ -4,8 +4,10 @@ using System.Xml; using RdcMan.Configuration; -namespace RdcMan { - public abstract class GroupBase : RdcTreeNode { +namespace RdcMan +{ + public abstract class GroupBase : RdcTreeNode + { //internal const string XmlGroupNameTag = "name"; //internal const string XmlExpandedTag = "expanded"; @@ -35,30 +37,46 @@ internal bool HasServers { get => base.Nodes.Count == 0 ? false : base.Nodes[0] is ServerBase; } - internal int NumberOfServers { - get { - if (_numberOfServers == -1) { + internal int NumberOfServers + { + get + { + if (_numberOfServers == -1) + { _numberOfServers = 0; - foreach (TreeNode node in base.Nodes) { + foreach (TreeNode node in base.Nodes) + { if (node is GroupBase groupBase) + { _numberOfServers += groupBase.NumberOfServers; + } else + { _numberOfServers++; + } } } return _numberOfServers; } } - internal int NumberOfConnectedServers { - get { - if (_numberOfConnectedServers == -1) { + internal int NumberOfConnectedServers + { + get + { + if (_numberOfConnectedServers == -1) + { _numberOfConnectedServers = 0; - foreach (TreeNode node in base.Nodes) { + foreach (TreeNode node in base.Nodes) + { if (node is GroupBase groupBase) + { _numberOfConnectedServers += groupBase.NumberOfConnectedServers; + } else if ((node as ServerBase).IsConnected) + { _numberOfConnectedServers++; + } } } return _numberOfConnectedServers; @@ -71,56 +89,70 @@ public bool HasGroups { get => base.Nodes.Count > 0 ? base.Nodes[0] is GroupBase : false; } - static GroupBase() { - NodeActions = new Dictionary { + static GroupBase() + { + NodeActions = new Dictionary + { { "properties", - delegate(XmlNode childNode, RdcTreeNode parent, ICollection errors) { + delegate(XmlNode childNode, RdcTreeNode parent, ICollection errors) + { if (SchemaVersion <= 2) + { (parent as GroupBase).ReadXml(PropertyActions, childNode, errors); + } else + { (parent as GroupBase).ReadXmlSettingsGroup(childNode, errors); + } } }, { "server", - delegate(XmlNode childNode, RdcTreeNode parent, ICollection errors) { + delegate(XmlNode childNode, RdcTreeNode parent, ICollection errors) + { Server server = Server.Create(childNode, parent as GroupBase, errors); LongRunningActionForm.Instance.UpdateStatus(server.Properties.DisplayName.Value); } }, { "group", - delegate(XmlNode childNode, RdcTreeNode parent, ICollection errors) { + delegate(XmlNode childNode, RdcTreeNode parent, ICollection errors) + { GroupBase groupBase2 = Group.Create(childNode, parent as GroupBase, errors); LongRunningActionForm.Instance.UpdateStatus(groupBase2.Properties.GroupName.Value); } }, { "smartGroup", - delegate(XmlNode childNode, RdcTreeNode parent, ICollection errors) { + delegate(XmlNode childNode, RdcTreeNode parent, ICollection errors) + { GroupBase groupBase = SmartGroup.Create(childNode, parent as GroupBase, errors); LongRunningActionForm.Instance.UpdateStatus(groupBase.Properties.GroupName.Value); } } }; - PropertyActions = new Dictionary { + PropertyActions = new Dictionary + { { "name", - delegate(XmlNode childNode, RdcTreeNode node, ICollection errors) { + delegate(XmlNode childNode, RdcTreeNode node, ICollection errors) + { (node as GroupBase).Properties.GroupName.Value = childNode.InnerText; } }, { "expanded", - delegate(XmlNode childNode, RdcTreeNode node, ICollection errors) { + delegate(XmlNode childNode, RdcTreeNode node, ICollection errors) + { bool.TryParse(childNode.InnerText, out var result); (node as GroupBase).Properties.Expanded.Value = result; } }, { "comment", - delegate(XmlNode childNode, RdcTreeNode node, ICollection errors) { + delegate(XmlNode childNode, RdcTreeNode node, ICollection errors) + { (node as GroupBase).Properties.Comment.Value = childNode.InnerText; } } @@ -128,9 +160,11 @@ static GroupBase() { Server.ConnectionStateChanged += Server_ConnectionStateChanged; } - private static void Server_ConnectionStateChanged(ConnectionStateChangedEventArgs args) { + private static void Server_ConnectionStateChanged(ConnectionStateChangedEventArgs args) + { (args.Server.Parent as GroupBase).OnConnectionStateChange(args.Server); - args.Server.VisitServerRefs(delegate (ServerRef r) { + args.Server.VisitServerRefs(delegate(ServerRef r) + { (r.Parent as GroupBase).OnConnectionStateChange(r); }); } @@ -139,37 +173,45 @@ public virtual bool CanRemoveChildren() { return base.Nodes.Count > 0 ? AllowEdit(popUI: false) : false; } - protected override void InitSettings() { + protected override void InitSettings() + { base.DisplaySettings = new GroupDisplaySettings(); base.InitSettings(); } - internal override void UpdateSettings(NodePropertiesDialog dlg) { + internal override void UpdateSettings(NodePropertiesDialog dlg) + { base.UpdateSettings(dlg); base.Text = Properties.GroupName.Value; } - public override void InvalidateNode() { + public override void InvalidateNode() + { _numberOfServers = -1; ResetConnectionStatistics(this); base.InvalidateNode(); } - internal void ResetConnectionStatistics() { - this.VisitNodeAndParents(delegate (RdcTreeNode group) { + internal void ResetConnectionStatistics() + { + this.VisitNodeAndParents(delegate(RdcTreeNode group) + { ResetConnectionStatistics((GroupBase)group); }); } - private static void ResetConnectionStatistics(GroupBase group) { + private static void ResetConnectionStatistics(GroupBase group) + { group._numberOfConnectedServers = -1; } - public virtual bool CanAddServers() { + public virtual bool CanAddServers() + { return CanDropServers(); } - public virtual bool CanAddGroups() { + public virtual bool CanAddGroups() + { return CanDropGroups(); } @@ -181,28 +223,37 @@ public virtual bool CanDropGroups() { return !HasServers ? AllowEdit(popUI: false) : false; } - public virtual DragDropEffects DropBehavior() { + public virtual DragDropEffects DropBehavior() + { return DragDropEffects.Move; } - internal override void Show() { + internal override void Show() + { Program.TheForm.ShowGroup(this); } - internal override void Hide() { + internal override void Hide() + { Program.TheForm.HideGroup(this); } - internal override void WriteXml(XmlTextWriter tw) { + internal override void WriteXml(XmlTextWriter tw) + { Properties.Expanded.Value = base.IsExpanded; WriteXmlSettingsGroups(tw); foreach (RdcTreeNode node in base.Nodes) + { node.WriteXml(tw); + } } - public void RemoveChildren() { - ServerTree.Instance.Operation(OperationBehavior.SuspendSelect | OperationBehavior.SuspendSort | OperationBehavior.SuspendUpdate | OperationBehavior.SuspendGroupChanged, delegate { - base.Nodes.ForEach(delegate (TreeNode node) { + public void RemoveChildren() + { + ServerTree.Instance.Operation(OperationBehavior.SuspendSelect | OperationBehavior.SuspendSort | OperationBehavior.SuspendUpdate | OperationBehavior.SuspendGroupChanged, delegate + { + base.Nodes.ForEach(delegate(TreeNode node) + { (node as RdcTreeNode).OnRemoving(); }); base.Nodes.Clear(); @@ -210,113 +261,153 @@ public void RemoveChildren() { ServerTree.Instance.OnGroupChanged(this, ChangeType.TreeChanged); } - public override void OnRemoving() { + public override void OnRemoving() + { Hide(); RemoveChildren(); } - public override void Connect() { + public override void Connect() + { ConnectAs(null, null); } - public override void ConnectAs(LogonCredentials logonSettings, ConnectionSettings connectionSettings) { + public override void ConnectAs(LogonCredentials logonSettings, ConnectionSettings connectionSettings) + { List allChildren = this.GetAllChildren((ServerBase s) => !s.IsConnected); int count = allChildren.Count; - if (count >= Current.RdcManSection.WarningThresholds.Connect) { - DialogResult dialogResult = FormTools.YesNoDialog(base.Text + " " + count + " Ͽӵķ ȷ"); + if (count >= Current.RdcManSection.WarningThresholds.Connect) + { + DialogResult dialogResult = FormTools.YesNoDialog(base.Text + " " + count + " δӵķ ȷ"); if (dialogResult != DialogResult.Yes) + { return; + } } NodeHelper.ThrottledConnectAs(allChildren, logonSettings, connectionSettings); } - public override void Reconnect() { - this.GetAllChildren((ServerBase s) => s.IsConnected).ForEach(delegate (ServerBase server) { + public override void Reconnect() + { + this.GetAllChildren((ServerBase s) => s.IsConnected).ForEach(delegate(ServerBase server) + { server.Reconnect(); }); } - public override void Disconnect() { + public override void Disconnect() + { NodeHelper.ThrottledDisconnect(this.GetAllChildren((ServerBase s) => s.IsConnected)); } - public override void LogOff() { - foreach (ServerBase allChild in this.GetAllChildren((ServerBase s) => s.IsConnected)) { + public override void LogOff() + { + foreach (ServerBase allChild in this.GetAllChildren((ServerBase s) => s.IsConnected)) + { allChild.LogOff(); Thread.Sleep(25); } } - private void OnConnectionStateChange(ServerBase server) { + private void OnConnectionStateChange(ServerBase server) + { InheritSettings(); - if (!server.IsConnected) { + if (!server.IsConnected) + { ReconnectServerRef reconnectServerRef = server.ServerNode.FindServerRef(); if (reconnectServerRef != null && reconnectServerRef.NeedToReconnect) + { return; + } } bool flag = false; if (Program.Preferences.ServerSortOrder == SortOrder.ByStatus) + { flag |= ServerTree.Instance.SortNode(server); + } if (flag | !(server.ServerNode.Parent as GroupBase).DisplaySettings.ShowDisconnectedThumbnails.Value) + { ServerTree.Instance.OnGroupChanged(this, ChangeType.InvalidateUI); + } } - public override bool CanDropOnTarget(RdcTreeNode targetNode) { + public override bool CanDropOnTarget(RdcTreeNode targetNode) + { if (targetNode == this) + { return true; - + } GroupBase groupBase = targetNode as GroupBase; if (groupBase == null) + { return false; - + } if (!groupBase.CanDropGroups()) + { return false; - + } if (!AllowEdit(popUI: false)) + { return false; - - while (groupBase != null) { + } + while (groupBase != null) + { if (groupBase.Parent == this) + { return false; - + } groupBase = groupBase.Parent as GroupBase; } return true; } - public override bool ConfirmRemove(bool askUser) { + public override bool ConfirmRemove(bool askUser) + { if (!CanRemove(popUI: true)) + { return false; - + } AnyOrAllConnected(out var anyConnected, out var _); - if (anyConnected) { - FormTools.InformationDialog(base.Text + " лỰɾ֮ǰϿǡ"); + if (anyConnected) + { + FormTools.InformationDialog(base.Text + " лỰɾ֮ǰҪȶϿ"); return false; } - if (askUser && base.Nodes.Count > 0) { + if (askUser && base.Nodes.Count > 0) + { DialogResult dialogResult = FormTools.YesNoDialog("ɾ " + base.Text + " "); if (dialogResult != DialogResult.Yes) + { return false; + } } return true; } - public void AnyOrAllConnected(out bool anyConnected, out bool allConnected) { + public void AnyOrAllConnected(out bool anyConnected, out bool allConnected) + { bool any = false; bool all = true; - base.Nodes.VisitNodes(delegate (RdcTreeNode node) { - if (node is ServerBase serverBase) { + base.Nodes.VisitNodes(delegate(RdcTreeNode node) + { + if (node is ServerBase serverBase) + { if (serverBase.IsConnected) + { any = true; + } else + { all = false; + } } }); anyConnected = any; allConnected = all; } - internal virtual void ReadXml(XmlNode xmlNode, ICollection errors) { + internal virtual void ReadXml(XmlNode xmlNode, ICollection errors) + { ReadXml(NodeActions, xmlNode, errors); } } diff --git a/RdcMan/GroupBasePropertiesDialog.cs b/RdcMan/GroupBasePropertiesDialog.cs index 3dc3e3f..2d2bf65 100644 --- a/RdcMan/GroupBasePropertiesDialog.cs +++ b/RdcMan/GroupBasePropertiesDialog.cs @@ -5,8 +5,10 @@ using System.Text; using System.Windows.Forms; -namespace RdcMan { - internal abstract class GroupBasePropertiesDialog : NodePropertiesDialog { +namespace RdcMan +{ + internal abstract class GroupBasePropertiesDialog : NodePropertiesDialog + { protected ListBox _credentialsListBox; private CredentialsStore _credentialsStore; @@ -14,31 +16,38 @@ internal abstract class GroupBasePropertiesDialog : NodePropertiesDialog { private int _credentialsStoreChangeId; protected GroupBasePropertiesDialog(GroupBase group, string dialogTitle, string acceptButtonText, Form parentForm) - : base(group, dialogTitle, acceptButtonText, parentForm) { } + : base(group, dialogTitle, acceptButtonText, parentForm) + { + } - protected int CreateProfileManagementTabPage() { + protected int CreateProfileManagementTabPage() + { int result = 0; TabPage tabPage = FormTools.NewTabPage("¼ƾ֤"); Label label = FormTools.NewLabel("¼ƾ֤", 0, result++); - _credentialsListBox = new ListBox { + _credentialsListBox = new ListBox + { Location = FormTools.NewLocation(0, result++), Size = new Size(340, 200) }; _credentialsListBox.KeyDown += CredentialsListBox_KeyDown; _credentialsListBox.DoubleClick += EditButton_Click; _credentialsListBox.VisibleChanged += CredentialsListBox_VisibleChanged; - Button button = new Button { - Text = "(&A)", + Button button = new Button + { + Text = "(&A)", Location = new Point(_credentialsListBox.Right + FormTools.ControlHeight, _credentialsListBox.Top) }; button.Click += AddButton_Click; - Button button2 = new Button { - Text = "(&E)༭", + Button button2 = new Button + { + Text = "༭(&E)", Location = new Point(_credentialsListBox.Right + FormTools.ControlHeight, button.Bottom + FormTools.VerticalSpace) }; button2.Click += EditButton_Click; - Button button3 = new Button { - Text = "(&D)ɾ", + Button button3 = new Button + { + Text = "ɾ(&D)", Location = new Point(_credentialsListBox.Right + FormTools.ControlHeight, button2.Bottom + FormTools.VerticalSpace) }; button3.Click += DeleteButton_Click; @@ -48,47 +57,60 @@ protected int CreateProfileManagementTabPage() { return result; } - private void CredentialsListBox_VisibleChanged(object sender, EventArgs e) { + private void CredentialsListBox_VisibleChanged(object sender, EventArgs e) + { PopulateCredentialsListBoxIfChanged(); } - private void PopulateCredentialsListBoxIfChanged() { + private void PopulateCredentialsListBoxIfChanged() + { if (_credentialsStoreChangeId != _credentialsStore.ChangeId) + { PopulateCredentialsListBox(); + } } - protected void PopulateCredentialsManagementTab(CredentialsStore store) { + protected void PopulateCredentialsManagementTab(CredentialsStore store) + { _credentialsStore = store; PopulateCredentialsListBox(); } - private void PopulateCredentialsListBox() { + private void PopulateCredentialsListBox() + { _credentialsListBox.Items.Clear(); - foreach (CredentialsProfile profile in _credentialsStore.Profiles) { + foreach (CredentialsProfile profile in _credentialsStore.Profiles) + { _credentialsListBox.Items.Add(profile); } _credentialsStoreChangeId = _credentialsStore.ChangeId; } - private void AddButton_Click(object sender, EventArgs e) { + private void AddButton_Click(object sender, EventArgs e) + { using AddCredentialsDialog addCredentialsDialog = new AddCredentialsDialog(base.AssociatedNode); - if (addCredentialsDialog.ShowDialog() == DialogResult.OK) { + if (addCredentialsDialog.ShowDialog() == DialogResult.OK) + { CredentialsProfile credentialsProfile = new CredentialsProfile(addCredentialsDialog.ProfileName, addCredentialsDialog.ProfileScope, addCredentialsDialog.UserName, addCredentialsDialog.Password.Value, addCredentialsDialog.Domain); if (!_credentialsStore.Contains(credentialsProfile.ProfileName)) + { _credentialsListBox.Items.Add(credentialsProfile); - + } _credentialsStore[credentialsProfile.ProfileName] = credentialsProfile; } } - private void EditButton_Click(object sender, EventArgs e) { + private void EditButton_Click(object sender, EventArgs e) + { int selectedIndex = _credentialsListBox.SelectedIndex; if (selectedIndex == -1) + { return; - + } CredentialsProfile credentialsProfile = _credentialsListBox.Items[selectedIndex] as CredentialsProfile; using LogonSettingsDialog logonSettingsDialog = LogonSettingsDialog.NewEditCredentialsDialog(credentialsProfile); - if (logonSettingsDialog.ShowDialog() == DialogResult.OK) { + if (logonSettingsDialog.ShowDialog() == DialogResult.OK) + { PasswordSetting password = (logonSettingsDialog.PasswordChanged ? logonSettingsDialog.Password : credentialsProfile.Password); credentialsProfile = new CredentialsProfile(credentialsProfile.ProfileName, credentialsProfile.ProfileScope, logonSettingsDialog.UserName, password, logonSettingsDialog.Domain); _credentialsStore[credentialsProfile.ProfileName] = credentialsProfile; @@ -96,73 +118,95 @@ private void EditButton_Click(object sender, EventArgs e) { } } - private void DeleteButton_Click(object sender, EventArgs e) { + private void DeleteButton_Click(object sender, EventArgs e) + { DeleteCredentials(); } - private void CredentialsListBox_KeyDown(object sender, KeyEventArgs e) { - if (e.KeyCode == Keys.Delete) { + private void CredentialsListBox_KeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Delete) + { e.Handled = true; DeleteCredentials(); } } - private void DeleteCredentials() { + private void DeleteCredentials() + { int selectedIndex = _credentialsListBox.SelectedIndex; if (selectedIndex == -1) + { return; - + } CredentialsProfile credentialsProfile = _credentialsListBox.Items[selectedIndex] as CredentialsProfile; ICollection credentialsInUseLocations = GetCredentialsInUseLocations(credentialsProfile); - if (credentialsInUseLocations.Count > 0) { + if (credentialsInUseLocations.Count > 0) + { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(credentialsProfile.ProfileName + " Щڵʹã").AppendLine(); - foreach (string item in credentialsInUseLocations) { + foreach (string item in credentialsInUseLocations) + { stringBuilder.AppendLine(item); } - stringBuilder.AppendLine().AppendLine("ȷҪɾ"); + stringBuilder.AppendLine().AppendLine("ȷҪɾ"); if (FormTools.YesNoDialog(stringBuilder.ToString()) != DialogResult.Yes) + { return; + } } _credentialsStore.Remove(credentialsProfile.ProfileName); _credentialsListBox.Items.RemoveAt(selectedIndex); RevertDeletedCredentials(credentialsProfile); } - private ICollection GetCredentialsInUseLocations(CredentialsProfile credentials) { + private ICollection GetCredentialsInUseLocations(CredentialsProfile credentials) + { HashSet inUseLocations = new HashSet(); ICollection nodes = ((base.AssociatedNode.FileGroup == null) ? ((IList)ServerTree.Instance.Nodes) : ((IList)new FileGroup[1] { base.AssociatedNode.FileGroup })); - foreach (TabPage tabPage in base.TabPages) { + foreach (TabPage tabPage in base.TabPages) + { if (tabPage is ICredentialsTabPage credentialsTabPage && credentialsTabPage.Credentials == credentials) + { inUseLocations.Add("{0}.{1}".InvariantFormat(Text, tabPage.Text)); + } } - nodes.VisitNodes(delegate (RdcTreeNode node) { + nodes.VisitNodes(delegate(RdcTreeNode node) + { if (node is VirtualGroup) + { return NodeVisitorResult.NoRecurse; - + } if (node.LogonCredentials.DirectlyReferences(credentials)) + { inUseLocations.Add("{0}.{1}".InvariantFormat(node.FullPath, "¼ƾ֤")); - + } if (node.GatewaySettings.DirectlyReferences(credentials)) + { inUseLocations.Add("{0}.{1}".InvariantFormat(node.FullPath, "")); - + } return NodeVisitorResult.Continue; }); return inUseLocations; } - private void RevertDeletedCredentials(CredentialsProfile credentials) { + private void RevertDeletedCredentials(CredentialsProfile credentials) + { ICollection nodes = ((base.AssociatedNode.FileGroup == null) ? ((IList)ServerTree.Instance.Nodes) : ((IList)new FileGroup[1] { base.AssociatedNode.FileGroup })); - nodes.VisitNodes(delegate (RdcTreeNode node) { + nodes.VisitNodes(delegate(RdcTreeNode node) + { if (node is VirtualGroup) + { return NodeVisitorResult.NoRecurse; - + } if (node.LogonCredentials.DirectlyReferences(credentials)) + { node.LogonCredentials.ProfileName.Reset(); - + } if (node.GatewaySettings.DirectlyReferences(credentials)) + { node.GatewaySettings.ProfileName.Reset(); - + } return NodeVisitorResult.Continue; }); } diff --git a/RdcMan/GroupBasePropertiesTabPage.cs b/RdcMan/GroupBasePropertiesTabPage.cs index dc6b159..fd1e870 100644 --- a/RdcMan/GroupBasePropertiesTabPage.cs +++ b/RdcMan/GroupBasePropertiesTabPage.cs @@ -1,26 +1,34 @@ -namespace RdcMan { - internal class GroupBasePropertiesTabPage : NodePropertiesPage where TSettingsGroup : GroupSettings { +namespace RdcMan +{ + internal class GroupBasePropertiesTabPage : NodePropertiesPage where TSettingsGroup : GroupSettings + { private RdcTextBox _groupNameTextBox; protected GroupBasePropertiesTabPage(TabbedSettingsDialog dialog, TSettingsGroup settings, string name) - : base(dialog, settings, name) { } + : base(dialog, settings, name) + { + } - protected void AddGroupName(ref int rowIndex, ref int tabIndex) { + protected void AddGroupName(ref int rowIndex, ref int tabIndex) + { _groupNameTextBox = FormTools.AddLabeledTextBox(this, "(&G)", base.Settings.GroupName, ref rowIndex, ref tabIndex); _groupNameTextBox.Enabled = true; - _groupNameTextBox.Validate = delegate { + _groupNameTextBox.Validate = delegate + { _groupNameTextBox.Text = _groupNameTextBox.Text.Trim(); string text = _groupNameTextBox.Text; if (text.Length == 0) + { return ""; - + } string pathSeparator = ServerTree.Instance.PathSeparator; return (text.IndexOf(pathSeparator) != -1) ? ("Ʋܰ·ָ \"" + pathSeparator + "\"") : null; }; base.FocusControl = _groupNameTextBox; } - protected override bool CanBeParent(GroupBase group) { + protected override bool CanBeParent(GroupBase group) + { return group.CanAddGroups(); } } diff --git a/RdcMan/GroupChangedEventArgs.cs b/RdcMan/GroupChangedEventArgs.cs index 4fff740..4e63c34 100644 --- a/RdcMan/GroupChangedEventArgs.cs +++ b/RdcMan/GroupChangedEventArgs.cs @@ -1,12 +1,15 @@ using System; -namespace RdcMan { - public class GroupChangedEventArgs : EventArgs { +namespace RdcMan +{ + public class GroupChangedEventArgs : EventArgs + { public GroupBase Group { get; private set; } public ChangeType ChangeType { get; private set; } - public GroupChangedEventArgs(GroupBase group, ChangeType changeType) { + public GroupChangedEventArgs(GroupBase group, ChangeType changeType) + { Group = group; ChangeType = changeType; } diff --git a/RdcMan/GroupDisplaySettings.cs b/RdcMan/GroupDisplaySettings.cs index 07e34a0..228fdc6 100644 --- a/RdcMan/GroupDisplaySettings.cs +++ b/RdcMan/GroupDisplaySettings.cs @@ -1,8 +1,10 @@ using System.Collections.Generic; using System.Windows.Forms; -namespace RdcMan { - public class GroupDisplaySettings : CommonDisplaySettings { +namespace RdcMan +{ + public class GroupDisplaySettings : CommonDisplaySettings + { private static Dictionary _settingProperties; protected override Dictionary SettingProperties => _settingProperties; @@ -16,11 +18,13 @@ public class GroupDisplaySettings : CommonDisplaySettings { [Setting("showDisconnectedThumbnails", DefaultValue = true)] public BoolSetting ShowDisconnectedThumbnails { get; protected set; } - static GroupDisplaySettings() { + static GroupDisplaySettings() + { typeof(GroupDisplaySettings).GetSettingProperties(out _settingProperties); } - public override TabPage CreateTabPage(TabbedSettingsDialog dialog) { + public override TabPage CreateTabPage(TabbedSettingsDialog dialog) + { return new GroupDisplaySettingsTabPage(dialog, this); } } diff --git a/RdcMan/GroupDisplaySettingsTabPage.cs b/RdcMan/GroupDisplaySettingsTabPage.cs index bb9b8bb..ae27719 100644 --- a/RdcMan/GroupDisplaySettingsTabPage.cs +++ b/RdcMan/GroupDisplaySettingsTabPage.cs @@ -1,33 +1,41 @@ using System.Drawing; -namespace RdcMan { - public class GroupDisplaySettingsTabPage : DisplaySettingsTabPage { +namespace RdcMan +{ + public class GroupDisplaySettingsTabPage : DisplaySettingsTabPage + { private readonly RdcCheckBox _previewCheckBox; private readonly RdcCheckBox _interactionCheckBox; public GroupDisplaySettingsTabPage(TabbedSettingsDialog dialog, GroupDisplaySettings settings) - : base(dialog, settings) { + : base(dialog, settings) + { Create(out var rowIndex, out var num); _previewCheckBox = FormTools.AddCheckBox(this, "ͼԤỰ(&P)", settings.SessionThumbnailPreview, 0, ref rowIndex, ref num); _interactionCheckBox = FormTools.AddCheckBox(this, "ͼỰ(&A)", settings.AllowThumbnailSessionInteraction, 0, ref rowIndex, ref num); _interactionCheckBox.Location = new Point(_previewCheckBox.Left + 24, _interactionCheckBox.Top); - _previewCheckBox.CheckedChanged += delegate { + _previewCheckBox.CheckedChanged += delegate + { PreviewCheckBoxChanged(); }; - if (base.InheritanceControl != null) { - base.InheritanceControl.EnabledChanged += delegate { + if (base.InheritanceControl != null) + { + base.InheritanceControl.EnabledChanged += delegate + { PreviewCheckBoxChanged(); }; } FormTools.AddCheckBox(this, "ʾϿӵͼ(&D)", settings.ShowDisconnectedThumbnails, 0, ref rowIndex, ref num); } - private void PreviewCheckBoxChanged() { + private void PreviewCheckBoxChanged() + { _interactionCheckBox.Enabled = _previewCheckBox.Checked && _previewCheckBox.Enabled; } - protected override void UpdateControls() { + protected override void UpdateControls() + { base.UpdateControls(); PreviewCheckBoxChanged(); } diff --git a/RdcMan/GroupPropertiesDialog.cs b/RdcMan/GroupPropertiesDialog.cs index cf9ce85..bfa78ce 100644 --- a/RdcMan/GroupPropertiesDialog.cs +++ b/RdcMan/GroupPropertiesDialog.cs @@ -1,32 +1,41 @@ using System.Windows.Forms; -namespace RdcMan { - internal class GroupPropertiesDialog : GroupBasePropertiesDialog { +namespace RdcMan +{ + internal class GroupPropertiesDialog : GroupBasePropertiesDialog + { protected GroupPropertiesDialog(GroupBase group, string dialogTitle, string acceptButtonText, Form parentForm) - : base(group, dialogTitle, acceptButtonText, parentForm) { + : base(group, dialogTitle, acceptButtonText, parentForm) + { } - public override void CreateControls(RdcTreeNode settingsNode) { + public override void CreateControls(RdcTreeNode settingsNode) + { GroupPropertiesTabPage page = (GroupPropertiesTabPage)(base.PropertiesPage = settingsNode.Properties.CreateTabPage(this) as GroupPropertiesTabPage); AddTabPage(page); base.PropertiesPage.ParentGroupChanged += base.PopulateCredentialsProfiles; base.CreateControls(settingsNode); } - public static GroupPropertiesDialog NewAddDialog(GroupBase parent) { + public static GroupPropertiesDialog NewAddDialog(GroupBase parent) + { Group group = Group.CreateForAddDialog(); GroupPropertiesDialog groupPropertiesDialog = new GroupPropertiesDialog(group, "", "", null); groupPropertiesDialog.CreateControls(group); if (parent != null && !parent.CanAddGroups()) + { parent = null; - if (!groupPropertiesDialog.PropertiesPage.PopulateParentDropDown(null, parent)) { + } + if (!groupPropertiesDialog.PropertiesPage.PopulateParentDropDown(null, parent)) + { groupPropertiesDialog.Dispose(); return null; } return groupPropertiesDialog; } - public static GroupPropertiesDialog NewPropertiesDialog(Group group, Form parentForm) { + public static GroupPropertiesDialog NewPropertiesDialog(Group group, Form parentForm) + { GroupPropertiesDialog groupPropertiesDialog = new GroupPropertiesDialog(group, group.Text + " ", "ȷ", parentForm); groupPropertiesDialog.CreateControls(group); groupPropertiesDialog.PropertiesPage.PopulateParentDropDown(group, group.Parent as GroupBase); diff --git a/RdcMan/GroupPropertiesTabPage.cs b/RdcMan/GroupPropertiesTabPage.cs index 58c0b9f..3917636 100644 --- a/RdcMan/GroupPropertiesTabPage.cs +++ b/RdcMan/GroupPropertiesTabPage.cs @@ -1,7 +1,10 @@ -namespace RdcMan { - internal class GroupPropertiesTabPage : GroupBasePropertiesTabPage { +namespace RdcMan +{ + internal class GroupPropertiesTabPage : GroupBasePropertiesTabPage + { public GroupPropertiesTabPage(TabbedSettingsDialog dialog, GroupSettings settings) - : base(dialog, settings, settings.Name) { + : base(dialog, settings, settings.Name) + { int rowIndex = 0; int num = 0; AddGroupName(ref rowIndex, ref num); diff --git a/RdcMan/GroupSettings.cs b/RdcMan/GroupSettings.cs index c4e43d3..f023a56 100644 --- a/RdcMan/GroupSettings.cs +++ b/RdcMan/GroupSettings.cs @@ -2,9 +2,11 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { - public class GroupSettings : CommonNodeSettings { - //internal const string TabName = ""; +namespace RdcMan +{ + public class GroupSettings : CommonNodeSettings + { + //internal const string TabName = "Group Settings"; private static Dictionary _settingProperties; @@ -15,7 +17,8 @@ public class GroupSettings : CommonNodeSettings { protected override Dictionary SettingProperties => _settingProperties; - static GroupSettings() { + static GroupSettings() + { typeof(GroupSettings).GetSettingProperties(out _settingProperties); } @@ -23,18 +26,23 @@ static GroupSettings() { protected GroupSettings(string name) : base(name) { } - public override TabPage CreateTabPage(TabbedSettingsDialog dialog) { + public override TabPage CreateTabPage(TabbedSettingsDialog dialog) + { return new GroupPropertiesTabPage(dialog, this); } - protected override void WriteSettings(XmlTextWriter tw, RdcTreeNode node) { + protected override void WriteSettings(XmlTextWriter tw, RdcTreeNode node) + { HashSet hashSet = new HashSet(); if (string.IsNullOrEmpty(base.Comment.Value)) + { hashSet.Add(base.Comment); - + } base.WriteSettings(tw, node, hashSet); } - protected override void Copy(RdcTreeNode node) { } + protected override void Copy(RdcTreeNode node) + { + } } } diff --git a/RdcMan/HeaderColumnClickEventArgs.cs b/RdcMan/HeaderColumnClickEventArgs.cs index 92ebedd..5188457 100644 --- a/RdcMan/HeaderColumnClickEventArgs.cs +++ b/RdcMan/HeaderColumnClickEventArgs.cs @@ -1,12 +1,15 @@ using System; -namespace RdcMan { - public class HeaderColumnClickEventArgs : EventArgs { +namespace RdcMan +{ + public class HeaderColumnClickEventArgs : EventArgs + { public int Column { get; private set; } public bool IsChecked { get; private set; } - public HeaderColumnClickEventArgs(int column, bool isChecked) { + public HeaderColumnClickEventArgs(int column, bool isChecked) + { Column = column; IsChecked = isChecked; } diff --git a/RdcMan/HeaderColumnClickEventHandler.cs b/RdcMan/HeaderColumnClickEventHandler.cs index ea88dd0..c058ef4 100644 --- a/RdcMan/HeaderColumnClickEventHandler.cs +++ b/RdcMan/HeaderColumnClickEventHandler.cs @@ -1,3 +1,4 @@ -namespace RdcMan { +namespace RdcMan +{ public delegate void HeaderColumnClickEventHandler(object sender, HeaderColumnClickEventArgs args); } diff --git a/RdcMan/Helpers.cs b/RdcMan/Helpers.cs index a680adf..730ab88 100644 --- a/RdcMan/Helpers.cs +++ b/RdcMan/Helpers.cs @@ -8,16 +8,20 @@ using System.Xml; using Win32; -namespace RdcMan { - public static class Helpers { +namespace RdcMan +{ + public static class Helpers + { public delegate void ReadXmlDelegate(XmlNode childNode, RdcTreeNode node, ICollection errors); - private class OperationTimer : IDisposable { - private readonly Stopwatch _stopWatch; + private class OperationTimer : IDisposable + { + private Stopwatch _stopWatch; - private readonly string _text; + private string _text; - public OperationTimer(string text) { + public OperationTimer(string text) + { _text = text; _stopWatch = new Stopwatch(); _stopWatch.Start(); @@ -25,33 +29,40 @@ public OperationTimer(string text) { Log.AdjustIndent(1); } - void IDisposable.Dispose() { + void IDisposable.Dispose() + { _stopWatch.Stop(); Log.AdjustIndent(-1); Log.Write("Finished {0}: {1} ms", _text, _stopWatch.ElapsedMilliseconds); } } - public static bool IsControlKeyPressed { - get { + public static bool IsControlKeyPressed + { + get + { short asyncKeyState = User.GetAsyncKeyState(17); return (asyncKeyState & 0x8000) != 0; } } - public static void Add(this Control.ControlCollection collection, params Control[] controls) { + public static void Add(this Control.ControlCollection collection, params Control[] controls) + { collection.AddRange(controls); } - public static string GetName(this XmlNode node) { + public static string GetName(this XmlNode node) + { XmlAttribute xmlAttribute = node.Attributes["name"]; return xmlAttribute != null ? xmlAttribute.Value : node.Name; } - public static string GetFullPath(this XmlNode node) { + public static string GetFullPath(this XmlNode node) + { StringBuilder stringBuilder = new StringBuilder(node.GetName()); XmlNode parentNode = node.ParentNode; - while (parentNode != null && !(parentNode is XmlDocument)) { + while (parentNode != null && !(parentNode is XmlDocument)) + { stringBuilder.Insert(0, "/"); stringBuilder.Insert(0, parentNode.GetName()); parentNode = parentNode.ParentNode; @@ -59,21 +70,29 @@ public static string GetFullPath(this XmlNode node) { return stringBuilder.ToString(); } - public static void ForEach(this IEnumerable objects, Action action) { + public static void ForEach(this IEnumerable objects, Action action) + { foreach (TObject @object in objects) + { action(@object); + } } - public static void ForEach(this TreeNodeCollection objects, Action action) { + public static void ForEach(this TreeNodeCollection objects, Action action) + { foreach (TreeNode @object in objects) + { action(@object); + } } - public static TEnum ParseEnum(this string value) where TEnum : struct { + public static TEnum ParseEnum(this string value) where TEnum : struct + { return (TEnum)Enum.Parse(typeof(TEnum), value); } - public static IEnumerable EnumValues() where TEnum : struct { + public static IEnumerable EnumValues() where TEnum : struct + { return Enum.GetValues(typeof(TEnum)).Cast(); } @@ -86,45 +105,57 @@ public static string SortOrderToString(SortOrder sortOrder) { }; } - public static string GetTemporaryFileName(string fileName, string suffix) { + public static string GetTemporaryFileName(string fileName, string suffix) + { string text = fileName + suffix; int num = 0; while (File.Exists(text)) + { text = fileName + suffix + num++; - + } return text; } - public static void MoveTemporaryToPermanent(string newFileName, string fileName, bool saveOld) { + public static void MoveTemporaryToPermanent(string newFileName, string fileName, bool saveOld) + { string temporaryFileName = GetTemporaryFileName(fileName, ".old"); if (File.Exists(fileName)) + { File.Move(fileName, temporaryFileName); - + } File.Move(newFileName, fileName); - if (!saveOld) + { File.Delete(temporaryFileName); + } } - public static int NaturalCompare(string x, string y) { + public static int NaturalCompare(string x, string y) + { int i = 0; int i2 = 0; - while (i < x.Length && i2 < y.Length) { + while (i < x.Length && i2 < y.Length) + { char c = char.ToLowerInvariant(x[i]); char c2 = char.ToLowerInvariant(y[i]); - if (char.IsDigit(c) && char.IsDigit(c2)) { + if (char.IsDigit(c) && char.IsDigit(c2)) + { uint num = ParseNumber(x, ref i); uint num2 = ParseNumber(y, ref i2); if (num != num2) return num >= num2 ? 1 : -1; if (i != i2) + { return i2 - i; + } } - else { + else + { if (c != c2) + { return c - c2; - + } i++; i2++; } @@ -132,15 +163,18 @@ public static int NaturalCompare(string x, string y) { return x.Length - y.Length; } - private static uint ParseNumber(string s, ref int i) { + private static uint ParseNumber(string s, ref int i) + { uint num = (uint)(s[i] - 48); while (++i < s.Length && char.IsDigit(s[i])) + { num = num * 10 + s[i] - 48; - + } return num; } - public static IDisposable Timer(string format, params object[] args) { + public static IDisposable Timer(string format, params object[] args) + { return new OperationTimer(format.InvariantFormat(args)); } diff --git a/RdcMan/HotKeyBox.cs b/RdcMan/HotKeyBox.cs index 1e09702..489eb8f 100644 --- a/RdcMan/HotKeyBox.cs +++ b/RdcMan/HotKeyBox.cs @@ -1,43 +1,57 @@ using System.Windows.Forms; -namespace RdcMan { - public class HotKeyBox : TextBox, ISettingControl { +namespace RdcMan +{ + public class HotKeyBox : TextBox, ISettingControl + { private Keys _hotKey; public string Prefix { get; set; } public EnumSetting Setting { get; set; } - public Keys HotKey { + public Keys HotKey + { get => _hotKey; - set { + set + { _hotKey = value; Text = string.Concat(str1: (HotKey == Keys.Next) ? "PageDown" : ((HotKey == Keys.Cancel) ? "Break" : ((HotKey >= Keys.D0 && HotKey <= Keys.D9) ? ((int)(HotKey - 48)).ToString() : ((HotKey < Keys.NumPad0 || HotKey > Keys.NumPad9) ? HotKey.ToString() : ((int)(HotKey - 96) + " (num pad)")))), str0: Prefix).ToUpper(); } } - protected override bool ProcessCmdKey(ref Message m, Keys keyData) { + protected override bool ProcessCmdKey(ref Message m, Keys keyData) + { Keys keys = keyData & Keys.KeyCode; if (keys == Keys.Tab || keys == Keys.Escape) + { return base.ProcessCmdKey(ref m, keyData); - + } if ((keyData & Keys.Modifiers) == 0 || keys == Keys.Cancel) + { HotKey = keys; - + } return true; } - void ISettingControl.UpdateControl() { + void ISettingControl.UpdateControl() + { if (Setting != null) + { HotKey = Setting.Value; + } } - void ISettingControl.UpdateSetting() { + void ISettingControl.UpdateSetting() + { if (Setting != null) + { Setting.Value = HotKey; + } } - string ISettingControl.Validate() { + string ISettingControl.Validate() + { return null; } } diff --git a/RdcMan/IBuiltInVirtualGroup.cs b/RdcMan/IBuiltInVirtualGroup.cs index 74f07f6..960aecc 100644 --- a/RdcMan/IBuiltInVirtualGroup.cs +++ b/RdcMan/IBuiltInVirtualGroup.cs @@ -1,8 +1,10 @@ using System.Collections.Generic; using System.Xml; -namespace RdcMan { - internal interface IBuiltInVirtualGroup { +namespace RdcMan +{ + internal interface IBuiltInVirtualGroup + { string XmlNodeName { get; } string Text { get; } diff --git a/RdcMan/ICredentialsTabPage.cs b/RdcMan/ICredentialsTabPage.cs index 0cd448d..2f472ef 100644 --- a/RdcMan/ICredentialsTabPage.cs +++ b/RdcMan/ICredentialsTabPage.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public interface ICredentialsTabPage { +namespace RdcMan +{ + public interface ICredentialsTabPage + { CredentialsProfile Credentials { get; } void PopulateCredentialsProfiles(FileGroup file); diff --git a/RdcMan/IDeferDecryption.cs b/RdcMan/IDeferDecryption.cs index d988fad..9e661b4 100644 --- a/RdcMan/IDeferDecryption.cs +++ b/RdcMan/IDeferDecryption.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public interface IDeferDecryption { +namespace RdcMan +{ + public interface IDeferDecryption + { bool IsDecrypted { get; set; } void Decrypt(EncryptionSettings settings); diff --git a/RdcMan/ILogonCredentials.cs b/RdcMan/ILogonCredentials.cs index 4551d34..840303a 100644 --- a/RdcMan/ILogonCredentials.cs +++ b/RdcMan/ILogonCredentials.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public interface ILogonCredentials { +namespace RdcMan +{ + public interface ILogonCredentials + { string ProfileName { get; } ProfileScope ProfileScope { get; } diff --git a/RdcMan/IMainForm.cs b/RdcMan/IMainForm.cs index 9817d5a..0b5e042 100644 --- a/RdcMan/IMainForm.cs +++ b/RdcMan/IMainForm.cs @@ -1,8 +1,10 @@ using System; using System.Windows.Forms; -namespace RdcMan { - public interface IMainForm { +namespace RdcMan +{ + public interface IMainForm + { MenuStrip MainMenuStrip { get; } bool RegisterShortcut(Keys shortcutKey, Action action); diff --git a/RdcMan/INodePropertiesPage.cs b/RdcMan/INodePropertiesPage.cs index 2bc3e51..f9ba964 100644 --- a/RdcMan/INodePropertiesPage.cs +++ b/RdcMan/INodePropertiesPage.cs @@ -1,7 +1,9 @@ using System; -namespace RdcMan { - public interface INodePropertiesPage { +namespace RdcMan +{ + public interface INodePropertiesPage + { GroupBase ParentGroup { get; } event Action ParentGroupChanged; diff --git a/RdcMan/IPlugin.cs b/RdcMan/IPlugin.cs index 3c875d6..de342d5 100644 --- a/RdcMan/IPlugin.cs +++ b/RdcMan/IPlugin.cs @@ -1,8 +1,10 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { - public interface IPlugin { +namespace RdcMan +{ + public interface IPlugin + { void PreLoad(IPluginContext context, XmlNode xmlNode); void PostLoad(IPluginContext context); diff --git a/RdcMan/IPluginContext.cs b/RdcMan/IPluginContext.cs index 92a9f88..356bc58 100644 --- a/RdcMan/IPluginContext.cs +++ b/RdcMan/IPluginContext.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public interface IPluginContext { +namespace RdcMan +{ + public interface IPluginContext + { IMainForm MainForm { get; } IServerTree Tree { get; } diff --git a/RdcMan/IRdpClient.cs b/RdcMan/IRdpClient.cs index d74ca10..f1315d9 100644 --- a/RdcMan/IRdpClient.cs +++ b/RdcMan/IRdpClient.cs @@ -1,3 +1,4 @@ -namespace RdcMan { +namespace RdcMan +{ internal interface IRdpClient { } } diff --git a/RdcMan/IServerRefFactory.cs b/RdcMan/IServerRefFactory.cs index a0e7c10..1321194 100644 --- a/RdcMan/IServerRefFactory.cs +++ b/RdcMan/IServerRefFactory.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - internal interface IServerRefFactory { +namespace RdcMan +{ + internal interface IServerRefFactory + { ServerRef Create(Server server); } } diff --git a/RdcMan/IServerTree.cs b/RdcMan/IServerTree.cs index 849c1ba..53c535c 100644 --- a/RdcMan/IServerTree.cs +++ b/RdcMan/IServerTree.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public interface IServerTree { +namespace RdcMan +{ + public interface IServerTree + { GroupBase RootNode { get; } void AddNode(RdcTreeNode node, GroupBase parent); diff --git a/RdcMan/ISetting.cs b/RdcMan/ISetting.cs index 2bb5097..cd0cbbe 100644 --- a/RdcMan/ISetting.cs +++ b/RdcMan/ISetting.cs @@ -1,7 +1,9 @@ using System.Xml; -namespace RdcMan { - public interface ISetting { +namespace RdcMan +{ + public interface ISetting + { void ReadXml(XmlNode xmlNode, RdcTreeNode node); void WriteXml(XmlTextWriter tw, RdcTreeNode node); diff --git a/RdcMan/ISettingControl.cs b/RdcMan/ISettingControl.cs index e25679e..e9b7479 100644 --- a/RdcMan/ISettingControl.cs +++ b/RdcMan/ISettingControl.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public interface ISettingControl { +namespace RdcMan +{ + public interface ISettingControl + { void UpdateControl(); void UpdateSetting(); diff --git a/RdcMan/ISettingsTabPage.cs b/RdcMan/ISettingsTabPage.cs index 9d11bc7..ef2d419 100644 --- a/RdcMan/ISettingsTabPage.cs +++ b/RdcMan/ISettingsTabPage.cs @@ -1,7 +1,9 @@ using System.Windows.Forms; -namespace RdcMan { - public interface ISettingsTabPage { +namespace RdcMan +{ + public interface ISettingsTabPage + { InheritanceControl InheritanceControl { get; } Control FocusControl { get; } diff --git a/RdcMan/IUndockedServerForm.cs b/RdcMan/IUndockedServerForm.cs index 01467b6..0f6ec5e 100644 --- a/RdcMan/IUndockedServerForm.cs +++ b/RdcMan/IUndockedServerForm.cs @@ -1,7 +1,9 @@ using System.Windows.Forms; -namespace RdcMan { - public interface IUndockedServerForm { +namespace RdcMan +{ + public interface IUndockedServerForm + { MenuStrip MainMenuStrip { get; } ServerBase Server { get; } diff --git a/RdcMan/ImageConstants.cs b/RdcMan/ImageConstants.cs index be1de20..46a3b4c 100644 --- a/RdcMan/ImageConstants.cs +++ b/RdcMan/ImageConstants.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public enum ImageConstants { +namespace RdcMan +{ + public enum ImageConstants + { DisconnectedServer, ConnectingServer, ConnectingSelectedServer, diff --git a/RdcMan/ImportServersPropertiesPage.cs b/RdcMan/ImportServersPropertiesPage.cs index 3b252a9..5bc5eb5 100644 --- a/RdcMan/ImportServersPropertiesPage.cs +++ b/RdcMan/ImportServersPropertiesPage.cs @@ -5,26 +5,31 @@ using System.Text.RegularExpressions; using System.Windows.Forms; -namespace RdcMan { - internal class ImportServersPropertiesPage : NodePropertiesPage { - private readonly RdcTextBox _fileNameTextBox; +namespace RdcMan +{ + internal class ImportServersPropertiesPage : NodePropertiesPage + { + private RdcTextBox _fileNameTextBox; - private readonly RdcTextBox _serversTextBox; + private RdcTextBox _serversTextBox; public List ExpandedServerNames { get; private set; } public ImportServersPropertiesPage(TabbedSettingsDialog dialog) - : base(dialog, (SettingsGroup)null, "") { + : base(dialog, (SettingsGroup)null, "") + { int num = 0; int num2 = 0; - Label value = new Label { + Label value = new Label + { Location = FormTools.NewLocation(0, num2), Size = new Size(480, 48), Text = "ѡзϢļıϢɶźͻзָչ." }; num2 += 2; base.Controls.Add(value); - Button browseButton = new Button { + Button browseButton = new Button + { TabIndex = num++, Text = "(&B)" }; @@ -40,10 +45,12 @@ public ImportServersPropertiesPage(TabbedSettingsDialog dialog) num2 += 6; base.Controls.Add(browseButton, _serversTextBox); AddParentCombo(ref num2, ref num); - _fileNameTextBox.TextChanged += delegate { + _fileNameTextBox.TextChanged += delegate + { _serversTextBox.Enabled = string.IsNullOrEmpty(_fileNameTextBox.Text); }; - _serversTextBox.TextChanged += delegate { + _serversTextBox.TextChanged += delegate + { RdcTextBox fileNameTextBox = _fileNameTextBox; bool enabled = (browseButton.Enabled = string.IsNullOrEmpty(_serversTextBox.Text)); fileNameTextBox.Enabled = enabled; @@ -51,45 +58,55 @@ public ImportServersPropertiesPage(TabbedSettingsDialog dialog) base.FocusControl = _fileNameTextBox; } - protected override bool IsValid() { + protected override bool IsValid() + { Control c = _serversTextBox; string text = _serversTextBox.Text; base.Dialog.SetError(_serversTextBox, null); base.Dialog.SetError(_fileNameTextBox, null); - if (!string.IsNullOrEmpty(_fileNameTextBox.Text)) { + if (!string.IsNullOrEmpty(_fileNameTextBox.Text)) + { c = _fileNameTextBox; - try { + try + { text = File.ReadAllText(_fileNameTextBox.Text); } - catch (Exception ex) { + catch (Exception ex) + { base.Dialog.SetError(_fileNameTextBox, ex.Message); return false; } } - if (string.IsNullOrWhiteSpace(text)) { + if (string.IsNullOrWhiteSpace(text)) + { base.Dialog.SetError(_fileNameTextBox, "ļ"); return false; } - try { + try + { List list = new List(); text = text.Replace(Environment.NewLine, ","); MatchCollection matchCollection = Regex.Matches(text, "([^,\\{\\s]*\\{[^\\}]*\\}[^,\\{,\\}\\s]*)|([^,\\{\\}\\s]+)"); - foreach (Match item in matchCollection) { + foreach (Match item in matchCollection) + { list.AddRange(StringUtilities.ExpandPattern(item.Groups[0].Value.Trim())); } ExpandedServerNames = list; } - catch (Exception ex2) { + catch (Exception ex2) + { base.Dialog.SetError(c, ex2.Message); } return true; } - protected override bool CanBeParent(GroupBase group) { + protected override bool CanBeParent(GroupBase group) + { return group.CanAddServers(); } - private void OnBrowseClick(object sender, EventArgs e) { + private void OnBrowseClick(object sender, EventArgs e) + { using OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Title = ""; openFileDialog.DefaultExt = "txt"; @@ -98,7 +115,9 @@ private void OnBrowseClick(object sender, EventArgs e) { openFileDialog.RestoreDirectory = false; openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"; if (openFileDialog.ShowDialog() == DialogResult.OK) + { _fileNameTextBox.Text = openFileDialog.FileName; + } } } } diff --git a/RdcMan/InheritSettingsType.cs b/RdcMan/InheritSettingsType.cs index 42831f4..b6fee5d 100644 --- a/RdcMan/InheritSettingsType.cs +++ b/RdcMan/InheritSettingsType.cs @@ -1,27 +1,33 @@ using System; using System.Xml; -namespace RdcMan { - public class InheritSettingsType { +namespace RdcMan +{ + public class InheritSettingsType + { public InheritanceMode Mode { get; set; } - public InheritSettingsType() { + public InheritSettingsType() + { Mode = InheritanceMode.FromParent; } - public GroupBase GetInheritedSettingsNode(RdcTreeNode node) { - switch (Mode) { - case InheritanceMode.None: - case InheritanceMode.Disabled: - return null; - case InheritanceMode.FromParent: + public GroupBase GetInheritedSettingsNode(RdcTreeNode node) + { + switch (Mode) + { + case InheritanceMode.None: + case InheritanceMode.Disabled: + return null; + case InheritanceMode.FromParent: return (node.Parent != null) ? node.Parent as GroupBase : DefaultSettingsGroup.Instance; - default: - throw new Exception("Unexpected inheritance kind"); + default: + throw new Exception("Unexpected inheritance kind"); } } - public void WriteXml(XmlTextWriter tw) { + public void WriteXml(XmlTextWriter tw) + { tw.WriteAttributeString("inherit", Mode.ToString()); } } diff --git a/RdcMan/InheritanceControl.cs b/RdcMan/InheritanceControl.cs index f74652c..ff86ecd 100644 --- a/RdcMan/InheritanceControl.cs +++ b/RdcMan/InheritanceControl.cs @@ -3,8 +3,10 @@ using System.Linq; using System.Windows.Forms; -namespace RdcMan { - public class InheritanceControl { +namespace RdcMan +{ + public class InheritanceControl + { public CheckBox FromParentCheck; //private const string SourcePrefix = "Source: "; @@ -23,15 +25,18 @@ public class InheritanceControl { public event Action EnabledChanged; - public InheritanceControl(TabbedSettingsDialog dialog, string settingsGroupName) { + public InheritanceControl(TabbedSettingsDialog dialog, string settingsGroupName) + { _dialog = dialog; _settingsGroupName = settingsGroupName; _sourceNode = DefaultSettingsGroup.Instance; _enabled = true; } - public void Create(Control parent, ref int rowIndex, ref int tabIndex) { - _disabledLabel = new Label { + public void Create(Control parent, ref int rowIndex, ref int tabIndex) + { + _disabledLabel = new Label + { Enabled = true, Location = new Point(0, (parent.Height - FormTools.ControlHeight) / 2), Size = new Size(parent.Width, FormTools.ControlHeight), @@ -40,7 +45,8 @@ public void Create(Control parent, ref int rowIndex, ref int tabIndex) { }; FromParentCheck = FormTools.NewCheckBox("Ӹ̳(&H)", 1, rowIndex++, tabIndex++); FromParentCheck.CheckedChanged += CheckChangedHandler; - _sourceButton = new Button { + _sourceButton = new Button + { Location = FormTools.NewLocation(1, rowIndex++) }; _sourceButton.Size = new Size(340, _sourceButton.Height); @@ -51,17 +57,20 @@ public void Create(Control parent, ref int rowIndex, ref int tabIndex) { parent.Controls.Add(_sourceButton); } - private void SourceButton_Click(object sender, EventArgs e) { + private void SourceButton_Click(object sender, EventArgs e) + { string activeTabName = ((_sourceButton.Parent is TabPage tabPage) ? tabPage.Text : string.Empty); _sourceNode.DoPropertiesDialog(_sourceButton.FindForm(), activeTabName); } - private void SourceButton_TextChanged(object sender, EventArgs e) { + private void SourceButton_TextChanged(object sender, EventArgs e) + { string text = _sourceButton.Text; Graphics graphics = _sourceButton.CreateGraphics(); bool flag = false; SizeF sizeF = graphics.MeasureString(text, _sourceButton.Font); - while (Math.Round(sizeF.Width, 1) > (double)_sourceButton.Width) { + while (Math.Round(sizeF.Width, 1) > (double)_sourceButton.Width) + { double num = Math.Round(sizeF.Width, 0) - (double)_sourceButton.Width; int num2 = (int)Math.Round(num / (double)_sourceButton.Font.Size, 0) + 4; text = "Source: ..." + text.Substring(num2 + "Source: ".Length); @@ -69,76 +78,109 @@ private void SourceButton_TextChanged(object sender, EventArgs e) { sizeF = graphics.MeasureString(text, _sourceButton.Font); } if (flag) + { _sourceButton.Text = text; + } } - public void UpdateControlsFromSettings(InheritSettingsType settings) { + public void UpdateControlsFromSettings(InheritSettingsType settings) + { bool flag = settings.Mode == InheritanceMode.FromParent; if (flag != FromParentCheck.Checked) + { FromParentCheck.Checked = flag; + } else + { OnSettingChanged(); + } } - public void Enable(bool value, string reason) { + public void Enable(bool value, string reason) + { _enabled = value; _disabledLabel.Text = "Щò {0}".InvariantFormat(reason); - foreach (Control control in FromParentCheck.Parent.Controls) { + foreach (Control control in FromParentCheck.Parent.Controls) + { control.Visible = _enabled; } _disabledLabel.Enabled = !_enabled; _disabledLabel.Visible = !_enabled; if (_enabled) + { OnSettingChanged(); + } } - private void CheckChangedHandler(object sender, EventArgs e) { + private void CheckChangedHandler(object sender, EventArgs e) + { OnSettingChanged(); } - private void OnSettingChanged() { + private void OnSettingChanged() + { CheckBox fromParentCheck = FromParentCheck; EnableDisableControls(!fromParentCheck.Checked); - if (fromParentCheck.Checked) { + if (fromParentCheck.Checked) + { GroupBase groupBase = _dialog.TabPages.OfType().First().ParentGroup; - if (groupBase != _sourceNode) { + if (groupBase != _sourceNode) + { if (groupBase == null) + { _sourceNode = DefaultSettingsGroup.Instance; - else { - while (true) { + } + else + { + while (true) + { SettingsGroup settingsGroupByName = groupBase.GetSettingsGroupByName(_settingsGroupName); if (settingsGroupByName.InheritSettingsType.Mode != 0) + { break; - + } groupBase = settingsGroupByName.InheritSettingsType.GetInheritedSettingsNode(groupBase); } _sourceNode = groupBase; } } if (_sourceNode != DefaultSettingsGroup.Instance) + { _sourceButton.Text = "Source: " + _sourceNode.FullPath; + } else + { _sourceButton.Text = "Source: Ĭ"; - + } _sourceButton.Show(); } else + { _sourceButton.Hide(); + } } - public void EnableDisableControls(bool enable) { - foreach (Control control in FromParentCheck.Parent.Controls) { + public void EnableDisableControls(bool enable) + { + foreach (Control control in FromParentCheck.Parent.Controls) + { if (control != FromParentCheck && control != _sourceButton) + { control.Enabled = enable; + } } if (this.EnabledChanged != null) + { this.EnabledChanged(enable); + } } - public InheritanceMode GetInheritanceMode() { + public InheritanceMode GetInheritanceMode() + { if (FromParentCheck.Checked) + { return InheritanceMode.FromParent; - + } return InheritanceMode.None; } } diff --git a/RdcMan/InheritanceMode.cs b/RdcMan/InheritanceMode.cs index 9ec554e..1ef64a7 100644 --- a/RdcMan/InheritanceMode.cs +++ b/RdcMan/InheritanceMode.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public enum InheritanceMode { +namespace RdcMan +{ + public enum InheritanceMode + { FromParent, None, Disabled diff --git a/RdcMan/IntSetting.cs b/RdcMan/IntSetting.cs index bb4f301..e8b1c75 100644 --- a/RdcMan/IntSetting.cs +++ b/RdcMan/IntSetting.cs @@ -1,10 +1,13 @@ using System.Xml; -namespace RdcMan { - public class IntSetting : Setting { +namespace RdcMan +{ + public class IntSetting : Setting + { public IntSetting(object o) : base(o) { } - public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) { + public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) + { base.Value = int.Parse(xmlNode.FirstChild.InnerText); } } diff --git a/RdcMan/ListSessionsForm.cs b/RdcMan/ListSessionsForm.cs index b447455..0c803b7 100644 --- a/RdcMan/ListSessionsForm.cs +++ b/RdcMan/ListSessionsForm.cs @@ -7,8 +7,10 @@ using System.Windows.Forms; using Win32; -namespace RdcMan { - internal class ListSessionsForm : Form { +namespace RdcMan +{ + internal class ListSessionsForm : Form + { //private IContainer components; public Label StatusLabel; @@ -33,11 +35,14 @@ internal class ListSessionsForm : Form { private bool _areQuerying; - protected override void Dispose(bool disposing) { - //if (disposing && components != null) - // components.Dispose(); - base.Dispose(disposing); - } + //protected override void Dispose(bool disposing) + //{ + // if (disposing && components != null) + // { + // components.Dispose(); + // } + // base.Dispose(disposing); + //} private void InitializeComponent() { base.SuspendLayout(); @@ -86,10 +91,10 @@ private void InitializeComponent() { UseVisualStyleBackColor = true }; this.RefreshButton.Click += new EventHandler(RefreshButton_Click); + base.ClientSize = new Size(366, 206); base.Controls.Add(this.RefreshButton); base.Controls.Add(this.SessionListView); base.Controls.Add(this.StatusLabel); - base.ClientSize = new Size(366, 206); base.Name = "ListSessionsForm"; base.Load += new EventHandler(ListSessionsForm_Load); base.SizeChanged += new EventHandler(ListSessionsForm_SizeChanged); @@ -98,7 +103,8 @@ private void InitializeComponent() { base.ResumeLayout(false); } - public ListSessionsForm(ServerBase server) { + public ListSessionsForm(ServerBase server) + { InitializeComponent(); _remoteSessions = new RemoteSessions(server); _areQuerying = true; @@ -112,21 +118,25 @@ public ListSessionsForm(ServerBase server) { base.Icon = Program.TheForm.Icon; } - private ListViewItem GetSelection() { + private ListViewItem GetSelection() + { ListView sessionListView = SessionListView; if (sessionListView.SelectedItems.Count != 1) + { return null; - + } IEnumerator enumerator = sessionListView.SelectedItems.GetEnumerator(); enumerator.MoveNext(); return enumerator.Current as ListViewItem; } - private void ListSessionsForm_Load(object sender, EventArgs e) { + private void ListSessionsForm_Load(object sender, EventArgs e) + { ThreadPool.QueueUserWorkItem(OpenThreadProc, this); } - private static void OpenThreadProc(object o) { + private static void OpenThreadProc(object o) + { ListSessionsForm form = o as ListSessionsForm; if (!form._remoteSessions.OpenServer()) { form.Invoke((MethodInvoker)delegate { @@ -134,15 +144,20 @@ private static void OpenThreadProc(object o) { }); } else + { QuerySessions(form); + } } - private static void QuerySessions(object o) { + private static void QuerySessions(object o) + { ListSessionsForm form = o as ListSessionsForm; - if (form.IsDisposed) { + if (form.IsDisposed) + { return; } - form.Invoke((MethodInvoker)delegate { + form.Invoke((MethodInvoker)delegate + { form.SessionListView.BeginUpdate(); form.SessionListView.Items.Clear(); }); @@ -153,20 +168,24 @@ private static void QuerySessions(object o) { }); return; } - foreach (RemoteSessionInfo item in list) { + foreach (RemoteSessionInfo item in list) + { Wts.ConnectstateClass connectstateClass = item.State; string text = ((item.DomainName.Length <= 0) ? item.UserName : (item.DomainName + "\\" + item.UserName)); - ListViewItem value = new ListViewItem { + ListViewItem value = new ListViewItem + { Text = item.SessionId.ToString() }; value.SubItems.Add(connectstateClass.ToString()); value.SubItems.Add(text); value.SubItems.Add(item.ClientName); - form.Invoke((MethodInvoker)delegate { + form.Invoke((MethodInvoker)delegate + { form.SessionListView.Items.Add(value); }); } - form.Invoke((MethodInvoker)delegate { + form.Invoke((MethodInvoker)delegate + { int count = form.SessionListView.Items.Count; form.StatusLabel.Text = count + " Ự"; form.SortListView(); @@ -175,42 +194,50 @@ private static void QuerySessions(object o) { }); } - private void ListSessionsForm_FormClosed(object sender, FormClosedEventArgs e) { + private void ListSessionsForm_FormClosed(object sender, FormClosedEventArgs e) + { _remoteSessions.CloseServer(); } - private void RefreshButton_Click(object sender, EventArgs e) { + private void RefreshButton_Click(object sender, EventArgs e) + { RefreshSessions(); } - private void RefreshSessions() { - lock (_queryLock) { + private void RefreshSessions() + { + lock (_queryLock) + { if (_areQuerying) + { return; - + } _areQuerying = true; } StatusLabel.Text = "ˢ..."; ThreadPool.QueueUserWorkItem(QuerySessions, this); } - private void OnContextMenu(object sender, EventArgs e) { + private void OnContextMenu(object sender, EventArgs e) + { ContextMenu contextMenu = sender as ContextMenu; ListViewItem selection = GetSelection(); - if (selection != null) { + if (selection != null) + { contextMenu.MenuItems.Clear(); Wts.ConnectstateClass connectstateClass; - switch (selection.SubItems[1].Text) { - case "Active": - case "Connected": - connectstateClass = Wts.ConnectstateClass.Connected; - break; - case "Disconnected": - connectstateClass = Wts.ConnectstateClass.Disconnected; - break; - default: - connectstateClass = Wts.ConnectstateClass.ConnectQuery; - break; + switch (selection.SubItems[1].Text) + { + case "Active": + case "Connected": + connectstateClass = Wts.ConnectstateClass.Connected; + break; + case "Disconnected": + connectstateClass = Wts.ConnectstateClass.Disconnected; + break; + default: + connectstateClass = Wts.ConnectstateClass.ConnectQuery; + break; } MenuItem item = new MenuItem("Ͽ(&D)", DisconnectSession) { Enabled = (connectstateClass == Wts.ConnectstateClass.Connected) @@ -223,46 +250,56 @@ private void OnContextMenu(object sender, EventArgs e) { } } - private void DisconnectSession(object sender, EventArgs e) { + private void DisconnectSession(object sender, EventArgs e) + { ListViewItem selection = GetSelection(); - if (int.TryParse(selection.SubItems[0].Text, out var result)) { + if (int.TryParse(selection.SubItems[0].Text, out var result)) + { _remoteSessions.DisconnectSession(result); RefreshSessions(); } } - private void LogOffSession(object sender, EventArgs e) { + private void LogOffSession(object sender, EventArgs e) + { ListViewItem selection = GetSelection(); - if (int.TryParse(selection.SubItems[0].Text, out var result)) { + if (int.TryParse(selection.SubItems[0].Text, out var result)) + { _remoteSessions.LogOffSession(result); RefreshSessions(); } } - private void ListSessionsForm_Resize(object sender, EventArgs e) { + private void ListSessionsForm_Resize(object sender, EventArgs e) + { SessionListView.Width = RefreshButton.Right - SessionListView.Left; } - private void SessionListView_ColumnClick(object sender, ColumnClickEventArgs e) { + private void SessionListView_ColumnClick(object sender, ColumnClickEventArgs e) + { _sortOrder = new int[1]; int num = 0; _sortOrder[num++] = e.Column; SortListView(); } - private void SortListView() { + private void SortListView() + { ArrayList arrayList = new ArrayList(SessionListView.Items.Count); foreach (ListViewItem item in SessionListView.Items) + { arrayList.Add(item); - + } arrayList.Sort(new SessionListSortComparer(_sortOrder)); SessionListView.Items.Clear(); - foreach (ListViewItem item2 in arrayList) + { SessionListView.Items.Add(item2); + } } - private void ListSessionsForm_SizeChanged(object sender, EventArgs e) { + private void ListSessionsForm_SizeChanged(object sender, EventArgs e) + { int num = Math.Max(20, base.ClientRectangle.Width - SessionListView.Location.X * 2); int num2 = Math.Max(20, base.ClientRectangle.Height - SessionListView.Location.Y - 10); SessionListView.Size = new Size(num, num2); diff --git a/RdcMan/ListSetting.cs b/RdcMan/ListSetting.cs index b7ac66e..aba779e 100644 --- a/RdcMan/ListSetting.cs +++ b/RdcMan/ListSetting.cs @@ -2,29 +2,40 @@ using System.Collections.Generic; using System.Xml; -namespace RdcMan { - public class ListSetting : Setting> where T : class { - //private const string XmlNodeName = "item"; +namespace RdcMan +{ + public class ListSetting : Setting> where T : class + { + private const string XmlNodeName = "item"; public ListSetting(object o) - : base(o) { + : base(o) + { if (base.Value == null) + { base.Value = new List(); + } } - public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) { + public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) + { List list = new List(); - foreach (XmlNode childNode in xmlNode.ChildNodes) { - if (childNode.Name != "item") + foreach (XmlNode childNode in xmlNode.ChildNodes) + { + if (childNode.Name != XmlNodeName) + { throw new Exception(); + } list.Add(childNode.InnerText as T); } base.Value = list; } - public override void WriteXml(XmlTextWriter tw, RdcTreeNode node) { - foreach (T item in base.Value) { - tw.WriteElementString("item", item.ToString()); + public override void WriteXml(XmlTextWriter tw, RdcTreeNode node) + { + foreach (T item in base.Value) + { + tw.WriteElementString(XmlNodeName, item.ToString()); } } } diff --git a/RdcMan/LocalResourcesSettings.cs b/RdcMan/LocalResourcesSettings.cs index 724c881..d9dc905 100644 --- a/RdcMan/LocalResourcesSettings.cs +++ b/RdcMan/LocalResourcesSettings.cs @@ -1,11 +1,13 @@ using System.Collections.Generic; using System.Windows.Forms; -namespace RdcMan { - public class LocalResourcesSettings : SettingsGroup { +namespace RdcMan +{ + public class LocalResourcesSettings : SettingsGroup + { //internal const string TabName = "Local Resources"; - private static readonly Dictionary _settingProperties; + private static Dictionary _settingProperties; protected override Dictionary SettingProperties => _settingProperties; @@ -42,17 +44,23 @@ public class LocalResourcesSettings : SettingsGroup { [Setting("redirectPnpDevices")] public BoolSetting RedirectPnpDevices { get; private set; } - static LocalResourcesSettings() { + static LocalResourcesSettings() + { typeof(LocalResourcesSettings).GetSettingProperties(out _settingProperties); } - public LocalResourcesSettings() : base("Դ", "localResources") { } + public LocalResourcesSettings() + : base("Դ", "localResources") + { + } - public override TabPage CreateTabPage(TabbedSettingsDialog dialog) { + public override TabPage CreateTabPage(TabbedSettingsDialog dialog) + { return new LocalResourcesTabPage(dialog, this); } - protected override void Copy(RdcTreeNode node) { + protected override void Copy(RdcTreeNode node) + { Copy(node.LocalResourceSettings); } } diff --git a/RdcMan/LocalResourcesTabPage.cs b/RdcMan/LocalResourcesTabPage.cs index 8344b4b..91918d3 100644 --- a/RdcMan/LocalResourcesTabPage.cs +++ b/RdcMan/LocalResourcesTabPage.cs @@ -4,8 +4,10 @@ using System.Windows.Forms; using MSTSCLib; -namespace RdcMan { - public class LocalResourcesTabPage : SettingsTabPage { +namespace RdcMan +{ + public class LocalResourcesTabPage : SettingsTabPage + { private bool _processingAfterCheck; private TreeNode _redirectDrivesCheckBox; @@ -20,7 +22,9 @@ public class LocalResourcesTabPage : SettingsTabPage { private TreeNode _redirectPnpDevicesCheckBox; - public LocalResourcesTabPage(TabbedSettingsDialog dialog, LocalResourcesSettings settings) : base(dialog, settings) { + public LocalResourcesTabPage(TabbedSettingsDialog dialog, LocalResourcesSettings settings) + : base(dialog, settings) + { int num = 0; int rowIndex = 0; CreateInheritanceControl(ref rowIndex, ref num); @@ -29,25 +33,27 @@ public LocalResourcesTabPage(TabbedSettingsDialog dialog, LocalResourcesSettings FormTools.AddLabeledEnumDropDown(this, "(&Q)", base.Settings.AudioRedirectionQuality, ref rowIndex, ref num, RdpClient.AudioRedirectionQualityToString); FormTools.AddLabeledEnumDropDown(this, "Զ¼(&R)", base.Settings.AudioCaptureRedirectionMode, ref rowIndex, ref num, RdpClient.AudioCaptureRedirectionModeToString); } - FormTools.AddLabeledEnumDropDown(this, "&Windows ϼ", base.Settings.KeyboardHookMode, ref rowIndex, ref num, RdpClient.KeyboardHookModeToString); - Label value = FormTools.NewLabel("ضѡ", 0, rowIndex); + FormTools.AddLabeledEnumDropDown(this, "ϼ(&W)", base.Settings.KeyboardHookMode, ref rowIndex, ref num, RdpClient.KeyboardHookModeToString); + Label value = FormTools.NewLabel("豸ض(&D)", 0, rowIndex); TreeView treeView = new TreeView { Location = FormTools.NewLocation(1, rowIndex), - Size = new Size(340, 190), + Size = new Size(340, 160), CheckBoxes = true, Scrollable = true, ShowLines = false }; treeView.AfterCheck += RedirectView_AfterCheck; - _redirectClipboardCheckBox = treeView.Nodes.Add("Clipboard"); - _redirectPrintersCheckBox = treeView.Nodes.Add("Printers"); - _redirectSmartCardsCheckBox = treeView.Nodes.Add("Smart cards"); - _redirectPortsCheckBox = treeView.Nodes.Add("Ports"); + _redirectClipboardCheckBox = treeView.Nodes.Add(""); + _redirectPrintersCheckBox = treeView.Nodes.Add("ӡ"); + _redirectSmartCardsCheckBox = treeView.Nodes.Add("ܿ"); + _redirectPortsCheckBox = treeView.Nodes.Add("ڶ˿"); _redirectDrivesCheckBox = treeView.Nodes.Add("Drives"); - _redirectPnpDevicesCheckBox = treeView.Nodes.Add("PnP devices"); - if (RdpClient.SupportsFineGrainedRedirection) { + _redirectPnpDevicesCheckBox = treeView.Nodes.Add("PnP豸"); + if (RdpClient.SupportsFineGrainedRedirection) + { IMsRdpDriveCollection driveCollection = RdpClient.DriveCollection; - for (uint num2 = 0u; num2 < driveCollection.DriveCount; num2++) { + for (uint num2 = 0u; num2 < driveCollection.DriveCount; num2++) + { IMsRdpDrive msRdpDrive = driveCollection.get_DriveByIndex(num2); _redirectDrivesCheckBox.Nodes.Add(msRdpDrive.Name.Substring(0, msRdpDrive.Name.Length - 1)); } @@ -56,7 +62,8 @@ public LocalResourcesTabPage(TabbedSettingsDialog dialog, LocalResourcesSettings base.Controls.Add(treeView); } - protected override void UpdateControls() { + protected override void UpdateControls() + { base.UpdateControls(); _redirectDrivesCheckBox.Checked = base.Settings.RedirectDrives.Value; _redirectPortsCheckBox.Checked = base.Settings.RedirectPorts.Value; @@ -74,7 +81,8 @@ protected override void UpdateControls() { } } - protected override void UpdateSettings() { + protected override void UpdateSettings() + { base.UpdateSettings(); base.Settings.RedirectDrives.Value = _redirectDrivesCheckBox.Checked; List list = new List(); @@ -90,14 +98,19 @@ protected override void UpdateSettings() { base.Settings.RedirectPnpDevices.Value = _redirectPnpDevicesCheckBox.Checked; } - private void RedirectView_AfterCheck(object sender, TreeViewEventArgs e) { + private void RedirectView_AfterCheck(object sender, TreeViewEventArgs e) + { if (_processingAfterCheck) + { return; - + } _processingAfterCheck = true; if (e.Node.Nodes.Count == 0 && e.Node.Parent != null) + { e.Node.Parent.Checked = e.Node.Parent.Nodes.Cast().All((TreeNode node) => node.Checked); - else { + } + else + { foreach (TreeNode node in e.Node.Nodes) node.Checked = e.Node.Checked; } diff --git a/RdcMan/Log.cs b/RdcMan/Log.cs index 869a74f..82c4474 100644 --- a/RdcMan/Log.cs +++ b/RdcMan/Log.cs @@ -5,28 +5,35 @@ using System.Reflection; using RdcMan.Configuration; -namespace RdcMan { - public static class Log { +namespace RdcMan +{ + public static class Log + { private static int Indent; private static TextWriter Writer; public static bool Enabled { get; private set; } - public static void Init() { + public static void Init() + { LoggingElement loggingElement = Current.RdcManSection?.Logging; Enabled = loggingElement?.Enabled ?? false; - if (Enabled) { + if (Enabled) + { string text = Environment.ExpandEnvironmentVariables(loggingElement.Path); string format = "RDCMan-{0}.log"; foreach (FileInfo item in (from n in Directory.GetFiles(text, format.InvariantFormat("*"), SearchOption.TopDirectoryOnly) - select new FileInfo(n) into i - orderby i.CreationTime descending - select i).Skip(loggingElement.MaximumNumberOfFiles - 1)) { - try { + select new FileInfo(n) into i + orderby i.CreationTime descending + select i).Skip(loggingElement.MaximumNumberOfFiles - 1)) + { + try + { item.Delete(); } - catch { + catch + { } } string text2 = DateTime.Now.ToString("yyyyMMddHHmm"); @@ -40,40 +47,50 @@ orderby i.CreationTime descending Write("mstscax.dll v{0}".InvariantFormat(RdpClient.RdpControlVersion)); } - public static void Write(string format, params object[] args) { - string value = "{0} {1} {2}".InvariantFormat(DateTime.Now.ToString("s"), new string(' ', Indent * 2), format.InvariantFormat(args)); - if (Enabled) { + public static void Write(string format, params object[] args) + { + if (Enabled) + { + string value = "{0} {1} {2}".InvariantFormat(DateTime.Now.ToString("s"), new string(' ', Indent * 2), format.InvariantFormat(args)); Writer.WriteLine(value); Writer.Flush(); } } - public static void AdjustIndent(int delta) { + public static void AdjustIndent(int delta) + { Indent += delta; } - public static void DumpObject(T o) { + public static void DumpObject(T o) + { HashSet visited = new HashSet(); Type typeFromHandle = typeof(T); Write("Fields of {0}:", typeFromHandle); DumpObject(o, visited); } - private static void DumpObject(T o, HashSet visited) { + private static void DumpObject(T o, HashSet visited) + { Type typeFromHandle = typeof(T); DumpObject(o, typeFromHandle, visited); } - private static void DumpObject(T o, Type type, HashSet visited) { + private static void DumpObject(T o, Type type, HashSet visited) + { AdjustIndent(1); PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - foreach (PropertyInfo propertyInfo in properties) { - if (propertyInfo.GetGetMethod() != null && propertyInfo.Name.IndexOf("password", StringComparison.OrdinalIgnoreCase) == -1) { - try { + foreach (PropertyInfo propertyInfo in properties) + { + if (propertyInfo.GetGetMethod() != null && propertyInfo.Name.IndexOf("password", StringComparison.OrdinalIgnoreCase) == -1) + { + try + { object value = propertyInfo.GetValue(o, null); DumpValue(propertyInfo, value, visited); } - catch (Exception ex) { + catch (Exception ex) + { Write("{0} exception when processing: {1}", propertyInfo.Name, ex.Message); } } @@ -81,20 +98,30 @@ private static void DumpObject(T o, Type type, HashSet visited) { AdjustIndent(-1); } - private static void DumpValue(PropertyInfo prop, object value, HashSet visited) { + private static void DumpValue(PropertyInfo prop, object value, HashSet visited) + { Type propertyType = prop.PropertyType; if (value == null || propertyType.IsPrimitive || propertyType.IsEnum) + { Write("{0} {1} = {2}", propertyType.Name, prop.Name, value ?? "{null}"); + } else if (propertyType.FullName.Equals("System.String")) - Write("{0} {1} = {2}", propertyType.Name, prop.Name, value); + { + Write("{0} {1} = '{2}'", propertyType.Name, prop.Name, value); + } else if (propertyType.IsArray) + { Write("{0} {1}", propertyType.Name, prop.Name); - else if (visited.Add(value)) { + } + else if (visited.Add(value)) + { Write("{0} {1}", propertyType.Name, prop.Name); DumpObject(value, propertyType, visited); } else + { Write("{0} is a recursive reference", prop.Name); + } } } } diff --git a/RdcMan/LogonCredentialsDialogOptions.cs b/RdcMan/LogonCredentialsDialogOptions.cs index e756341..fb03669 100644 --- a/RdcMan/LogonCredentialsDialogOptions.cs +++ b/RdcMan/LogonCredentialsDialogOptions.cs @@ -1,8 +1,10 @@ using System; -namespace RdcMan { +namespace RdcMan +{ [Flags] - public enum LogonCredentialsDialogOptions { + public enum LogonCredentialsDialogOptions + { None = 0, AllowInheritance = 1, ShowProfiles = 2, diff --git a/RdcMan/LogonCredentialsTabPage.cs b/RdcMan/LogonCredentialsTabPage.cs index 892120f..d6e55f8 100644 --- a/RdcMan/LogonCredentialsTabPage.cs +++ b/RdcMan/LogonCredentialsTabPage.cs @@ -1,19 +1,24 @@ -namespace RdcMan { - public class LogonCredentialsTabPage : CredentialsTabPage { +namespace RdcMan +{ + public class LogonCredentialsTabPage : CredentialsTabPage + { public LogonCredentialsTabPage(TabbedSettingsDialog dialog, LogonCredentials settings) : base(dialog, settings) { } - public void CreateControls(LogonCredentialsDialogOptions options) { - int num = 0; + public void CreateControls(LogonCredentialsDialogOptions options) + { + int tabIndex = 0; int rowIndex = 0; - if ((options & LogonCredentialsDialogOptions.AllowInheritance) != 0) { - CreateInheritanceControl(ref rowIndex, ref num); - base.InheritanceControl.EnabledChanged += delegate (bool enabled) { + if ((options & LogonCredentialsDialogOptions.AllowInheritance) != 0) + { + CreateInheritanceControl(ref rowIndex, ref tabIndex); + base.InheritanceControl.EnabledChanged += delegate(bool enabled) + { _credentialsUI.EnableDisableControls(enabled); }; } _credentialsUI = new CredentialsUI(base.InheritanceControl); - _credentialsUI.AddControlsToParent(this, options, ref rowIndex, ref num); + _credentialsUI.AddControlsToParent(this, options, ref rowIndex, ref tabIndex); } } } diff --git a/RdcMan/LogonSettingsDialog.cs b/RdcMan/LogonSettingsDialog.cs index de08859..1404bb0 100644 --- a/RdcMan/LogonSettingsDialog.cs +++ b/RdcMan/LogonSettingsDialog.cs @@ -37,11 +37,11 @@ public static LogonSettingsDialog NewEditCredentialsDialog(CredentialsProfile cr { LogonSettingsDialog logonSettingsDialog = new LogonSettingsDialog("༭ƾ", ""); int rowIndex = 0; - int num = 0; - logonSettingsDialog._logonCredentialsUI.AddControlsToParent(logonSettingsDialog, LogonCredentialsDialogOptions.None, ref rowIndex, ref num); + int tabIndex = 0; + logonSettingsDialog._logonCredentialsUI.AddControlsToParent(logonSettingsDialog, LogonCredentialsDialogOptions.None, ref rowIndex, ref tabIndex); logonSettingsDialog._logonCredentialsUI.EnableDisableControls(enable: true); logonSettingsDialog._logonCredentialsUI.InitFromCredentials(credentials); - logonSettingsDialog.FinalizeLayout(rowIndex, num); + logonSettingsDialog.FinalizeLayout(rowIndex, tabIndex); return logonSettingsDialog; } diff --git a/RdcMan/LongRunningActionForm.cs b/RdcMan/LongRunningActionForm.cs index dbda185..2b567fd 100644 --- a/RdcMan/LongRunningActionForm.cs +++ b/RdcMan/LongRunningActionForm.cs @@ -3,8 +3,10 @@ using System.Threading; using System.Windows.Forms; -namespace RdcMan { - internal class LongRunningActionForm : Form { +namespace RdcMan +{ + internal class LongRunningActionForm : Form + { //private const int PopupDelayInSeconds = 2; //private const int UpdateFrequencyInMilliseconds = 25; @@ -19,16 +21,19 @@ internal class LongRunningActionForm : Form { public static LongRunningActionForm Instance { get; private set; } - private LongRunningActionForm() { + private LongRunningActionForm() + { SuspendLayout(); base.AutoScaleDimensions = new SizeF(96f, 96f); base.AutoScaleMode = AutoScaleMode.Dpi; - ProgressBar progressBar = new ProgressBar { + ProgressBar progressBar = new ProgressBar + { Location = FormTools.NewLocation(0, 0), Size = new Size(450, FormTools.ControlHeight), Style = ProgressBarStyle.Marquee }; - _statusLabel = new Label { + _statusLabel = new Label + { AutoEllipsis = true, Location = FormTools.NewLocation(0, 1), Size = progressBar.Size @@ -44,23 +49,30 @@ private LongRunningActionForm() { this.ScaleAndLayout(); } - public static void PerformOperation(string title, bool showImmediately, Action action) { - LongRunningActionForm form = new LongRunningActionForm { + public static void PerformOperation(string title, bool showImmediately, Action action) + { + LongRunningActionForm form = new LongRunningActionForm + { Text = title }; - try { + try + { Program.TheForm.Enabled = false; form._startTime = DateTime.Now; if (showImmediately) + { form.MakeVisible(); - + } Instance = form; action(); } - finally { - if (form.Visible) { + finally + { + if (form.Visible) + { form.Done = true; - form.Invoke((MethodInvoker)delegate { + form.Invoke((MethodInvoker)delegate + { form.Close(); }); } @@ -69,33 +81,43 @@ public static void PerformOperation(string title, bool showImmediately, Action a } } - public void UpdateStatus(string statusText) { + public void UpdateStatus(string statusText) + { TimeSpan timeSpan = DateTime.Now.Subtract(_startTime); if (!base.Visible && timeSpan.TotalSeconds >= 2.0) + { MakeVisible(); - - if (base.Visible && timeSpan.TotalMilliseconds - _lastUpdateInMilliseconds >= 25.0) { + } + if (base.Visible && timeSpan.TotalMilliseconds - _lastUpdateInMilliseconds >= 25.0) + { _lastUpdateInMilliseconds = timeSpan.TotalMilliseconds; - Invoke((MethodInvoker)delegate { + Invoke((MethodInvoker)delegate + { _statusLabel.Text = statusText; }); } } - private void MakeVisible() { - ThreadPool.QueueUserWorkItem(delegate { + private void MakeVisible() + { + ThreadPool.QueueUserWorkItem(delegate + { Application.Run(new ApplicationContext(this)); }); SpinWait.SpinUntil(() => base.Visible); } - private void ShownHandler(object sender, EventArgs e) { + private void ShownHandler(object sender, EventArgs e) + { BringToFront(); } - private void FormClosingHandler(object sender, FormClosingEventArgs e) { + private void FormClosingHandler(object sender, FormClosingEventArgs e) + { if (!Done && e.CloseReason == CloseReason.UserClosing) + { e.Cancel = true; + } } } } diff --git a/RdcMan/MainForm.cs b/RdcMan/MainForm.cs index ce828c6..ad24a57 100644 --- a/RdcMan/MainForm.cs +++ b/RdcMan/MainForm.cs @@ -6,8 +6,10 @@ using System.Windows.Forms; using Win32; -namespace RdcMan { - internal class MainForm : RdcBaseForm, IMainForm { +namespace RdcMan +{ + internal class MainForm : RdcBaseForm, IMainForm + { private const int MinimumRemoteDesktopPanelHeight = 200; private const int AutoHideIntervalInMilliseconds = 250; @@ -78,22 +80,22 @@ internal class MainForm : RdcBaseForm, IMainForm { public bool IsInternalVersion { get; private set; } - public DockStyle ServerTreeLocation { - get { - return Program.Preferences.ServerTreeLocation; - } - set { + public DockStyle ServerTreeLocation + { + get => Program.Preferences.ServerTreeLocation; + set + { Program.Preferences.ServerTreeLocation = value; _treeSplitter.Dock = value; ServerTree.Instance.Dock = value; } } - public ControlVisibility ServerTreeVisibility { - get { - return Program.Preferences.ServerTreeVisibility; - } - set { + public ControlVisibility ServerTreeVisibility + { + get => Program.Preferences.ServerTreeVisibility; + set + { Program.Preferences.ServerTreeVisibility = value; Size clientSize = GetClientSize(); UpdateServerTreeVisibility(value); @@ -103,115 +105,143 @@ public ControlVisibility ServerTreeVisibility { MenuStrip IMainForm.MainMenuStrip => _menuStrip; - private MainForm() { - Shortcuts = new Dictionary { + private MainForm() + { + Shortcuts = new Dictionary + { { Keys.N | Keys.Control, - delegate { + delegate + { OnFileNew(); } }, { Keys.O | Keys.Control, - delegate { + delegate + { OnFileOpen(); } }, { Keys.S | Keys.Control, - delegate { + delegate + { OnFileSave(); } }, { Keys.A | Keys.Control, - delegate { + delegate + { AddNodeDialogHelper.AddServersDialog(); } }, { Keys.G | Keys.Control, - delegate { + delegate + { AddNodeDialogHelper.AddGroupDialog(); } }, { Keys.F | Keys.Control, - delegate { + delegate + { MenuHelper.FindServers(); } }, { Keys.Q | Keys.Control, - delegate { + delegate + { MenuHelper.ConnectTo(); } } }; - SelectedNodeShortcuts = new Dictionary> { + SelectedNodeShortcuts = new Dictionary> + { { Keys.Delete, - delegate(RdcTreeNode node) { + delegate(RdcTreeNode node) + { ServerTree.Instance.ConfirmRemove(node, askUser: true); } }, { Keys.Delete | Keys.Shift, - delegate(RdcTreeNode node) { + delegate(RdcTreeNode node) + { ServerTree.Instance.ConfirmRemove(node, askUser: false); } }, { Keys.Return, - delegate(RdcTreeNode node) { + delegate(RdcTreeNode node) + { node.Connect(); } }, { Keys.Return | Keys.Shift, - delegate(RdcTreeNode node) { + delegate(RdcTreeNode node) + { bool allConnected; if (node is ServerBase serverBase) + { allConnected = serverBase.IsConnected; + } else + { (node as GroupBase).AnyOrAllConnected(out var _, out allConnected); - + } if (!allConnected) + { node.DoConnectAs(); + } } }, { Keys.Return | Keys.Alt, - delegate(RdcTreeNode node) { + delegate(RdcTreeNode node) + { if (node.HasProperties) + { node.DoPropertiesDialog(); + } } }, { Keys.D | Keys.Control, - delegate(RdcTreeNode node) { + delegate(RdcTreeNode node) + { MenuHelper.AddFavorite(node); } } }; } - public static MainForm Create() { + public static MainForm Create() + { MainForm mainForm2 = (Program.TheForm = new MainForm()); if (mainForm2.Initialize()) + { return mainForm2; - + } return null; } - private bool Initialize() { + private bool Initialize() + { _allowSizeChanged = true; SuspendLayout(); InitComp(); - try { + try + { RdpClient.Initialize(this); } - catch { + catch + { FormTools.ErrorDialog("RDCMan ڳʼڼܵԭע˲ݵ mstscax.dll 汾߸ûעᡣйϸϢİļ"); return false; } @@ -223,43 +253,63 @@ private bool Initialize() { return true; } - public void SetTitle() { + protected override void OnResizeBegin(EventArgs e) + { + _clientPanel.Resizing = true; + } + + protected override void OnResizeEnd(EventArgs e) + { + _clientPanel.Resizing = false; + } + + public void SetTitle() + { TreeNode selectedNode = ServerTree.Instance.SelectedNode; string text = DescriptionText + " v" + VersionText + " - Sysinternals: www.sysinternals.com"; - if (selectedNode != null) { + if (selectedNode != null) + { string qualifiedNameForUI; - if (selectedNode is ServerBase serverBase) { + if (selectedNode is ServerBase serverBase) + { Server serverNode = serverBase.ServerNode; qualifiedNameForUI = serverNode.GetQualifiedNameForUI(); } else + { qualifiedNameForUI = selectedNode.Text; - + } text = qualifiedNameForUI + " - " + text; } Text = text; } - public void RecordLastFocusedServerLabel(ServerLabel label) { + public void RecordLastFocusedServerLabel(ServerLabel label) + { _clientPanel.RecordLastFocusedServerLabel(label); } - public void AddToClientPanel(Control client) { + public void AddToClientPanel(Control client) + { _clientPanel.Controls.Add(client); } - public void RemoveFromClientPanel(Control client) { + public void RemoveFromClientPanel(Control client) + { _clientPanel.Controls.Remove(client); } - public void GoToServerTree() { + public void GoToServerTree() + { Program.TheForm.LeaveFullScreen(); Program.TheForm.EnsureServerTreeVisible(); ServerTree.Instance.Focus(); } - public override void GoFullScreenClient(Server server, bool isTopMostWindow) { - if (!IsFullScreen) { + public override void GoFullScreenClient(Server server, bool isTopMostWindow) + { + if (!IsFullScreen) + { LockWindowSize(isLocked: false); _fullScreenServer = server; RemoveFromClientPanel(server.Client.Control); @@ -271,12 +321,16 @@ public override void GoFullScreenClient(Server server, bool isTopMostWindow) { } } - public override bool SwitchFullScreenClient(Server server) { + public override bool SwitchFullScreenClient(Server server) + { if (!IsFullScreen || !server.IsClientDocked) + { return false; + } if (server == _fullScreenServer) + { return true; - + } RdpClient client = _fullScreenServer.Client; RdpClient client2 = server.Client; _fullScreenServer.SuspendFullScreenBehavior(); @@ -299,13 +353,18 @@ public override bool SwitchFullScreenClient(Server server) { return true; } - public void LeaveFullScreen() { + public void LeaveFullScreen() + { if (_fullScreenServer != null) + { _fullScreenServer.LeaveFullScreen(); + } } - public override void LeaveFullScreenClient(Server server) { - if (IsFullScreen) { + public override void LeaveFullScreenClient(Server server) + { + if (IsFullScreen) + { base.Controls.Clear(); base.Controls.AddRange(_savedControls); _savedControls = null; @@ -316,14 +375,17 @@ public override void LeaveFullScreenClient(Server server) { } } - public void EnsureServerTreeVisible() { + public void EnsureServerTreeVisible() + { UpdateServerTreeVisibility(ControlVisibility.Dock); } - private void InitComp() { + private void InitComp() + { bool lockWindowSize = Program.Preferences.LockWindowSize; Program.Preferences.LockWindowSize = false; - _remoteDesktopPanel = new Panel { + _remoteDesktopPanel = new Panel + { Dock = DockStyle.None }; ServerTree.Instance.HideSelection = false; @@ -334,7 +396,8 @@ private void InitComp() { ServerTree.Instance.LostFocus += AutoHideServerTree; ServerTree.Instance.AfterSelect += ServerTree_AfterSelect; Server.ConnectionStateChanged += Server_ConnectionStateChange; - _treeSplitter = new Splitter { + _treeSplitter = new Splitter + { Dock = DockStyle.Left, Width = 4, MinSize = 10, @@ -348,15 +411,20 @@ private void InitComp() { _autoSaveTimer.Tick += AutoSaveTimerTickHandler; SetMainMenuVisibility(); if (Program.Preferences.ServerTreeWidth > Screen.PrimaryScreen.Bounds.Width) + { ServerTree.Instance.Width = MinimumRemoteDesktopPanelHeight; + } else + { ServerTree.Instance.Width = Program.Preferences.ServerTreeWidth; - + } ServerTreeLocation = Program.Preferences.ServerTreeLocation; ServerTreeVisibility = Program.Preferences.ServerTreeVisibility; - if (!Program.Preferences.WindowPosition.IsEmpty) { + if (!Program.Preferences.WindowPosition.IsEmpty) + { Screen screen = Screen.FromPoint(Program.Preferences.WindowPosition); - if (screen.Bounds.Contains(Program.Preferences.WindowPosition)) { + if (screen.Bounds.Contains(Program.Preferences.WindowPosition)) + { base.StartPosition = FormStartPosition.Manual; base.Location = Program.Preferences.WindowPosition; } @@ -364,8 +432,9 @@ private void InitComp() { base.Controls.Add(_remoteDesktopPanel); base.Size = Program.Preferences.WindowSize; if (Program.Preferences.WindowIsMaximized) + { base.WindowState = FormWindowState.Maximized; - + } Program.Preferences.LockWindowSize = lockWindowSize; LockWindowSize(); Assembly executingAssembly = Assembly.GetExecutingAssembly(); @@ -373,14 +442,16 @@ private void InitComp() { AssemblyName name = executingAssembly.GetName(); VersionText = name.Version.Major + "." + name.Version.Minor; BuildText = name.Version.Build + "." + name.Version.Revision; - if (!WinTrust.VerifyEmbeddedSignature(executingAssembly.Location)) { + if (!WinTrust.VerifyEmbeddedSignature(executingAssembly.Location)) + { BuildText += " FOR INTERNAL MICROSOFT USE ONLY"; IsInternalVersion = true; } object[] customAttributes = executingAssembly.GetCustomAttributes(typeof(AssemblyConfigurationAttribute), inherit: false); if (customAttributes.Length != 0) + { VersionText += (customAttributes[0] as AssemblyConfigurationAttribute).Configuration; - + } customAttributes = executingAssembly.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), inherit: false); DescriptionText = (customAttributes[0] as AssemblyDescriptionAttribute).Description; ServerTree.Instance.Init(executingAssembly); @@ -388,11 +459,16 @@ private void InitComp() { _serverTreeAutoHideTimer.Tick += ServerTreeAutoHideTimerTick; } - private void Server_ConnectionStateChange(ConnectionStateChangedEventArgs args) { } + private void Server_ConnectionStateChange(ConnectionStateChangedEventArgs args) + { + } - private void ServerTree_AfterSelect(object sender, TreeViewEventArgs e) { } + private void ServerTree_AfterSelect(object sender, TreeViewEventArgs e) + { + } - protected override void LayoutContent() { + protected override void LayoutContent() + { int num = base.ClientSize.Width; int num2 = base.ClientSize.Height; int num3 = ((!Program.Preferences.HideMainMenu) ? _menuPanel.Height : 0); @@ -402,52 +478,69 @@ protected override void LayoutContent() { _remoteDesktopPanel.Bounds = new Rectangle(0, num3, num, num2); } - private void AutoSaveTimerTickHandler(object sender, EventArgs e) { - if (!_areShuttingDown) { + private void AutoSaveTimerTickHandler(object sender, EventArgs e) + { + if (!_areShuttingDown) + { RdgFile.AutoSave(); Program.Preferences.Save(); } } - private void ServerTreeAutoHideTimerTick(object sender, EventArgs e) { - if (Program.Preferences.ServerTreeVisibility == ControlVisibility.AutoHide) { - if (!ServerTree.Instance.Visible) { + private void ServerTreeAutoHideTimerTick(object sender, EventArgs e) + { + if (Program.Preferences.ServerTreeVisibility == ControlVisibility.AutoHide) + { + if (!ServerTree.Instance.Visible) + { _serverTreeAutoHideTimer.Stop(); UpdateServerTreeVisibility(ControlVisibility.Dock); return; } Rectangle rectangle = ServerTree.Instance.RectangleToScreen(ServerTree.Instance.ClientRectangle); rectangle.Inflate(48, 48); - if (!rectangle.Contains(Control.MousePosition)) { + if (!rectangle.Contains(Control.MousePosition)) + { _serverTreeAutoHideTimer.Stop(); UpdateServerTreeVisibility(ControlVisibility.Hide); } } else + { _serverTreeAutoHideTimer.Stop(); + } } - private void AutoHideServerTree(object sender, EventArgs e) { - if (Program.Preferences.ServerTreeVisibility != 0 && ServerTree.Instance.Visible) { + private void AutoHideServerTree(object sender, EventArgs e) + { + if (Program.Preferences.ServerTreeVisibility != 0 && ServerTree.Instance.Visible) + { _serverTreeAutoHideTimer.Stop(); UpdateServerTreeVisibility(ControlVisibility.Hide); } } - private void SetAutoShowServerTreeTimer(object sender, EventArgs e) { - if (Program.Preferences.ServerTreeVisibility == ControlVisibility.AutoHide && !ServerTree.Instance.Visible) { + private void SetAutoShowServerTreeTimer(object sender, EventArgs e) + { + if (Program.Preferences.ServerTreeVisibility == ControlVisibility.AutoHide && !ServerTree.Instance.Visible) + { _serverTreeAutoHideTimer.Interval = Program.Preferences.ServerTreeAutoHidePopUpDelay + 1; _serverTreeAutoHideTimer.Start(); } } - private void DisableAutoShowTimer(object sender, EventArgs e) { + private void DisableAutoShowTimer(object sender, EventArgs e) + { if (Program.Preferences.ServerTreeVisibility == ControlVisibility.AutoHide && !ServerTree.Instance.Visible) + { _serverTreeAutoHideTimer.Stop(); + } } - private void SetAutoHideServerTreeTimer(object sender, EventArgs e) { - if (Program.Preferences.ServerTreeVisibility == ControlVisibility.AutoHide && ServerTree.Instance.Visible) { + private void SetAutoHideServerTreeTimer(object sender, EventArgs e) + { + if (Program.Preferences.ServerTreeVisibility == ControlVisibility.AutoHide && ServerTree.Instance.Visible) + { _serverTreeAutoHideTimer.Interval = AutoHideIntervalInMilliseconds; _serverTreeAutoHideTimer.Start(); } @@ -628,14 +721,18 @@ protected void CreateMainMenu() { })); } - protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { - if (!_menuStrip.IsActive) { - if (Shortcuts.TryGetValue(keyData, out var value)) { + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { + if (!_menuStrip.IsActive) + { + if (Shortcuts.TryGetValue(keyData, out var value)) + { value(); return true; } RdcTreeNode selectedNode = GetSelectedNode(); - if (selectedNode != null && SelectedNodeShortcuts.TryGetValue(keyData, out var value2)) { + if (selectedNode != null && SelectedNodeShortcuts.TryGetValue(keyData, out var value2)) + { value2(selectedNode); return true; } @@ -643,21 +740,25 @@ protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { return base.ProcessCmdKey(ref msg, keyData); } - public RdcTreeNode GetSelectedNode() { + public RdcTreeNode GetSelectedNode() + { return _clientPanel.GetSelectedNode(base.ActiveControl) ?? (ServerTree.Instance.SelectedNode as RdcTreeNode); } - public override Size GetClientSize() { + public override Size GetClientSize() + { Size result = new Size(_clientPanel.Width, base.ClientSize.Height); result.Height -= ((!Program.Preferences.HideMainMenu) ? _menuPanel.Height : 0); return result; } - public void ShowGroup(GroupBase group) { + public void ShowGroup(GroupBase group) + { _clientPanel.ShowGroup(group); } - public void HideGroup(GroupBase group) { + public void HideGroup(GroupBase group) + { _clientPanel.HideGroup(group); } @@ -665,25 +766,34 @@ private bool AnyActive() { return ConnectedGroup.Instance.Nodes.Count > 0 && FormTools.YesNoDialog("ڻӡȷ") != DialogResult.Yes; } - private SaveResult DoExit() { + private SaveResult DoExit() + { if (_areShuttingDown) + { return SaveResult.Save; + } if (AnyActive()) + { return SaveResult.Cancel; - - foreach (TreeNode node in ServerTree.Instance.Nodes) { + } + foreach (TreeNode node in ServerTree.Instance.Nodes) + { if (!(node is FileGroup file)) + { continue; - + } SaveResult saveResult = RdgFile.ShouldSaveFile(file); - switch (saveResult) { - case SaveResult.Cancel: - return saveResult; - case SaveResult.NoSave: - continue; + switch (saveResult) + { + case SaveResult.Cancel: + return saveResult; + case SaveResult.NoSave: + continue; } if (RdgFile.DoSaveWithRetry(file) == SaveResult.Cancel) + { return SaveResult.Cancel; + } } _areShuttingDown = true; _serverTreeAutoHideTimer.Stop(); @@ -696,18 +806,27 @@ private SaveResult DoExit() { Program.Preferences.ServerTreeWidth = ServerTree.Instance.Width; Program.Preferences.NeedToSave = true; Program.Preferences.Save(); - Program.PluginAction(delegate (IPlugin p) { + Program.PluginAction(delegate(IPlugin p) + { p.Shutdown(); }); - using (Helpers.Timer("destroying sessions")) { + using (Helpers.Timer("destroying sessions")) + { ServerTree.Instance.SelectedNode = null; - ServerTree.Instance.Operation(OperationBehavior.SuspendSelect | OperationBehavior.SuspendSort | OperationBehavior.SuspendUpdate | OperationBehavior.SuspendGroupChanged, delegate { - ServerTree.Instance.Nodes.VisitNodes(delegate (RdcTreeNode node) { - try { + ServerTree.Instance.Operation(OperationBehavior.SuspendSelect | OperationBehavior.SuspendSort | OperationBehavior.SuspendUpdate | OperationBehavior.SuspendGroupChanged, delegate + { + ServerTree.Instance.Nodes.VisitNodes(delegate(RdcTreeNode node) + { + try + { if (node is Server server) + { server.OnRemoving(); + } + } + catch + { } - catch { } }); ServerTree.Instance.Nodes.Clear(); }); @@ -715,82 +834,106 @@ private SaveResult DoExit() { return SaveResult.Save; } - public override void SetClientSize(Size size) { + public override void SetClientSize(Size size) + { LockWindowSize(isLocked: false); int num = size.Width; int num2 = size.Height; if (ServerTreeVisibility == ControlVisibility.Dock) + { num += ServerTree.Instance.Width + _treeSplitter.Width; + } else if (ServerTreeVisibility == ControlVisibility.AutoHide) + { num += _treeSplitter.Width; - + } num2 += ((!Program.Preferences.HideMainMenu) ? _menuPanel.Height : 0); base.ClientSize = new Size(num, num2); LockWindowSize(); } - public void LockWindowSize() { + public void LockWindowSize() + { LockWindowSize(Program.Preferences.LockWindowSize); } - protected override void OnSizeChanged(EventArgs e) { + protected override void OnSizeChanged(EventArgs e) + { base.OnSizeChanged(e); - if (_allowSizeChanged) { + if (_allowSizeChanged) + { LayoutContent(); Program.Preferences.NeedToSave = true; } } - protected override void OnClosing(CancelEventArgs e) { + protected override void OnClosing(CancelEventArgs e) + { e.Cancel = DoExit() == SaveResult.Cancel; } - private void OnFileNew() { + private void OnFileNew() + { FileGroup fileGroup = RdgFile.NewFile(); - if (fileGroup != null) { + if (fileGroup != null) + { ServerTree.Instance.SelectedNode = fileGroup; Program.Preferences.NeedToSave = true; } } - private void OnFileClose() { + private void OnFileClose() + { FileGroup selectedFile = ServerTree.Instance.GetSelectedFile(); if (selectedFile != null) + { DoFileClose(selectedFile); + } } - public void DoFileClose(FileGroup file) { + public void DoFileClose(FileGroup file) + { RdgFile.CloseFileGroup(file); Program.Preferences.NeedToSave = true; Program.Preferences.Save(); } - private void OnFileOpen() { + private void OnFileOpen() + { FileGroup fileGroup = RdgFile.OpenFile(); - if (fileGroup != null) { + if (fileGroup != null) + { ServerTree.Instance.SelectedNode = fileGroup; Program.Preferences.NeedToSave = true; Program.Preferences.Save(); } } - private void OnFileSave() { + private void OnFileSave() + { FileGroup selectedFile = ServerTree.Instance.GetSelectedFile(); if (selectedFile != null) + { DoFileSave(selectedFile); + } } - public void DoFileSave(FileGroup file) { + public void DoFileSave(FileGroup file) + { RdgFile.SaveFileGroup(file); } - private void OnFileSaveAs() { + private void OnFileSaveAs() + { FileGroup selectedFile = ServerTree.Instance.GetSelectedFile(); if (selectedFile != null) + { RdgFile.SaveAs(selectedFile); + } } - protected override void UpdateMainMenu() { + protected override void UpdateMainMenu() + { UpdateMenuItems(_menuStrip.Items); RdcTreeNode selectedNode = GetSelectedNode(); FileGroup fileGroup = ((selectedNode != null && !(selectedNode is ServerRef)) ? selectedNode.FileGroup : null); @@ -811,7 +954,8 @@ protected override void UpdateMainMenu() { _fileCloseMenuItem.Enabled = true; } _editPropertiesMenuItem.Enabled = selectedNode?.HasProperties ?? false; - if (selectedNode is ServerBase serverBase) { + if (selectedNode is ServerBase serverBase) + { bool isConnected = serverBase.IsConnected; bool isClientFullScreen = serverBase.IsClientFullScreen; _sessionConnectMenuItem.Enabled = !isConnected; @@ -821,8 +965,9 @@ protected override void UpdateMainMenu() { _sessionLogOffMenuItem.Enabled = !Policies.DisableLogOff && isConnected; _sessionSendKeysMenuItem.Enabled = isConnected; if (RdpClient.SupportsRemoteSessionActions) + { _sessionRemoteActionsMenuItem.Enabled = isConnected; - + } _sessionListSessionsMenuItem.Enabled = true; _sessionFullScreenMenuItem.Enabled = isConnected && !isClientFullScreen; _sessionUndockMenuItem.Enabled = serverBase.IsClientDocked && !isClientFullScreen; @@ -832,7 +977,8 @@ protected override void UpdateMainMenu() { _sessionScreenCaptureMenuItem.Enabled = serverNode.ConnectionState == RdpClient.ConnectionState.Connected && serverNode.IsClientDocked && serverNode.Client.Control.Visible; return; } - if (selectedNode is GroupBase groupBase) { + if (selectedNode is GroupBase groupBase) + { groupBase.AnyOrAllConnected(out var anyConnected, out var allConnected); _sessionConnectMenuItem.Enabled = !allConnected; _sessionConnectAsMenuItem.Enabled = !allConnected; @@ -840,7 +986,8 @@ protected override void UpdateMainMenu() { _sessionDisconnectMenuItem.Enabled = anyConnected; _sessionLogOffMenuItem.Enabled = !Policies.DisableLogOff && anyConnected; } - else { + else + { _sessionConnectMenuItem.Enabled = false; _sessionConnectAsMenuItem.Enabled = false; _sessionReconnectMenuItem.Enabled = false; @@ -848,7 +995,8 @@ protected override void UpdateMainMenu() { _sessionLogOffMenuItem.Enabled = false; } _sessionSendKeysMenuItem.Enabled = false; - if (RdpClient.SupportsRemoteSessionActions) { + if (RdpClient.SupportsRemoteSessionActions) + { _sessionRemoteActionsMenuItem.Enabled = false; } _sessionListSessionsMenuItem.Enabled = false; @@ -859,68 +1007,91 @@ protected override void UpdateMainMenu() { _sessionScreenCaptureMenuItem.Enabled = false; } - private void LockWindowSize(bool isLocked) { - if (isLocked) { + private void LockWindowSize(bool isLocked) + { + if (isLocked) + { MinimumSize = base.Size; MaximumSize = base.Size; } - else { + else + { MinimumSize = new Size(400, 300); MaximumSize = new Size(0, 0); } } - private void OnHelpAbout() { + private void OnHelpAbout() + { using About about = new About(IsInternalVersion); about.ShowDialog(); } - public void UpdateAutoSaveTimer() { - if (Program.Preferences.AutoSaveFiles && Program.Preferences.AutoSaveInterval > 0) { + public void UpdateAutoSaveTimer() + { + if (Program.Preferences.AutoSaveFiles && Program.Preferences.AutoSaveInterval > 0) + { _autoSaveTimer.Interval = Program.Preferences.AutoSaveInterval * 60 * 1000; _autoSaveTimer.Start(); } else + { _autoSaveTimer.Stop(); + } } - private void UpdateServerTreeVisibility(ControlVisibility value) { + private void UpdateServerTreeVisibility(ControlVisibility value) + { SuspendLayout(); - if (value == ControlVisibility.Dock) { + if (value == ControlVisibility.Dock) + { ServerTree.Instance.Enabled = true; ServerTree.Instance.Show(); - if (Program.Preferences.ServerTreeVisibility != 0) { + if (Program.Preferences.ServerTreeVisibility != 0) + { ServerTree.Instance.BringToFront(); if (Program.Preferences.ServerTreeLocation == DockStyle.Right) + { _treeSplitter.Hide(); + } } - else { + else + { _treeSplitter.SendToBack(); ServerTree.Instance.SendToBack(); _treeSplitter.Show(); } } - else { + else + { ServerTree.Instance.Hide(); ServerTree.Instance.Enabled = false; if (Program.Preferences.ServerTreeVisibility != ControlVisibility.AutoHide) + { _treeSplitter.Hide(); + } else + { _treeSplitter.Show(); + } } ResumeLayout(); } - private void OnVisibleChanged(object sender, EventArgs e) { + private void OnVisibleChanged(object sender, EventArgs e) + { Program.InitializedEvent.Set(); } - bool IMainForm.RegisterShortcut(Keys shortcutKey, Action action) { - try { + bool IMainForm.RegisterShortcut(Keys shortcutKey, Action action) + { + try + { Shortcuts.Add(shortcutKey, action); return true; } - catch { + catch + { return false; } } diff --git a/RdcMan/MenuExtensions.cs b/RdcMan/MenuExtensions.cs index 7be6d76..f9bc2af 100644 --- a/RdcMan/MenuExtensions.cs +++ b/RdcMan/MenuExtensions.cs @@ -1,12 +1,16 @@ using System.Windows.Forms; -namespace RdcMan { - public static class MenuExtensions { - public static ToolStripMenuItem Add(this ToolStrip menu, string text, MenuNames nameConstant) { +namespace RdcMan +{ + public static class MenuExtensions + { + public static ToolStripMenuItem Add(this ToolStrip menu, string text, MenuNames nameConstant) + { return menu.Items.Add(text, nameConstant); } - public static ToolStripMenuItem Add(this ToolStripItemCollection menuItems, string text, MenuNames nameConstant) { + public static ToolStripMenuItem Add(this ToolStripItemCollection menuItems, string text, MenuNames nameConstant) + { ToolStripMenuItem toolStripMenuItem = new ToolStripMenuItem(text); toolStripMenuItem.Name = nameConstant.ToString(); menuItems.Add(toolStripMenuItem); diff --git a/RdcMan/MenuHelper.cs b/RdcMan/MenuHelper.cs index 433080c..f14ce11 100644 --- a/RdcMan/MenuHelper.cs +++ b/RdcMan/MenuHelper.cs @@ -4,9 +4,12 @@ using System.Windows.Forms; using MSTSCLib; -namespace RdcMan { - public static class MenuHelper { - public static void AddSessionMenuItems(ContextMenuStrip menu, ServerBase server) { +namespace RdcMan +{ + public static class MenuHelper + { + public static void AddSessionMenuItems(ContextMenuStrip menu, ServerBase server) + { bool isConnected = server.IsConnected; ToolStripMenuItem toolStripMenuItem = new DelegateMenuItem("(&C)", MenuNames.SessionConnect, server.Connect); toolStripMenuItem.Enabled = !isConnected; @@ -14,7 +17,7 @@ public static void AddSessionMenuItems(ContextMenuStrip menu, ServerBase server) toolStripMenuItem = new DelegateMenuItem("Ϊ(&A)...", MenuNames.SessionConnectAs, server.DoConnectAs); toolStripMenuItem.Enabled = !isConnected; menu.Items.Add(toolStripMenuItem); - toolStripMenuItem = new DelegateMenuItem("(&R)", MenuNames.SessionReconnect, server.Reconnect); + toolStripMenuItem = new DelegateMenuItem("(&C)", MenuNames.SessionReconnect, server.Reconnect); toolStripMenuItem.Enabled = isConnected; menu.Items.Add(toolStripMenuItem); menu.Items.Add("-"); @@ -39,7 +42,8 @@ public static void AddSessionMenuItems(ContextMenuStrip menu, ServerBase server) })); } - public static void AddSendKeysMenuItems(ToolStripMenuItem parentItem, Func getServer) { + public static void AddSendKeysMenuItems(ToolStripMenuItem parentItem, Func getServer) + { List list = new List(new SendKeysMenuItem[4] { new SendKeysMenuItem("ȫԻ", new Keys[3] { Keys.ControlKey, @@ -60,41 +64,53 @@ public static void AddSendKeysMenuItems(ToolStripMenuItem parentItem, Func getServer) { - List list = new List(new ToolStripMenuItem[5] { - new ToolStripMenuItem("App commands") { + public static void AddRemoteActionsMenuItems(ToolStripMenuItem parentItem, Func getServer) + { + List list = new List(new ToolStripMenuItem[5] + { + new ToolStripMenuItem("App commands") + { Tag = RemoteSessionActionType.RemoteSessionActionAppbar }, - new ToolStripMenuItem("Charms") { + new ToolStripMenuItem("Charms") + { Tag = RemoteSessionActionType.RemoteSessionActionCharms }, - new ToolStripMenuItem("Snap") { + new ToolStripMenuItem("Snap") + { Tag = RemoteSessionActionType.RemoteSessionActionSnap }, - new ToolStripMenuItem("Switch apps") { + new ToolStripMenuItem("Switch apps") + { Tag = RemoteSessionActionType.RemoteSessionActionAppSwitch }, - new ToolStripMenuItem("Start") { + new ToolStripMenuItem("Start") + { Tag = RemoteSessionActionType.RemoteSessionActionStartScreen } }); - foreach (ToolStripMenuItem item in list) { - item.Click += delegate (object sender, EventArgs e) { + foreach (ToolStripMenuItem item in list) + { + item.Click += delegate(object sender, EventArgs e) + { getServer().ServerNode.SendRemoteAction((RemoteSessionActionType)(sender as ToolStripMenuItem).Tag); }; parentItem.DropDownItems.Add(item); } } - public static void AddDockingMenuItems(ContextMenuStrip menu, ServerBase server) { + public static void AddDockingMenuItems(ContextMenuStrip menu, ServerBase server) + { bool isConnected = server.IsConnected; bool isClientFullScreen = server.IsClientFullScreen; ToolStripMenuItem toolStripMenuItem = new DelegateMenuItem("ȫ(&F)", MenuNames.SessionFullScreen, delegate { @@ -117,7 +133,8 @@ public static void AddDockingMenuItems(ContextMenuStrip menu, ServerBase server) menu.Items.Add(toolStripMenuItem); } - public static void AddMaintenanceMenuItems(ContextMenuStrip menu, ServerBase server) { + public static void AddMaintenanceMenuItems(ContextMenuStrip menu, ServerBase server) + { ToolStripMenuItem toolStripMenuItem = new DelegateMenuItem("ɾ(&V)", MenuNames.EditRemove, delegate { ServerTree.Instance.ConfirmRemove(server, askUser: true); }); @@ -137,32 +154,43 @@ public static void AddMaintenanceMenuItems(ContextMenuStrip menu, ServerBase ser menu.Items.Add(toolStripMenuItem); } - public static void ConnectTo() { + public static void ConnectTo() + { using ConnectToDialog connectToDialog = ConnectToDialog.NewConnectToDialog(Program.TheForm); - if (connectToDialog.ShowDialog() == DialogResult.OK) { + if (connectToDialog.ShowDialog() == DialogResult.OK) + { Server server = TemporaryServer.Create(connectToDialog); server.Connect(); ServerTree.Instance.SelectedNode = server; } } - public static void FindServers() { + public static void FindServers() + { using FindServersDialog findServersDialog = new FindServersDialog(); - if (findServersDialog.ShowDialog() == DialogResult.OK) { + if (findServersDialog.ShowDialog() == DialogResult.OK) + { ServerBase serverBase = findServersDialog.SelectedServers.FirstOrDefault(); if (serverBase != null) + { ServerTree.Instance.SelectedNode = serverBase; + } } } - public static void AddFavorite(RdcTreeNode node) { + public static void AddFavorite(RdcTreeNode node) + { if (node is ServerBase serverBase) + { FavoritesGroup.Instance.AddReference(serverBase); + } } - public static void ShowGlobalOptionsDialog() { + public static void ShowGlobalOptionsDialog() + { using GlobalOptionsDialog globalOptionsDialog = GlobalOptionsDialog.New(); - if (globalOptionsDialog.ShowDialog() == DialogResult.OK) { + if (globalOptionsDialog.ShowDialog() == DialogResult.OK) + { globalOptionsDialog.UpdatePreferences(); Program.Preferences.NeedToSave = true; Program.Preferences.Save(); diff --git a/RdcMan/MenuNames.cs b/RdcMan/MenuNames.cs index 91aa1d8..79984ce 100644 --- a/RdcMan/MenuNames.cs +++ b/RdcMan/MenuNames.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public enum MenuNames { +namespace RdcMan +{ + public enum MenuNames + { None, File, FileNew, diff --git a/RdcMan/NodeHelper.cs b/RdcMan/NodeHelper.cs index eeeb25c..ee412c0 100644 --- a/RdcMan/NodeHelper.cs +++ b/RdcMan/NodeHelper.cs @@ -6,166 +6,222 @@ using System.Windows.Forms; using Win32; -namespace RdcMan { - internal static class NodeHelper { +namespace RdcMan +{ + internal static class NodeHelper + { private const int ThrottledConnectDelayInMilliseconds = 125; private const int ThrottledDisconnectDelayInMilliseconds = 25; - public static TreeNodeCollection GetParentNodes(this TreeNode node) { + public static TreeNodeCollection GetParentNodes(this TreeNode node) + { TreeNode parent = node.Parent; return parent != null ? parent.Nodes : node.TreeView.Nodes; } - public static void VisitNodes(this RdcTreeNode node, Action callback) { + public static void VisitNodes(this RdcTreeNode node, Action callback) + { callback(node); node.Nodes.VisitNodes(callback); } - public static void VisitNodes(this ICollection nodes, Action callback) { - foreach (RdcTreeNode node in nodes) { + public static void VisitNodes(this ICollection nodes, Action callback) + { + foreach (RdcTreeNode node in nodes) + { node.VisitNodes(callback); } } - public static bool VisitNodes(this RdcTreeNode node, Func callback) { - return callback(node) switch { - NodeVisitorResult.NoRecurse => true, - NodeVisitorResult.Break => false, - _ => node.Nodes.VisitNodes(callback), + public static bool VisitNodes(this RdcTreeNode node, Func callback) + { + return callback(node) switch + { + NodeVisitorResult.NoRecurse => true, + NodeVisitorResult.Break => false, + _ => node.Nodes.VisitNodes(callback), }; } - public static bool VisitNodes(this ICollection nodes, Func callback) { - foreach (RdcTreeNode node in nodes) { + public static bool VisitNodes(this ICollection nodes, Func callback) + { + foreach (RdcTreeNode node in nodes) + { if (!node.VisitNodes(callback)) + { return false; + } } return true; } - public static void VisitNodeAndParents(this RdcTreeNode node, Action callback) { + public static void VisitNodeAndParents(this RdcTreeNode node, Action callback) + { callback(node); node.VisitParents(callback); } - public static void VisitParents(this RdcTreeNode node, Action callback) { - for (RdcTreeNode rdcTreeNode = node.Parent as RdcTreeNode; rdcTreeNode != null; rdcTreeNode = rdcTreeNode.Parent as RdcTreeNode) { + public static void VisitParents(this RdcTreeNode node, Action callback) + { + for (RdcTreeNode rdcTreeNode = node.Parent as RdcTreeNode; rdcTreeNode != null; rdcTreeNode = rdcTreeNode.Parent as RdcTreeNode) + { callback(rdcTreeNode); } } - public static void VisitNodeAndParents(this RdcTreeNode node, Func callback) { + public static void VisitNodeAndParents(this RdcTreeNode node, Func callback) + { if (callback(node) == NodeVisitorResult.Continue) + { node.VisitParents(callback); + } } - public static void VisitParents(this RdcTreeNode node, Func callback) { + public static void VisitParents(this RdcTreeNode node, Func callback) + { RdcTreeNode rdcTreeNode = node.Parent as RdcTreeNode; - while (rdcTreeNode != null && callback(rdcTreeNode) == NodeVisitorResult.Continue) { + while (rdcTreeNode != null && callback(rdcTreeNode) == NodeVisitorResult.Continue) + { rdcTreeNode = rdcTreeNode.Parent as RdcTreeNode; } } - public static List GetAllChildren(this RdcTreeNode parent, Predicate predicate) where TNode : RdcTreeNode { + public static List GetAllChildren(this RdcTreeNode parent, Predicate predicate) where TNode : RdcTreeNode + { List children = new List(parent.Nodes.Count); - parent.VisitNodes(delegate (RdcTreeNode child) { + parent.VisitNodes(delegate(RdcTreeNode child) + { if (child is TNode val && predicate(val)) + { children.Add(val); + } }); return children; } - public static void AnyOrAllConnected(IEnumerable servers, out bool anyConnected, out bool allConnected) { + public static void AnyOrAllConnected(IEnumerable servers, out bool anyConnected, out bool allConnected) + { anyConnected = false; allConnected = true; - foreach (ServerBase server in servers) { + foreach (ServerBase server in servers) + { if (server.IsConnected) + { anyConnected = true; + } else + { allConnected = false; + } } } - public static void SelectNewActiveConnection(bool selectPrevious) { + public static void SelectNewActiveConnection(bool selectPrevious) + { List connectedServers = new List(); - ConnectedGroup.Instance.Nodes.VisitNodes(delegate (RdcTreeNode node) { + ConnectedGroup.Instance.Nodes.VisitNodes(delegate(RdcTreeNode node) + { connectedServers.Add(node as ServerBase); }); connectedServers.Sort((ServerBase a, ServerBase b) => (b as ConnectedServerRef).LastFocusTime.CompareTo((a as ConnectedServerRef).LastFocusTime)); ServerBase serverBase = null; if (selectPrevious) + { serverBase = connectedServers[Math.Min(1, connectedServers.Count - 1)]; - else { + } + else + { using SelectActiveServerForm selectActiveServerForm = new SelectActiveServerForm(connectedServers); - if (selectActiveServerForm.ShowDialog() == DialogResult.OK) { + if (selectActiveServerForm.ShowDialog() == DialogResult.OK) + { SelectActiveServerForm.SelectedObject selected = selectActiveServerForm.Selected; - switch (selected.Operation) { - case SelectActiveServerForm.Operation.MinimizeWindow: { - IntPtr window = User.GetWindow(Program.TheForm.Handle, 2u); - User.SetForegroundWindow(window); - Program.TheForm.WindowState = FormWindowState.Minimized; - break; - } - case SelectActiveServerForm.Operation.SelectServer: - serverBase = selected.Server; - break; - case SelectActiveServerForm.Operation.SelectTree: - Program.TheForm.GoToServerTree(); - break; + switch (selected.Operation) + { + case SelectActiveServerForm.Operation.MinimizeWindow: + { + IntPtr window = User.GetWindow(Program.TheForm.Handle, 2u); + User.SetForegroundWindow(window); + Program.TheForm.WindowState = FormWindowState.Minimized; + break; + } + case SelectActiveServerForm.Operation.SelectServer: + serverBase = selected.Server; + break; + case SelectActiveServerForm.Operation.SelectTree: + Program.TheForm.GoToServerTree(); + break; } } } - if (serverBase != null) { + if (serverBase != null) + { Program.TheForm.SwitchFullScreenClient(serverBase.ServerNode); ServerTree.Instance.SelectedNode = serverBase; serverBase.Focus(); } } - public static void ThrottledConnect(IEnumerable servers) { + public static void ThrottledConnect(IEnumerable servers) + { ThrottledConnectAs(servers, null, null); } - public static void ThrottledConnect(IEnumerable servers, Action postConnectAction) { + public static void ThrottledConnect(IEnumerable servers, Action postConnectAction) + { ThrottledConnectAs(servers, null, null, postConnectAction); } - public static void ThrottledConnectAs(IEnumerable servers, LogonCredentials logonCredentials, ConnectionSettings connectionSettings) { - ThrottledConnectAs(servers, logonCredentials, connectionSettings, delegate { + public static void ThrottledConnectAs(IEnumerable servers, LogonCredentials logonCredentials, ConnectionSettings connectionSettings) + { + ThrottledConnectAs(servers, logonCredentials, connectionSettings, delegate + { }); } - public static void ThrottledConnectAs(IEnumerable servers, LogonCredentials logonCredentials, ConnectionSettings connectionSettings, Action postConnectAction) { - ThrottledOperation(servers, new RdpClient.ConnectionState[2] { + public static void ThrottledConnectAs(IEnumerable servers, LogonCredentials logonCredentials, ConnectionSettings connectionSettings, Action postConnectAction) + { + ThrottledOperation(servers, new RdpClient.ConnectionState[2] + { RdpClient.ConnectionState.Connected, RdpClient.ConnectionState.Disconnected - }, delegate (ServerBase server) { + }, delegate(ServerBase server) + { server.ConnectAs(logonCredentials, connectionSettings); postConnectAction(server); }, ThrottledConnectDelayInMilliseconds); } - public static void ThrottledDisconnect(IEnumerable servers) { - ThrottledOperation(servers, new RdpClient.ConnectionState[1], delegate (ServerBase server) { + public static void ThrottledDisconnect(IEnumerable servers) + { + ThrottledOperation(servers, new RdpClient.ConnectionState[1], delegate(ServerBase server) + { server.Disconnect(); }, ThrottledDisconnectDelayInMilliseconds); } - private static void ThrottledOperation(IEnumerable servers, IEnumerable completionStates, Action operation, int delayInMilliseconds) { + private static void ThrottledOperation(IEnumerable servers, IEnumerable completionStates, Action operation, int delayInMilliseconds) + { List serversList = servers.ToList(); if (serversList.Count == 0) + { return; - - ThreadPool.QueueUserWorkItem(delegate { - using ThrottledOperation throttledOperation = new ThrottledOperation(serversList, completionStates, delegate { + } + ThreadPool.QueueUserWorkItem(delegate + { + using ThrottledOperation throttledOperation = new ThrottledOperation(serversList, completionStates, delegate + { ServerTree.Instance.SuspendSort(); - }, delegate (ServerBase server) { - Program.TheForm.Invoke((MethodInvoker)delegate { + }, delegate(ServerBase server) + { + Program.TheForm.Invoke((MethodInvoker)delegate + { operation(server); }); - }, delayInMilliseconds, delegate { - Program.TheForm.Invoke((MethodInvoker)delegate { + }, delayInMilliseconds, delegate + { + Program.TheForm.Invoke((MethodInvoker)delegate + { ServerTree.Instance.ResumeSort(); ServerTree.Instance.SortAllNodes(); }); diff --git a/RdcMan/NodePropertiesDialog.cs b/RdcMan/NodePropertiesDialog.cs index edaad2e..0036237 100644 --- a/RdcMan/NodePropertiesDialog.cs +++ b/RdcMan/NodePropertiesDialog.cs @@ -1,36 +1,45 @@ using System.Linq; using System.Windows.Forms; -namespace RdcMan { - public abstract class NodePropertiesDialog : TabbedSettingsDialog { +namespace RdcMan +{ + public abstract class NodePropertiesDialog : TabbedSettingsDialog + { public RdcTreeNode AssociatedNode { get; private set; } public INodePropertiesPage PropertiesPage { get; protected set; } - public override void InitButtons() { + public override void InitButtons() + { base.InitButtons(); if (AssociatedNode != null) + { _acceptButton.Enabled = AssociatedNode.AllowEdit(popUI: true); + } } protected NodePropertiesDialog(RdcTreeNode associatedNode, string dialogTitle, string acceptButtonText, Form parentForm) - : base(dialogTitle, acceptButtonText, parentForm) { + : base(dialogTitle, acceptButtonText, parentForm) + { AssociatedNode = associatedNode; } - public virtual void CreateControls(RdcTreeNode settings) { + public virtual void CreateControls(RdcTreeNode settings) + { LogonCredentialsTabPage logonCredentialsTabPage = (LogonCredentialsTabPage)settings.LogonCredentials.CreateTabPage(this); LogonCredentialsDialogOptions logonCredentialsDialogOptions = LogonCredentialsDialogOptions.ShowProfiles; if (settings.LogonCredentials.InheritSettingsType.Mode != InheritanceMode.Disabled) + { logonCredentialsDialogOptions |= LogonCredentialsDialogOptions.AllowInheritance; - + } logonCredentialsTabPage.CreateControls(logonCredentialsDialogOptions); AddTabPage(logonCredentialsTabPage); GatewaySettingsTabPage gatewaySettingsTabPage = (GatewaySettingsTabPage)settings.GatewaySettings.CreateTabPage(this); logonCredentialsDialogOptions = LogonCredentialsDialogOptions.ShowProfiles; if (settings.GatewaySettings.InheritSettingsType.Mode != InheritanceMode.Disabled) + { logonCredentialsDialogOptions |= LogonCredentialsDialogOptions.AllowInheritance; - + } gatewaySettingsTabPage.CreateControls(logonCredentialsDialogOptions); AddTabPage(gatewaySettingsTabPage); AddTabPage(settings.ConnectionSettings.CreateTabPage(this)); @@ -44,9 +53,11 @@ public virtual void CreateControls(RdcTreeNode settings) { settings.ResolveCredentials(); } - protected void PopulateCredentialsProfiles(GroupBase group) { + protected void PopulateCredentialsProfiles(GroupBase group) + { FileGroup file = group?.FileGroup; - foreach (ICredentialsTabPage item in base.TabPages.OfType()) { + foreach (ICredentialsTabPage item in base.TabPages.OfType()) + { item.PopulateCredentialsProfiles(file); } } diff --git a/RdcMan/NodePropertiesPage.cs b/RdcMan/NodePropertiesPage.cs index 348a507..849d195 100644 --- a/RdcMan/NodePropertiesPage.cs +++ b/RdcMan/NodePropertiesPage.cs @@ -1,57 +1,74 @@ using System; using System.Windows.Forms; -namespace RdcMan { - public abstract class NodePropertiesPage : SettingsTabPage, INodePropertiesPage where TSettingsGroup : SettingsGroup { +namespace RdcMan +{ + public abstract class NodePropertiesPage : SettingsTabPage, INodePropertiesPage where TSettingsGroup : SettingsGroup + { protected ValueComboBox _parentComboBox; - public GroupBase ParentGroup { - get { - return _parentComboBox == null || !_parentComboBox.Enabled ? null : _parentComboBox.SelectedValue; - } + public GroupBase ParentGroup + { + get => _parentComboBox == null || !_parentComboBox.Enabled ? null : _parentComboBox.SelectedValue; } public event Action ParentGroupChanged; protected NodePropertiesPage(TabbedSettingsDialog dialog, TSettingsGroup settings, string name) - : base(dialog, settings, name) { } + : base(dialog, settings, name) + { + } - public bool PopulateParentDropDown(GroupBase excludeGroup, GroupBase defaultParent) { + public bool PopulateParentDropDown(GroupBase excludeGroup, GroupBase defaultParent) + { PopulateParentDropDown(excludeGroup); if (defaultParent != null && CanBeParent(defaultParent)) + { _parentComboBox.SelectedValue = defaultParent; - else { + } + else + { if (_parentComboBox.ItemCount == 0) + { return false; - + } _parentComboBox.SelectedIndex = 0; } return true; } - public void SetParentDropDown(GroupBase group) { + public void SetParentDropDown(GroupBase group) + { _parentComboBox.AddItem(group.FullPath, group); _parentComboBox.SelectedIndex = 0; } protected abstract bool CanBeParent(GroupBase group); - private void PopulateParentDropDown(GroupBase excludeGroup) { - ServerTree.Instance.Nodes.VisitNodes(delegate (RdcTreeNode node) { + private void PopulateParentDropDown(GroupBase excludeGroup) + { + ServerTree.Instance.Nodes.VisitNodes(delegate(RdcTreeNode node) + { if (node == excludeGroup) + { return NodeVisitorResult.NoRecurse; + } if (node is GroupBase groupBase && CanBeParent(groupBase)) + { _parentComboBox.AddItem(groupBase.FullPath, groupBase); + } return NodeVisitorResult.Continue; }); } - protected void AddParentCombo(ref int rowIndex, ref int tabIndex) { + protected void AddParentCombo(ref int rowIndex, ref int tabIndex) + { _parentComboBox = FormTools.AddLabeledValueDropDown(this, "(&P)", ref rowIndex, ref tabIndex, null, null); _parentComboBox.SelectedIndexChanged += ParentGroupChangedHandler; } - protected RdcTextBox AddComment(ref int rowIndex, ref int tabIndex) { + protected RdcTextBox AddComment(ref int rowIndex, ref int tabIndex) + { Label label = FormTools.NewLabel("ע(&C)", 0, rowIndex); RdcTextBox rdcTextBox = FormTools.NewTextBox(1, rowIndex++, tabIndex++, 7); rdcTextBox.Enabled = true; @@ -60,7 +77,8 @@ protected RdcTextBox AddComment(ref int rowIndex, ref int tabIndex) { return rdcTextBox; } - protected virtual void ParentGroupChangedHandler(object sender, EventArgs e) { + protected virtual void ParentGroupChangedHandler(object sender, EventArgs e) + { GroupBase selectedValue = _parentComboBox.SelectedValue; this.ParentGroupChanged(selectedValue); } diff --git a/RdcMan/NodeVisitorResult.cs b/RdcMan/NodeVisitorResult.cs index 4528ef7..a128c7b 100644 --- a/RdcMan/NodeVisitorResult.cs +++ b/RdcMan/NodeVisitorResult.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public enum NodeVisitorResult { +namespace RdcMan +{ + public enum NodeVisitorResult + { Continue, NoRecurse, Break diff --git a/RdcMan/NumericTextBox.cs b/RdcMan/NumericTextBox.cs index 398ae62..2dde0bf 100644 --- a/RdcMan/NumericTextBox.cs +++ b/RdcMan/NumericTextBox.cs @@ -1,8 +1,10 @@ using System; using System.Windows.Forms; -namespace RdcMan { - public class NumericTextBox : TextBox, ISettingControl { +namespace RdcMan +{ + public class NumericTextBox : TextBox, ISettingControl + { private readonly int _min; private readonly int _max; @@ -11,56 +13,80 @@ public class NumericTextBox : TextBox, ISettingControl { public IntSetting Setting { get; set; } - public NumericTextBox(int min, int max, string invalidMessage) { + public NumericTextBox(int min, int max, string invalidMessage) + { if (min < 0) + { throw new ArgumentOutOfRangeException("min"); + } if (max < 0) + { throw new ArgumentOutOfRangeException("max"); + } if (min >= max) + { throw new ArgumentException("Minimum must be less than maximum"); + } if (string.IsNullOrWhiteSpace(invalidMessage)) + { throw new ArgumentOutOfRangeException("invalidMessage"); + } _min = min; _max = max; _invalidMessage = invalidMessage; } - void ISettingControl.UpdateControl() { + void ISettingControl.UpdateControl() + { if (Setting != null) + { Text = Setting.Value.ToString(); + } } - void ISettingControl.UpdateSetting() { + void ISettingControl.UpdateSetting() + { if (Setting != null) + { Setting.Value = int.Parse(Text); + } } - string ISettingControl.Validate() { + string ISettingControl.Validate() + { string result = null; int num = int.Parse(Text); if (num < _min || num > _max) + { result = _invalidMessage; + } return result; } - protected override bool ProcessCmdKey(ref Message m, Keys keyData) { + protected override bool ProcessCmdKey(ref Message m, Keys keyData) + { if ((keyData & Keys.Modifiers) == 0 && ((uint)(keyData - 48) <= 9u || (uint)(keyData - 96) <= 9u)) + { return base.ProcessCmdKey(ref m, keyData); + } if ((keyData & (Keys.Control | Keys.Alt)) != 0) + { + return base.ProcessCmdKey(ref m, keyData); + } + switch (keyData & Keys.KeyCode) + { + case Keys.Back: + case Keys.Tab: + case Keys.Return: + case Keys.Escape: + case Keys.End: + case Keys.Home: + case Keys.Left: + case Keys.Right: + case Keys.Delete: return base.ProcessCmdKey(ref m, keyData); - switch (keyData & Keys.KeyCode) { - case Keys.Back: - case Keys.Tab: - case Keys.Return: - case Keys.Escape: - case Keys.End: - case Keys.Home: - case Keys.Left: - case Keys.Right: - case Keys.Delete: - return base.ProcessCmdKey(ref m, keyData); - default: - return true; + default: + return true; } } } diff --git a/RdcMan/OperationBehavior.cs b/RdcMan/OperationBehavior.cs index 2f07d90..daf339a 100644 --- a/RdcMan/OperationBehavior.cs +++ b/RdcMan/OperationBehavior.cs @@ -1,8 +1,10 @@ using System; -namespace RdcMan { +namespace RdcMan +{ [Flags] - internal enum OperationBehavior { + internal enum OperationBehavior + { None = 0, SuspendSelect = 1, SuspendSort = 2, diff --git a/RdcMan/PasswordSetting.cs b/RdcMan/PasswordSetting.cs index ffb67ff..4f454af 100644 --- a/RdcMan/PasswordSetting.cs +++ b/RdcMan/PasswordSetting.cs @@ -1,46 +1,66 @@ using System.Xml; -namespace RdcMan { - public class PasswordSetting : BaseSetting, IDeferDecryption { - +namespace RdcMan +{ + public class PasswordSetting : BaseSetting, IDeferDecryption + { + //private const string StoreAsClearTextAttribute = "storeAsClearText"; + public bool IsDecrypted { get; set; } public PasswordSetting(object o) - : base(o) { } + : base(o) + { + } - public void SetPlainText(string value) { + public void SetPlainText(string value) + { Value = value; IsDecrypted = true; } - public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) { + public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) + { XmlNode firstChild = xmlNode.FirstChild; if (firstChild == null) + { Value = string.Empty; + } else + { Value = firstChild.InnerText; - - try { + } + try + { XmlNode xmlNode2 = xmlNode.Attributes["storeAsClearText"]; if (xmlNode2 != null && bool.Parse(xmlNode2.InnerText)) + { node.Password.IsDecrypted = true; + } else if (xmlNode.ParentNode.Name != "credentialsProfile") + { Encryption.DeferDecryption(this, node, xmlNode.GetFullPath()); + } + } + catch + { } - catch { } } - public override void WriteXml(XmlTextWriter tw, RdcTreeNode node) { + public override void WriteXml(XmlTextWriter tw, RdcTreeNode node) + { string text = (IsDecrypted ? Encryption.EncryptString(Value, node.EncryptionSettings) : Value); tw.WriteString(text); } - public override void Copy(ISetting source) { + public override void Copy(ISetting source) + { base.Copy(source); IsDecrypted = ((PasswordSetting)source).IsDecrypted; } - public void Decrypt(EncryptionSettings settings) { + public void Decrypt(EncryptionSettings settings) + { Value = Encryption.DecryptString(Value, settings); IsDecrypted = true; } diff --git a/RdcMan/PluginContext.cs b/RdcMan/PluginContext.cs index fcb1be7..950ad21 100644 --- a/RdcMan/PluginContext.cs +++ b/RdcMan/PluginContext.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - internal class PluginContext : IPluginContext { +namespace RdcMan +{ + internal class PluginContext : IPluginContext + { IMainForm IPluginContext.MainForm => Program.TheForm; IServerTree IPluginContext.Tree => ServerTree.Instance; diff --git a/RdcMan/PointHelper.cs b/RdcMan/PointHelper.cs index 6c27bc7..2472422 100644 --- a/RdcMan/PointHelper.cs +++ b/RdcMan/PointHelper.cs @@ -1,19 +1,24 @@ using System; using System.Drawing; -namespace RdcMan { - public static class PointHelper { +namespace RdcMan +{ + public static class PointHelper + { public static readonly string Separator = ", "; - public static Point Parse(string s) { + public static Point Parse(string s) + { string[] array = s.Split(new string[1] { Separator }, StringSplitOptions.None); if (array.Length != 2) - throw new InvalidOperationException("Bad Point string {0}".InvariantFormat(s)); - + { + throw new InvalidOperationException("Bad Point string '{0}'".InvariantFormat(s)); + } return new Point(int.Parse(array[0]), int.Parse(array[1])); } - public static string ToFormattedString(this Point point) { + public static string ToFormattedString(this Point point) + { return "{0}{1}{2}".InvariantFormat(point.X, Separator, point.Y); } } diff --git a/RdcMan/PointSetting.cs b/RdcMan/PointSetting.cs index 98c6f58..d63286c 100644 --- a/RdcMan/PointSetting.cs +++ b/RdcMan/PointSetting.cs @@ -1,20 +1,24 @@ using System.Drawing; using System.Xml; -namespace RdcMan { - public class PointSetting : Setting { - public PointSetting(object o) - : base(o) { } +namespace RdcMan +{ + public class PointSetting : Setting + { + public PointSetting(object o) : base(o) { } - public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) { + public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) + { base.Value = PointHelper.Parse(xmlNode.FirstChild.InnerText); } - public override void WriteXml(XmlTextWriter tw, RdcTreeNode node) { + public override void WriteXml(XmlTextWriter tw, RdcTreeNode node) + { tw.WriteString(base.Value.ToFormattedString()); } - public override string ToString() { + public override string ToString() + { return base.Value.ToFormattedString(); } } diff --git a/RdcMan/Policies.cs b/RdcMan/Policies.cs index 9edc3bb..03b9db5 100644 --- a/RdcMan/Policies.cs +++ b/RdcMan/Policies.cs @@ -1,7 +1,9 @@ using Microsoft.Win32; -namespace RdcMan { - public class Policies { +namespace RdcMan +{ + public class Policies + { public const string PolicyRegKey = "RDCMan"; public static bool DisableLogOff; @@ -12,7 +14,7 @@ public static void Read() { .OpenSubKey("Software", writable: true) .OpenSubKey("Policies", writable: true) .OpenSubKey("Microsoft", writable: true) - .CreateSubKey(PolicyRegKey, RegistryKeyPermissionCheck.ReadSubTree); + .CreateSubKey("RDCMan", RegistryKeyPermissionCheck.ReadSubTree); if (registryKey != null) DisableLogOff = (int)registryKey.GetValue("DisableLogOff", 0) == 1; } diff --git a/RdcMan/Preferences.cs b/RdcMan/Preferences.cs index bda1fa2..706fee5 100644 --- a/RdcMan/Preferences.cs +++ b/RdcMan/Preferences.cs @@ -9,18 +9,22 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { +namespace RdcMan +{ [SettingsProvider(typeof(RdcSettingsProvider))] - public sealed class Preferences : ApplicationSettingsBase { + public sealed class Preferences : ApplicationSettingsBase + { public bool NeedToSave { get; set; } public GlobalSettings Settings { get; private set; } public override object this[string propertyName] { - get { + get + { return Settings.GetValue(propertyName); } - set { + set + { Settings.SetValue(propertyName, value); } } @@ -32,10 +36,12 @@ public override object this[string propertyName] { [UserScopedSetting] [DefaultSettingValue("False")] public bool AutoSaveFiles { - get { + get + { return (bool)this["AutoSaveFiles"]; } - set { + set + { this["AutoSaveFiles"] = value; } } @@ -43,10 +49,12 @@ public bool AutoSaveFiles { [UserScopedSetting] [DefaultSettingValue("0")] public int AutoSaveInterval { - get { + get + { return (int)this["AutoSaveInterval"]; } - set { + set + { this["AutoSaveInterval"] = value; } } @@ -54,10 +62,12 @@ public int AutoSaveInterval { [UserScopedSetting] [DefaultSettingValue("False")] public bool ShowConnectedGroup { - get { + get + { return (bool)this["ShowConnectedGroup"]; } - set { + set + { this["ShowConnectedGroup"] = value; } } @@ -68,14 +78,15 @@ public bool ShowConnectedGroup { [UserScopedSetting] [DefaultSettingValue("False")] public bool ShowInternalGroup { - get { + get + { return (bool)this["ShowInternalGroup"]; } - set { + set + { this["ShowInternalGroup"] = value; } } - [UserScopedSetting] [DefaultSettingValue("False")] public bool ShowFavoritesGroup { @@ -89,478 +100,608 @@ public bool ShowFavoritesGroup { [UserScopedSetting] [DefaultSettingValue("False")] - public bool ShowReconnectGroup { - get { + public bool ShowReconnectGroup + { + get + { return (bool)this["ShowReconnectGroup"]; } - set { + set + { this["ShowReconnectGroup"] = value; } } [UserScopedSetting] [DefaultSettingValue("False")] - public bool ShowRecentlyUsedGroup { - get { + public bool ShowRecentlyUsedGroup + { + get + { return (bool)this["ShowRecentlyUsedGroup"]; } - set { + set + { this["ShowRecentlyUsedGroup"] = value; } } [UserScopedSetting] - public List FilesToOpen { - get { + public List FilesToOpen + { + get + { return (List)this["FilesToOpen"]; } - set { + set + { this["FilesToOpen"] = value; } } [UserScopedSetting] - public byte[] CredentialsProfiles { - get { + public byte[] CredentialsProfiles + { + get + { return (byte[])base["CredentialsProfiles"]; } - set { + set + { base["CredentialsProfiles"] = value; } } [UserScopedSetting] - public XmlDocument CredentialsProfilesXml { - get { + public XmlDocument CredentialsProfilesXml + { + get + { return (XmlDocument)this["CredentialsProfilesXml"]; } - set { + set + { this["CredentialsProfilesXml"] = value; } } [UserScopedSetting] [DefaultSettingValue("False")] - public bool FocusOnClick { - get { + public bool FocusOnClick + { + get + { return (bool)this["FocusOnClick"]; } - set { + set + { this["FocusOnClick"] = value; } } [UserScopedSetting] [DefaultSettingValue("False")] - public bool DimNodesWhenInactive { - get { + public bool DimNodesWhenInactive + { + get + { return (bool)this["DimNodesWhenInactive"]; } - set { + set + { this["DimNodesWhenInactive"] = value; } } [UserScopedSetting] [DefaultSettingValue("False")] - public bool FullScreenWindowIsTopMost { - get { + public bool FullScreenWindowIsTopMost + { + get + { return (bool)this["FullScreenWindowIsTopMost"]; } - set { + set + { this["FullScreenWindowIsTopMost"] = value; } } [UserScopedSetting] [DefaultSettingValue("False")] - public bool UseMultipleMonitors { - get { + public bool UseMultipleMonitors + { + get + { return (bool)this["UseMultipleMonitors"]; } - set { + set + { this["UseMultipleMonitors"] = value; } } [UserScopedSetting] [DefaultSettingValue("False")] - public bool EnablePanning { - get { + public bool EnablePanning + { + get + { return (bool)this["EnablePanning"]; } - set { + set + { this["EnablePanning"] = value; } } [UserScopedSetting] [DefaultSettingValue("1")] - public int PanningAcceleration { - get { + public int PanningAcceleration + { + get + { return (int)this["PanningAcceleration"]; } - set { + set + { this["PanningAcceleration"] = value; } } [UserScopedSetting] [DefaultSettingValue("ByName")] - public SortOrder GroupSortOrder { - get { + public SortOrder GroupSortOrder + { + get + { return (SortOrder)this["GroupSortOrder"]; } - set { + set + { this["GroupSortOrder"] = value; } } [UserScopedSetting] [DefaultSettingValue("ByStatus")] - public SortOrder ServerSortOrder { - get { + public SortOrder ServerSortOrder + { + get + { return (SortOrder)this["ServerSortOrder"]; } - set { + set + { this["ServerSortOrder"] = value; } } [UserScopedSetting] [DefaultSettingValue("Dock")] - public ControlVisibility ServerTreeVisibility { - get { + public ControlVisibility ServerTreeVisibility + { + get + { return (ControlVisibility)this["ServerTreeVisibility"]; } - set { + set + { this["ServerTreeVisibility"] = value; } } [UserScopedSetting] [DefaultSettingValue("0")] - public int ServerTreeAutoHidePopUpDelay { - get { + public int ServerTreeAutoHidePopUpDelay + { + get + { return (int)this["ServerTreeAutoHidePopUpDelay"]; } - set { + set + { this["ServerTreeAutoHidePopUpDelay"] = value; } } [UserScopedSetting] [DefaultSettingValue("Left")] - public DockStyle ServerTreeLocation { - get { + public DockStyle ServerTreeLocation + { + get + { return (DockStyle)this["ServerTreeLocation"]; } - set { + set + { this["ServerTreeLocation"] = value; } } [UserScopedSetting] [DefaultSettingValue("True")] - public bool ThumbnailSizeIsInPixels { - get { + public bool ThumbnailSizeIsInPixels + { + get + { return (bool)this["ThumbnailSizeIsInPixels"]; } - set { + set + { this["ThumbnailSizeIsInPixels"] = value; } } [UserScopedSetting] [DefaultSettingValue("160, 120")] - public Size ThumbnailSize { - get { + public Size ThumbnailSize + { + get + { return (Size)this["ThumbnailSize"]; } - set { + set + { this["ThumbnailSize"] = value; } } [UserScopedSetting] [DefaultSettingValue("15")] - public int ThumbnailPercentage { - get { + public int ThumbnailPercentage + { + get + { return (int)this["ThumbnailPercentage"]; } - set { + set + { this["ThumbnailPercentage"] = value; } } [UserScopedSetting] - public byte[] DefaultGroupSettings { - get { + public byte[] DefaultGroupSettings + { + get + { return (byte[])base["DefaultGroupSettings"]; } - set { + set + { base["DefaultGroupSettings"] = value; } } [UserScopedSetting] [DefaultSettingValue("0")] - public int PerformanceFlags { - get { + public int PerformanceFlags + { + get + { return (int)this["PerformanceFlags"]; } - set { + set + { this["PerformanceFlags"] = value; } } [UserScopedSetting] [DefaultSettingValue("True")] - public bool PersistentBitmapCaching { - get { + public bool PersistentBitmapCaching + { + get + { return (bool)this["PersistentBitmapCaching"]; } - set { + set + { this["PersistentBitmapCaching"] = value; } } [UserScopedSetting] [DefaultSettingValue("False")] - public bool WindowIsMaximized { - get { + public bool WindowIsMaximized + { + get + { return (bool)this["WindowIsMaximized"]; } - set { + set + { this["WindowIsMaximized"] = value; } } [UserScopedSetting] [DefaultSettingValue("200, 200")] - public Point WindowPosition { - get { + public Point WindowPosition + { + get + { return (Point)this["WindowPosition"]; } - set { + set + { this["WindowPosition"] = value; } } [UserScopedSetting] [DefaultSettingValue("200")] - public int ServerTreeWidth { - get { + public int ServerTreeWidth + { + get + { return (int)this["ServerTreeWidth"]; } - set { + set + { this["ServerTreeWidth"] = value; } } [UserScopedSetting] [DefaultSettingValue("Pinned")] - public RdpClient.ConnectionBarState ConnectionBarState { - get { + public RdpClient.ConnectionBarState ConnectionBarState + { + get + { return (RdpClient.ConnectionBarState)this["ConnectionBarState"]; } - set { + set + { this["ConnectionBarState"] = value; } } [UserScopedSetting] [DefaultSettingValue("1273, 823")] - public Size WindowSize { - get { + public Size WindowSize + { + get + { return (Size)this["WindowSize"]; } - set { + set + { this["WindowSize"] = value; } } [UserScopedSetting] [DefaultSettingValue("False")] - public bool LockWindowSize { - get { + public bool LockWindowSize + { + get + { return (bool)this["LockWindowSize"]; } - set { + set + { this["LockWindowSize"] = value; } } [UserScopedSetting] [DefaultSettingValue("Insert")] - public Keys HotKeyAltEsc { - get { + public Keys HotKeyAltEsc + { + get + { return (Keys)this["HotKeyAltEsc"]; } - set { + set + { this["HotKeyAltEsc"] = value; } } [UserScopedSetting] [DefaultSettingValue("Home")] - public Keys HotKeyCtrlEsc { - get { + public Keys HotKeyCtrlEsc + { + get + { return (Keys)this["HotKeyCtrlEsc"]; } - set { + set + { this["HotKeyCtrlEsc"] = value; } } [UserScopedSetting] [DefaultSettingValue("PageUp")] - public Keys HotKeyAltTab { - get { + public Keys HotKeyAltTab + { + get + { return (Keys)this["HotKeyAltTab"]; } - set { + set + { this["HotKeyAltTab"] = value; } } [UserScopedSetting] [DefaultSettingValue("PageDown")] - public Keys HotKeyAltShiftTab { - get { + public Keys HotKeyAltShiftTab + { + get + { return (Keys)this["HotKeyAltShiftTab"]; } - set { + set + { this["HotKeyAltShiftTab"] = value; } } [UserScopedSetting] [DefaultSettingValue("Delete")] - public Keys HotKeyAltSpace { - get { + public Keys HotKeyAltSpace + { + get + { return (Keys)this["HotKeyAltSpace"]; } - set { + set + { this["HotKeyAltSpace"] = value; } } [UserScopedSetting] [DefaultSettingValue("End")] - public Keys HotKeyCtrlAltDel { - get { + public Keys HotKeyCtrlAltDel + { + get + { return (Keys)this["HotKeyCtrlAltDel"]; } - set { + set + { this["HotKeyCtrlAltDel"] = value; } } [UserScopedSetting] [DefaultSettingValue("Cancel")] - public Keys HotKeyFullScreen { - get { + public Keys HotKeyFullScreen + { + get + { return (Keys)this["HotKeyFullScreen"]; } - set { + set + { this["HotKeyFullScreen"] = value; } } [UserScopedSetting] [DefaultSettingValue("Left")] - public Keys HotKeyFocusReleaseLeft { - get { + public Keys HotKeyFocusReleaseLeft + { + get + { return (Keys)this["HotKeyFocusReleaseLeft"]; } - set { + set + { this["HotKeyFocusReleaseLeft"] = value; } } [UserScopedSetting] [DefaultSettingValue("Right")] - public Keys HotKeyFocusReleaseRight { - get { + public Keys HotKeyFocusReleaseRight + { + get + { return (Keys)this["HotKeyFocusReleaseRight"]; } - set { + set + { this["HotKeyFocusReleaseRight"] = value; } } [UserScopedSetting] - [DefaultSettingValue("2022-01-01 00:00:00Z")] - public string LastUpdateCheckTimeUtc { - get { + [DefaultSettingValue("2012-06-01 00:00:00Z")] + public string LastUpdateCheckTimeUtc + { + get + { return (string)this["LastUpdateCheckTimeUtc"]; } - set { + set + { this["LastUpdateCheckTimeUtc"] = value; } } [UserScopedSetting] [DefaultSettingValue("False")] - public bool HideMainMenu { - get { + public bool HideMainMenu + { + get + { return (bool)this["HideMainMenu"]; } - set { + set + { this["HideMainMenu"] = value; } } [UserScopedSetting] [DefaultSettingValue("True")] - public bool ReconnectOnStartup { - get { + public bool ReconnectOnStartup + { + get + { return (bool)this["ReconnectOnStartup"]; } - set { + set + { this["ReconnectOnStartup"] = value; } } - private Preferences() { + private Preferences() + { Settings = new GlobalSettings(); string name = Assembly.GetExecutingAssembly().GetName().Name; SettingsDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Application.CompanyName, Application.ProductName); SettingsPath = Path.Combine(SettingsDirectory, name + ".settings"); } - public object GetTransferValue(string name) { + public object GetTransferValue(string name) + { return base[name]; } - public static Preferences Load() { + public static Preferences Load() + { Preferences preferences = new Preferences(); if (Program.ResetPreferences) + { return preferences; - + } List list = new List(); string text = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Microsoft Corporation", Application.ProductName); string text2 = Path.Combine(text, "RDCMan.settings"); - if (File.Exists(text2)) { - if (!File.Exists(preferences.SettingsPath)) { + if (File.Exists(text2)) + { + if (!File.Exists(preferences.SettingsPath)) + { Directory.CreateDirectory(preferences.SettingsDirectory); File.Move(text2, preferences.SettingsPath); } - try { + try + { Directory.Delete(text); } catch { } } bool flag = true; - try { - using XmlTextReader reader = new XmlTextReader(preferences.SettingsPath) { + try + { + using XmlTextReader reader = new XmlTextReader(preferences.SettingsPath) + { DtdProcessing = DtdProcessing.Ignore }; XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(reader); XmlNode lastChild = xmlDocument.LastChild; - try { + try + { string value = lastChild.Attributes["programVersion"].Value; preferences.Settings.ReadXml(lastChild, null, list); flag = false; @@ -568,12 +709,14 @@ public static Preferences Load() { catch { } } catch { } - - if (flag) { + if (flag) + { preferences.Settings.TransferPreferences(preferences); - if (preferences.DefaultGroupSettings != null) { + if (preferences.DefaultGroupSettings != null) + { MemoryStream input = new MemoryStream(preferences.DefaultGroupSettings); - XmlTextReader xmlTextReader = new XmlTextReader(input) { + XmlTextReader xmlTextReader = new XmlTextReader(input) + { WhitespaceHandling = WhitespaceHandling.None, DtdProcessing = DtdProcessing.Ignore }; @@ -584,9 +727,11 @@ public static Preferences Load() { GroupBase.SchemaVersion = 2; DefaultSettingsGroup.Instance.ReadXml(xmlNode, list); } - if (preferences.CredentialsProfiles != null) { + if (preferences.CredentialsProfiles != null) + { MemoryStream input2 = new MemoryStream(preferences.CredentialsProfiles); - XmlTextReader xmlTextReader2 = new XmlTextReader(input2) { + XmlTextReader xmlTextReader2 = new XmlTextReader(input2) + { WhitespaceHandling = WhitespaceHandling.None, DtdProcessing = DtdProcessing.Ignore }; @@ -597,47 +742,60 @@ public static Preferences Load() { Program.CredentialsProfiles.ReadXml(xmlNode2, ProfileScope.Global, DefaultSettingsGroup.Instance, list); } } - else { - if (preferences.Settings.DefaultGroupSettings != null) { + else + { + if (preferences.Settings.DefaultGroupSettings != null) + { XmlNode firstChild = preferences.Settings.DefaultGroupSettings.Value.FirstChild; DefaultSettingsGroup.Instance.ReadXml(firstChild, list); } - if (preferences.Settings.CredentialsProfiles != null) { + if (preferences.Settings.CredentialsProfiles != null) + { XmlNode firstChild2 = preferences.Settings.CredentialsProfiles.Value.FirstChild; Program.CredentialsProfiles.ReadXml(firstChild2, ProfileScope.Global, DefaultSettingsGroup.Instance, list); } } Encryption.DecryptPasswords(); - if (list.Count > 0) { + if (list.Count > 0) + { StringBuilder stringBuilder = new StringBuilder("´").AppendLine().AppendLine(); - foreach (string item in list) { + foreach (string item in list) + { stringBuilder.AppendLine(item); } stringBuilder.AppendLine().Append("ȫδȫء棬϶ζŶʧϢǷ"); DialogResult dialogResult = FormTools.ExclamationDialog(stringBuilder.ToString(), MessageBoxButtons.YesNo); if (dialogResult == DialogResult.No) + { return null; + } } return preferences; } - public void LoadBuiltInGroups() { + public void LoadBuiltInGroups() + { if (Settings.BuiltInGroups.Value == null) + { return; - + } GroupBase.SchemaVersion = 3; XmlNode firstChild = Settings.BuiltInGroups.Value.FirstChild; List errors = new List(); - foreach (XmlNode childNode in firstChild.ChildNodes) { + foreach (XmlNode childNode in firstChild.ChildNodes) + { Program.BuiltInVirtualGroups.Where((IBuiltInVirtualGroup v) => childNode.Name.Equals(v.XmlNodeName)).FirstOrDefault()?.ReadXml(childNode, null, errors); } } - public override void Save() { + public override void Save() + { if (!NeedToSave) + { return; - - using (StringWriter stringWriter = new StringWriter()) { + } + using (StringWriter stringWriter = new StringWriter()) + { using XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter); DefaultSettingsGroup.Instance.WriteXml(xmlTextWriter); xmlTextWriter.Flush(); @@ -646,7 +804,8 @@ public override void Save() { xmlDocument.LoadXml(stringWriter.ToString()); Settings.DefaultGroupSettings.Value = xmlDocument.LastChild; } - using (StringWriter stringWriter2 = new StringWriter()) { + using (StringWriter stringWriter2 = new StringWriter()) + { using XmlTextWriter xmlTextWriter2 = new XmlTextWriter(stringWriter2); Program.CredentialsProfiles.WriteXml(xmlTextWriter2, DefaultSettingsGroup.Instance); xmlTextWriter2.Flush(); @@ -659,7 +818,8 @@ public override void Save() { SerializeBuiltInGroups(); SerializePluginSettings(); string temporaryFileName = Helpers.GetTemporaryFileName(SettingsPath, ".new"); - using (XmlTextWriter xmlTextWriter3 = new XmlTextWriter(temporaryFileName, Encoding.UTF8)) { + using (XmlTextWriter xmlTextWriter3 = new XmlTextWriter(temporaryFileName, Encoding.UTF8)) + { xmlTextWriter3.Formatting = Formatting.Indented; xmlTextWriter3.WriteStartDocument(); Settings.WriteXml(xmlTextWriter3, null); @@ -670,14 +830,19 @@ public override void Save() { NeedToSave = false; } - private void SerializeBuiltInGroups() { + private void SerializeBuiltInGroups() + { using StringWriter stringWriter = new StringWriter(); XmlTextWriter tw = new XmlTextWriter(stringWriter); - try { + try + { tw.WriteStartElement("groups"); - Program.BuiltInVirtualGroups.ForEach(delegate (IBuiltInVirtualGroup virtualGroup) { + Program.BuiltInVirtualGroups.ForEach(delegate(IBuiltInVirtualGroup virtualGroup) + { if (!string.IsNullOrEmpty(virtualGroup.XmlNodeName)) + { virtualGroup.WriteXml(tw, null); + } }); tw.WriteEndElement(); tw.Flush(); @@ -686,33 +851,44 @@ private void SerializeBuiltInGroups() { xmlDocument.LoadXml(stringWriter.ToString()); Settings.BuiltInGroups.Value = xmlDocument.LastChild; } - finally { + finally + { if (tw != null) + { ((IDisposable)tw).Dispose(); + } } } - private void CollectFilesToOpen() { + private void CollectFilesToOpen() + { FilesToOpen = (from file in ServerTree.Instance.Nodes.OfType() - select file.Pathname).ToList(); + select file.Pathname).ToList(); } - private void SerializePluginSettings() { + private void SerializePluginSettings() + { using StringWriter stringWriter = new StringWriter(); XmlTextWriter tw = new XmlTextWriter(stringWriter); - try { + try + { tw.WriteStartElement("plugins"); - Program.PluginAction(delegate (IPlugin p) { - try { + Program.PluginAction(delegate(IPlugin p) + { + try + { XmlNode xmlNode = p.SaveSettings(); - if (xmlNode != null) { + if (xmlNode != null) + { tw.WriteStartElement("plugin"); - tw.WriteAttributeString("path", p.GetType().AssemblyQualifiedName); + tw.WriteAttributeString("path", p.GetType().Assembly.GetName().Name); xmlNode.WriteTo(tw); tw.WriteEndElement(); } } - catch { } + catch + { + } }); tw.WriteEndElement(); tw.Flush(); @@ -721,18 +897,23 @@ private void SerializePluginSettings() { xmlDocument.LoadXml(stringWriter.ToString()); Settings.PluginSettings.Value = xmlDocument.LastChild; } - finally { + finally + { if (tw != null) + { ((IDisposable)tw).Dispose(); + } } } - internal bool GetBuiltInGroupVisibility(IBuiltInVirtualGroup builtInGroup) { + internal bool GetBuiltInGroupVisibility(IBuiltInVirtualGroup builtInGroup) + { string propertyName = $"Show{builtInGroup.ConfigPropertyName}Group"; return (bool)this[propertyName]; } - internal void SetBuiltInGroupVisibility(IBuiltInVirtualGroup builtInGroup, bool value) { + internal void SetBuiltInGroupVisibility(IBuiltInVirtualGroup builtInGroup, bool value) + { string propertyName = $"Show{builtInGroup.ConfigPropertyName}Group"; this[propertyName] = value; } diff --git a/RdcMan/ProfileScope.cs b/RdcMan/ProfileScope.cs index 2e13558..f69e0c6 100644 --- a/RdcMan/ProfileScope.cs +++ b/RdcMan/ProfileScope.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public enum ProfileScope { +namespace RdcMan +{ + public enum ProfileScope + { Global, File, Local diff --git a/RdcMan/ProfileSetting.cs b/RdcMan/ProfileSetting.cs index 515c056..0b4e007 100644 --- a/RdcMan/ProfileSetting.cs +++ b/RdcMan/ProfileSetting.cs @@ -1,47 +1,58 @@ using System.Xml; -namespace RdcMan { - public class ProfileSetting : StringSetting { +namespace RdcMan +{ + public class ProfileSetting : StringSetting + { public const string ProfileScopeAttribute = "scope"; public ProfileScope Scope { get; private set; } public ProfileSetting(object o) - : base(o) { + : base(o) + { Reset(); } - public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) { + public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) + { base.ReadXml(xmlNode, node); - try { + try + { XmlNode namedItem = xmlNode.Attributes.GetNamedItem(ProfileScopeAttribute); Scope = namedItem.InnerText.ParseEnum(); } - catch { + catch + { Scope = ProfileScope.Local; } } - public override void WriteXml(XmlTextWriter tw, RdcTreeNode node) { + public override void WriteXml(XmlTextWriter tw, RdcTreeNode node) + { tw.WriteAttributeString(ProfileScopeAttribute, Scope.ToString()); tw.WriteString(base.Value); } - public override void Copy(ISetting source) { + public override void Copy(ISetting source) + { base.Copy(source); Scope = ((ProfileSetting)source).Scope; } - public override string ToString() { + public override string ToString() + { return "{0} ({1})".InvariantFormat(base.Value, Scope); } - public void UpdateValue(string newValue, ProfileScope newScope) { + public void UpdateValue(string newValue, ProfileScope newScope) + { base.Value = newValue; Scope = newScope; } - public void Reset() { + public void Reset() + { Scope = ProfileScope.Local; base.Value = "Custom"; } diff --git a/RdcMan/Program.cs b/RdcMan/Program.cs index bb86569..830a1d5 100644 --- a/RdcMan/Program.cs +++ b/RdcMan/Program.cs @@ -5,18 +5,20 @@ using System.IO; using System.Linq; using System.Reflection; -using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Windows.Forms; using System.Xml; using RdcMan.Configuration; -namespace RdcMan { - internal class Program { +namespace RdcMan +{ + internal class Program + { private delegate void ShowFormDelegate(Form form); - private class PluginConfig { + private class PluginConfig + { public IPlugin Plugin { get; set; } public string Name { get; set; } @@ -42,18 +44,6 @@ private class PluginConfig { private const string PluginPattern = "Plugin.*.dll"; - //private const int BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE = 1; - - //private const int BASE_SEARCH_PATH_PERMANENT = 32768; - - //private const uint NoRemoteImages = 1u; - - //private const uint PreferSystem32Images = 4u; - - private const int ProcessImageLoadPolicy = 10; - - private const int LOAD_LIBRARY_SEARCH_SYSTEM32 = 2048; - internal static MainForm TheForm { get; set; } internal static Preferences Preferences { get; private set; } @@ -66,78 +56,55 @@ private class PluginConfig { private static PluginContext PluginContext { get; set; } - public static void PluginAction(Action action) { - Plugins.Values.ForEach(delegate (PluginConfig v) { + public static void PluginAction(Action action) + { + Plugins.Values.ForEach(delegate(PluginConfig v) + { IPlugin plugin = v.Plugin; if (plugin != null) + { action(plugin); + } }); } - [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool SetDllDirectory(string lpPathName); - - [DllImport("kernel32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool SetSearchPathMode(int flags); - - [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool SetProcessMitigationPolicy(int policy, UIntPtr lpBuffer, UIntPtr size); - - [DllImport("kernel32.dll", SetLastError = true)] - private static extern bool SetDefaultDllDirectories(uint directoryFlags); - - private unsafe static bool DisableLocalDllLoading() { - int num = 0; - if (!SetDllDirectory("")) - num++; - - if (!SetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_SYSTEM32)) - num++; - - if (!SetSearchPathMode(32769)) - num++; - - uint structure = 5u; - if (!SetProcessMitigationPolicy(ProcessImageLoadPolicy, (UIntPtr)(&structure), (UIntPtr)(ulong)Marshal.SizeOf(structure))) { - Marshal.GetLastWin32Error(); - num++; - } - return num == 0; - } - [STAThread] - internal static void Main(params string[] args) { - if (!DisableLocalDllLoading()) - FormTools.InformationDialog(" - RDCMan ޷Ͻ̶δǩĿ⡣"); - + internal static void Main(params string[] args) + { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(defaultValue: true); Policies.Read(); - using (Helpers.Timer("parsing command line")) { + using (Helpers.Timer("parsing command line")) + { ParseCommandLine(); } - try { + try + { Current.Read(); } - catch (Exception ex) { + catch (Exception ex) + { FormTools.ErrorDialog("ȡ RDCMan ļʱ{0} ܲȶ/ܲ".InvariantFormat(ex.Message)); } - using (CompositionContainer compositionContainer = new CompositionContainer(new AssemblyCatalog(Assembly.GetCallingAssembly()))) { + using (CompositionContainer compositionContainer = new CompositionContainer(new AssemblyCatalog(Assembly.GetCallingAssembly()))) + { _builtInVirtualGroups.AddRange(compositionContainer.GetExportedValues()); _builtInVirtualGroups.Sort((IBuiltInVirtualGroup a, IBuiltInVirtualGroup b) => a.Text.CompareTo(b.Text)); } - using (Helpers.Timer("reading preferences")) { + using (Helpers.Timer("reading preferences")) + { Preferences = Preferences.Load(); if (Preferences == null) + { Environment.Exit(1); + } } Thread thread; - using (Helpers.Timer("starting message loop thread")) { + using (Helpers.Timer("starting message loop thread")) + { InitializedEvent = new ManualResetEvent(initialState: false); - thread = new Thread(StartMessageLoop) { + thread = new Thread(StartMessageLoop) + { IsBackground = true }; thread.SetApartmentState(ApartmentState.STA); @@ -145,30 +112,39 @@ internal static void Main(params string[] args) { InitializedEvent.WaitOne(); } if (TheForm == null) + { Environment.Exit(1); - + } TheForm.Invoke(new MethodInvoker(CompleteInitialization)); thread.Join(); Log.Write("Exiting"); } - private static void CompleteInitialization() { + private static void CompleteInitialization() + { InstantiatePlugins(); if (_filesToOpen.Count > 0) + { Preferences.FilesToOpen = _filesToOpen; + } else if (!_openFiles) + { Preferences.FilesToOpen = null; - + } List connectedServers = new List(); - ServerTree.Instance.Operation(OperationBehavior.SuspendSort, delegate { - foreach (IBuiltInVirtualGroup item in BuiltInVirtualGroups.Where((IBuiltInVirtualGroup group) => group.IsVisibilityConfigurable)) { + ServerTree.Instance.Operation(OperationBehavior.SuspendSort, delegate + { + foreach (IBuiltInVirtualGroup item in BuiltInVirtualGroups.Where((IBuiltInVirtualGroup group) => group.IsVisibilityConfigurable)) + { item.IsInTree = Preferences.GetBuiltInGroupVisibility(item); } }); OpenFiles(); - ServerTree.Instance.Operation(OperationBehavior.SuspendGroupChanged, delegate { + ServerTree.Instance.Operation(OperationBehavior.SuspendGroupChanged, delegate + { Preferences.LoadBuiltInGroups(); - ConnectedGroup.Instance.Nodes.ForEach(delegate (TreeNode n) { + ConnectedGroup.Instance.Nodes.ForEach(delegate(TreeNode n) + { connectedServers.Add(((ServerRef)n).ServerNode); }); ConnectedGroup.Instance.RemoveChildren(); @@ -178,115 +154,149 @@ private static void CompleteInitialization() { ServerTree.Instance.Focus(); bool isFirstConnection = ReconnectAtStartup(connectedServers); if (_serversToConnect != null) + { ConnectNamedServers(_serversToConnect, isFirstConnection); - + } if (Preferences.ServerTreeVisibility != 0) + { ServerTree.Instance.Hide(); - - PluginAction(delegate (IPlugin p) { + } + PluginAction(delegate(IPlugin p) + { p.PostLoad(PluginContext); }); Preferences.NeedToSave = false; TheForm.UpdateAutoSaveTimer(); - ThreadPool.QueueUserWorkItem(delegate { + ThreadPool.QueueUserWorkItem(delegate + { CheckForUpdate(); }); Log.Write("Startup completed"); } - private static bool ReconnectAtStartup(List connectedServers) { + private static bool ReconnectAtStartup(List connectedServers) + { IEnumerable reconnectServers = Enumerable.Empty(); - switch (_reconnectServersAtStart) { - case ReconnectServerOptions.All: - reconnectServers = connectedServers; - break; - case ReconnectServerOptions.None: - return false; - case ReconnectServerOptions.Ask: - if (Preferences.ReconnectOnStartup && connectedServers.Any()) - reconnectServers = new List(ConnectServersDialog(connectedServers)); - break; + switch (_reconnectServersAtStart) + { + case ReconnectServerOptions.All: + reconnectServers = connectedServers; + break; + case ReconnectServerOptions.None: + return false; + case ReconnectServerOptions.Ask: + if (Preferences.ReconnectOnStartup && connectedServers.Any()) + { + reconnectServers = new List(ConnectServersDialog(connectedServers)); + } + break; } return ConnectServers(reconnectServers, isFirstConnection: true); } - private static void InstantiatePlugins() { + private static void InstantiatePlugins() + { PluginContext = new PluginContext(); Assembly callingAssembly = Assembly.GetCallingAssembly(); - DirectoryCatalog catalog = new DirectoryCatalog(Path.GetDirectoryName(callingAssembly.Location), PluginPattern); + DirectoryCatalog catalog = new DirectoryCatalog(Path.GetDirectoryName(callingAssembly.Location), "Plugin.*.dll"); CompositionContainer compositionContainer = new CompositionContainer(catalog); Plugins = new Dictionary(StringComparer.OrdinalIgnoreCase); StringBuilder stringBuilder = new StringBuilder(); XmlNode value = Preferences.Settings.PluginSettings.Value; - if (value != null) { - foreach (XmlNode item in value.SelectNodes("//plugin")) { - try { + if (value != null) + { + foreach (XmlNode item in value.SelectNodes("//plugin")) + { + try + { string value2 = item.Attributes["path"].Value; - if (!string.IsNullOrEmpty(value2)) { - PluginConfig value3 = new PluginConfig { + if (!string.IsNullOrEmpty(value2)) + { + PluginConfig value3 = new PluginConfig + { Name = value2, SettingsNode = item }; Plugins[value2] = value3; } } - catch { } + catch + { + } } } foreach (IPlugin item2 in from e in compositionContainer.GetExports() - select e.Value) { + select e.Value) + { string name = item2.GetType().Assembly.GetName().Name; - if (!Plugins.TryGetValue(name, out var value4)) { - value4 = new PluginConfig { + if (!Plugins.TryGetValue(name, out var value4)) + { + value4 = new PluginConfig + { Name = name }; Plugins[name] = value4; } - try { + try + { item2.PreLoad(PluginContext, value4.SettingsNode); value4.Plugin = item2; } - catch (Exception ex) { + catch (Exception ex) + { stringBuilder.AppendLine("ء{0}ʱ{1}".InvariantFormat(name, ex.Message)); } } - foreach (PluginConfig item3 in Plugins.Values.Where((PluginConfig c) => c.Plugin == null)) { + foreach (PluginConfig item3 in Plugins.Values.Where((PluginConfig c) => c.Plugin == null)) + { stringBuilder.AppendLine("{0}ǰʹùδ".InvariantFormat(item3.Name)); } - if (stringBuilder.Length > 0) { + if (stringBuilder.Length > 0) + { stringBuilder.AppendLine().Append("Click Cancel to exit"); string text = "һЩδء RDCMan ޷ԤС{0}{0}".InvariantFormat(Environment.NewLine) + stringBuilder.ToString(); if (FormTools.ExclamationDialog(text, MessageBoxButtons.OKCancel) == DialogResult.Cancel) + { Environment.Exit(1); + } } } - private static void OpenFiles() { + private static void OpenFiles() + { List filesToOpen = Preferences.FilesToOpen; if (filesToOpen == null) + { return; - + } bool flag = true; - foreach (string item in filesToOpen) { + foreach (string item in filesToOpen) + { FileGroup fileGroup = RdgFile.OpenFile(item); - if (fileGroup != null && flag) { + if (fileGroup != null && flag) + { flag = false; ServerTree.Instance.SelectedNode = fileGroup; } } } - internal static IEnumerable ConnectServersDialog(IEnumerable servers) { + internal static IEnumerable ConnectServersDialog(IEnumerable servers) + { using ConnectServersDialog connectServersDialog = new ConnectServersDialog(servers); if (connectServersDialog.ShowDialog(TheForm) == DialogResult.OK) + { return connectServersDialog.SelectedServers.ToList(); - + } return new ServerBase[0]; } - internal static bool ConnectServers(IEnumerable reconnectServers, bool isFirstConnection) { - NodeHelper.ThrottledConnect(reconnectServers, delegate (ServerBase server) { - if (isFirstConnection) { + internal static bool ConnectServers(IEnumerable reconnectServers, bool isFirstConnection) + { + NodeHelper.ThrottledConnect(reconnectServers, delegate(ServerBase server) + { + if (isFirstConnection) + { ServerTree.Instance.SelectedNode = server; server.Focus(); isFirstConnection = false; @@ -295,21 +305,27 @@ internal static bool ConnectServers(IEnumerable reconnectServers, bo return isFirstConnection; } - private static bool ConnectNamedServers(ICollection serverNames, bool isFirstConnection) { + private static bool ConnectNamedServers(ICollection serverNames, bool isFirstConnection) + { HashSet nameHash = new HashSet(serverNames, StringComparer.OrdinalIgnoreCase); List serversToConnect = new List(); - ServerTree.Instance.Nodes.VisitNodes(delegate (RdcTreeNode node) { - if (node is Server server && nameHash.Contains(server.ServerName)) { + ServerTree.Instance.Nodes.VisitNodes(delegate(RdcTreeNode node) + { + if (node is Server server && nameHash.Contains(server.ServerName)) + { if (!server.IsConnected) + { serversToConnect.Add(server); - + } nameHash.Remove(server.ServerName); } }); isFirstConnection = ConnectServers(serversToConnect, isFirstConnection); - if (nameHash.Count > 0) { + if (nameHash.Count > 0) + { StringBuilder stringBuilder = new StringBuilder("δҵ·޷ӣ").AppendLine().AppendLine(); - foreach (string item in nameHash) { + foreach (string item in nameHash) + { stringBuilder.AppendLine(item); } FormTools.InformationDialog(stringBuilder.ToString()); @@ -317,7 +333,8 @@ private static bool ConnectNamedServers(ICollection serverNames, bool is return isFirstConnection; } - private static void ParseCommandLine() { + private static void ParseCommandLine() + { ArgumentParser argumentParser = new ArgumentParser(); argumentParser.AddSwitch("?", requiresValue: false); argumentParser.AddSwitch("h", requiresValue: false); @@ -326,32 +343,40 @@ private static void ParseCommandLine() { argumentParser.AddSwitch("noconnect", requiresValue: false); argumentParser.AddSwitch("reconnect", requiresValue: false); argumentParser.AddSwitch("c", requiresValue: true); - try { + try + { argumentParser.Parse(); } - catch (ArgumentException ex) { + catch (ArgumentException ex) + { FormTools.ErrorDialog(ex.Message); Environment.Exit(1); } - if (argumentParser.HasSwitch("?") || argumentParser.HasSwitch("h")) { + if (argumentParser.HasSwitch("?") || argumentParser.HasSwitch("h")) + { Usage(); Environment.Exit(0); } if (argumentParser.HasSwitch("reset")) + { ResetPreferences = true; - + } if (argumentParser.HasSwitch("noopen")) + { _openFiles = false; - + } if (argumentParser.HasSwitch("noconnect")) + { _reconnectServersAtStart = ReconnectServerOptions.None; - + } if (argumentParser.HasSwitch("reconnect")) + { _reconnectServersAtStart = ReconnectServerOptions.All; - + } if (argumentParser.HasSwitch("c")) + { _serversToConnect = argumentParser.SwitchValues["c"].Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries); - + } _filesToOpen.AddRange(argumentParser.PlainArgs); } @@ -366,53 +391,67 @@ internal static void Usage() { FormTools.InformationDialog("δҵļ:\r\n" + text); } - private static void StartMessageLoop() { - try { - if (MainForm.Create() != null) { + private static void StartMessageLoop() + { + try + { + if (MainForm.Create() != null) + { Log.Init(); _appContext = new ApplicationContext(TheForm); Application.Run(_appContext); } } - finally { + finally + { InitializedEvent.Set(); } } - internal static void ShowForm(Form form) { + internal static void ShowForm(Form form) + { _appContext.MainForm.Invoke(new ShowFormDelegate(ShowFormWorker), form); } - private static void ShowFormWorker(Form form) { + private static void ShowFormWorker(Form form) + { form.Show(); form.BringToFront(); } - private static void CheckForUpdate() { + private static void CheckForUpdate() + { ProgramUpdateElement updateElement = Current.RdcManSection?.ProgramUpdate; - try { + try + { if (string.IsNullOrEmpty(updateElement?.VersionPath) || string.IsNullOrEmpty(updateElement.UpdateUrl)) + { return; - - if (!DateTime.TryParse(Preferences.LastUpdateCheckTimeUtc, out var result) || DateTime.UtcNow.Subtract(result).TotalDays < 1.0) { + } + if (!DateTime.TryParse(Preferences.LastUpdateCheckTimeUtc, out var result) || DateTime.UtcNow.Subtract(result).TotalDays < 1.0) + { Log.Write("Last checked for update on {0}, not checking until tomorrow", result.ToString("s")); return; } Preferences.LastUpdateCheckTimeUtc = DateTime.UtcNow.ToString("u"); string input = File.ReadAllText(updateElement.VersionPath); if (!Version.TryParse(input, out var result2)) + { return; - + } Assembly executingAssembly = Assembly.GetExecutingAssembly(); AssemblyName name = executingAssembly.GetName(); Log.Write("Latest version = {0}", result2); - if (name.Version < result2) { - TheForm.Invoke((MethodInvoker)delegate { - FormTools.InformationDialog("{0} ṩ°汾 RDCMan".InvariantFormat(updateElement.UpdateUrl)); + if (name.Version < result2) + { + TheForm.Invoke((MethodInvoker)delegate + { + FormTools.InformationDialog("T{0} ṩ°汾 RDCMan".InvariantFormat(updateElement.UpdateUrl)); }); } } - catch (Exception ex) { + catch (Exception ex) + { FormTools.InformationDialog(" RDCMan °汾 {0}\r\n{1}".InvariantFormat(updateElement.UpdateUrl,ex.Message)); } } diff --git a/RdcMan/QuickConnectDialog.cs b/RdcMan/QuickConnectDialog.cs index 90b4194..bef6429 100644 --- a/RdcMan/QuickConnectDialog.cs +++ b/RdcMan/QuickConnectDialog.cs @@ -1,14 +1,17 @@ using System; using System.Windows.Forms; -namespace RdcMan { - public class QuickConnectDialog : TabbedSettingsDialog { +namespace RdcMan +{ + public class QuickConnectDialog : TabbedSettingsDialog + { public QuickConnectTabPage QuickConnectTabPage { get; private set; } protected QuickConnectDialog(string title, string buttonText, Form parentForm) : base(title, buttonText, parentForm) { } - public void CreateControls(bool inputServerName, LogonCredentials logonCredentials, ConnectionSettings connectionSettings, FileGroup fileGroup) { + public void CreateControls(bool inputServerName, LogonCredentials logonCredentials, ConnectionSettings connectionSettings, FileGroup fileGroup) + { QuickConnectTabPage = new QuickConnectTabPage(this, logonCredentials); QuickConnectTabPage.CreateControls(inputServerName, fileGroup); AddTabPage(QuickConnectTabPage); @@ -17,7 +20,8 @@ public void CreateControls(bool inputServerName, LogonCredentials logonCredentia InitButtons(); } - protected override void ShownCallback(object sender, EventArgs e) { + protected override void ShownCallback(object sender, EventArgs e) + { base.ShownCallback(sender, e); QuickConnectTabPage.OnShown(); } diff --git a/RdcMan/QuickConnectTabPage.cs b/RdcMan/QuickConnectTabPage.cs index 5784b02..5499710 100644 --- a/RdcMan/QuickConnectTabPage.cs +++ b/RdcMan/QuickConnectTabPage.cs @@ -1,15 +1,19 @@ -namespace RdcMan { - public class QuickConnectTabPage : LogonCredentialsTabPage { +namespace RdcMan +{ + public class QuickConnectTabPage : LogonCredentialsTabPage + { public RdcTextBox ServerNameTextBox { get; private set; } public QuickConnectTabPage(TabbedSettingsDialog dialog, LogonCredentials settings) : base(dialog, settings) { } - public void CreateControls(bool serverName, FileGroup fileGroup) { + public void CreateControls(bool serverName, FileGroup fileGroup) + { int num = 0; int rowIndex = 0; - if (serverName) { - ServerNameTextBox = FormTools.AddLabeledTextBox(this, "(&S)ƣ", ref rowIndex, ref num); + if (serverName) + { + ServerNameTextBox = FormTools.AddLabeledTextBox(this, "(&S)", ref rowIndex, ref num); ServerNameTextBox.Enabled = true; } _credentialsUI = new CredentialsUI(base.InheritanceControl); @@ -17,7 +21,8 @@ public void CreateControls(bool serverName, FileGroup fileGroup) { _credentialsUI.PopulateCredentialsProfiles(fileGroup); } - public void OnShown() { + public void OnShown() + { if (ServerNameTextBox != null) ServerNameTextBox.Focus(); else diff --git a/RdcMan/RdcBaseForm.cs b/RdcMan/RdcBaseForm.cs index c832769..ce8721a 100644 --- a/RdcMan/RdcBaseForm.cs +++ b/RdcMan/RdcBaseForm.cs @@ -4,14 +4,19 @@ using System.Windows.Forms; using Win32; -namespace RdcMan { - public abstract class RdcBaseForm : Form { - private class DrawingControl { - public static void SuspendDrawing(Control parent) { +namespace RdcMan +{ + public abstract class RdcBaseForm : Form + { + private class DrawingControl + { + public static void SuspendDrawing(Control parent) + { User.SendMessage(parent.Handle, 11u, (IntPtr)0, (IntPtr)0); } - public static void ResumeDrawing(Control parent) { + public static void ResumeDrawing(Control parent) + { User.SendMessage(parent.Handle, 11u, (IntPtr)1, (IntPtr)0); parent.Refresh(); } @@ -31,18 +36,22 @@ public static void ResumeDrawing(Control parent) { public bool IsActive => Form.ActiveForm == this; - protected RdcBaseForm() { + protected RdcBaseForm() + { base.AutoScaleDimensions = new SizeF(96f, 96f); base.AutoScaleMode = AutoScaleMode.Dpi; - _menuPanel = new Panel { + _menuPanel = new Panel + { Dock = DockStyle.None }; - _menuStrip = new RdcMenuStrip { + _menuStrip = new RdcMenuStrip + { BackColor = Color.FromKnownColor(KnownColor.Control), ForeColor = Color.FromKnownColor(KnownColor.ControlText), Visible = true }; - _menuStrip.MenuActivate += delegate { + _menuStrip.MenuActivate += delegate + { SetMainMenuVisibility(show: true); UpdateMainMenu(); }; @@ -54,27 +63,33 @@ protected RdcBaseForm() { public abstract Size GetClientSize(); - public void SetMainMenuVisibility() { + public void SetMainMenuVisibility() + { SetMainMenuVisibility(!Program.Preferences.HideMainMenu); } - public bool SetMainMenuVisibility(bool show) { + public bool SetMainMenuVisibility(bool show) + { int num = (show ? _menuStrip.Height : 0); - if (_menuPanel.Height != num) { + if (_menuPanel.Height != num) + { _menuPanel.Height = num; LayoutContent(); } return show; } - public virtual void GoFullScreenClient(Server server, bool isTopMostWindow) { + public virtual void GoFullScreenClient(Server server, bool isTopMostWindow) + { RdpClient client = server.Client; Rectangle rectangle = Screen.GetBounds(client.Control); - if (Program.Preferences.UseMultipleMonitors && (rectangle.Height < client.MsRdpClient.DesktopHeight || rectangle.Width < client.MsRdpClient.DesktopWidth)) { + if (Program.Preferences.UseMultipleMonitors && (rectangle.Height < client.MsRdpClient.DesktopHeight || rectangle.Width < client.MsRdpClient.DesktopWidth)) + { int num = 0; int num2 = 65535; Screen[] allScreens = Screen.AllScreens; - foreach (Screen screen in allScreens) { + foreach (Screen screen in allScreens) + { num += screen.Bounds.Width; num2 = Math.Min(screen.Bounds.Height, num2); } @@ -99,11 +114,13 @@ public virtual void GoFullScreenClient(Server server, bool isTopMostWindow) { Activate(); } - public virtual bool SwitchFullScreenClient(Server newServer) { + public virtual bool SwitchFullScreenClient(Server newServer) + { return false; } - public virtual void LeaveFullScreenClient(Server server) { + public virtual void LeaveFullScreenClient(Server server) + { DrawingControl.SuspendDrawing(this); SuspendLayout(); base.FormBorderStyle = _savedBorderStyle; @@ -116,10 +133,12 @@ public virtual void LeaveFullScreenClient(Server server) { Activate(); } - protected override void OnLeave(EventArgs e) { + protected override void OnLeave(EventArgs e) + { if (Program.Preferences.HideMainMenu && _menuPanel.Height > 0) + { User.SendMessage(_menuStrip.Handle, 16u, IntPtr.Zero, IntPtr.Zero); - + } base.OnLeave(e); } @@ -127,60 +146,76 @@ protected override void OnLeave(EventArgs e) { protected abstract void LayoutContent(); - protected void UpdateMenuItems(ToolStripItemCollection items) { - foreach (ToolStripItem item in items) { + protected void UpdateMenuItems(ToolStripItemCollection items) + { + foreach (ToolStripItem item in items) + { if (item is RdcMenuItem) + { (item as RdcMenuItem).Update(); + } if (item is ToolStripMenuItem toolStripMenuItem && toolStripMenuItem.DropDownItems != null) + { UpdateMenuItems(toolStripMenuItem.DropDownItems); + } } } - protected override bool ProcessKeyPreview(ref Message m) { + protected override bool ProcessKeyPreview(ref Message m) + { if (Program.Preferences.HideMainMenu && m.WParam == (IntPtr)18 && (long)m.Msg == 261) + { SetMainMenuVisibility(_menuPanel.Height == 0); - + } return base.ProcessKeyPreview(ref m); } - private void SetNonClientTracking(int hoverMilliseconds) { + private void SetNonClientTracking(int hoverMilliseconds) + { Structs.TRACKMOUSEEVENT lpEventTrack = new Structs.TRACKMOUSEEVENT(17u, base.Handle, (uint)hoverMilliseconds); - if (hoverMilliseconds < 0) { + if (hoverMilliseconds < 0) + { lpEventTrack.dwFlags |= 2147483648u; } bool flag = User.TrackMouseEvent(ref lpEventTrack); int lastWin32Error = Marshal.GetLastWin32Error(); } - protected override void OnDeactivate(EventArgs e) { + protected override void OnDeactivate(EventArgs e) + { base.OnDeactivate(e); SetMainMenuVisibility(); } - protected override void WndProc(ref Message m) { - switch (m.Msg) { - case 33: - if (Program.Preferences.HideMainMenu) - SetMainMenuVisibility(); - break; - case 160: - SetNonClientTracking(100); - break; - case 674: + protected override void WndProc(ref Message m) + { + switch (m.Msg) + { + case 33: + if (Program.Preferences.HideMainMenu) + { + SetMainMenuVisibility(); + } + break; + case 160: + SetNonClientTracking(100); + break; + case 674: + SetNonClientTracking(-1); + break; + case 161: + NCButtonDownLParam = m.LParam; + SetNonClientTracking(100); + break; + case 672: + if (IsActive && Program.Preferences.HideMainMenu && m.WParam.ToInt32() == 2 && m.LParam == NCButtonDownLParam && (User.GetAsyncKeyState(1) & 0x8000) == 0) + { + SetMainMenuVisibility(_menuPanel.Height == 0); SetNonClientTracking(-1); - break; - case 161: - NCButtonDownLParam = m.LParam; - SetNonClientTracking(100); - break; - case 672: - if (IsActive && Program.Preferences.HideMainMenu && m.WParam.ToInt32() == 2 && m.LParam == NCButtonDownLParam && (User.GetAsyncKeyState(1) & 0x8000) == 0) { - SetMainMenuVisibility(_menuPanel.Height == 0); - SetNonClientTracking(-1); - NCButtonDownLParam = IntPtr.Zero; - return; - } - break; + NCButtonDownLParam = IntPtr.Zero; + return; + } + break; } base.WndProc(ref m); } diff --git a/RdcMan/RdcCheckBox.cs b/RdcMan/RdcCheckBox.cs index 097ddcc..55cf472 100644 --- a/RdcMan/RdcCheckBox.cs +++ b/RdcMan/RdcCheckBox.cs @@ -1,20 +1,29 @@ using System.Windows.Forms; -namespace RdcMan { - public class RdcCheckBox : CheckBox, ISettingControl { +namespace RdcMan +{ + public class RdcCheckBox : CheckBox, ISettingControl + { public BoolSetting Setting { get; set; } - void ISettingControl.UpdateControl() { + void ISettingControl.UpdateControl() + { if (Setting != null) + { base.Checked = Setting.Value; + } } - void ISettingControl.UpdateSetting() { + void ISettingControl.UpdateSetting() + { if (Setting != null) + { Setting.Value = base.Checked; + } } - string ISettingControl.Validate() { + string ISettingControl.Validate() + { return null; } } diff --git a/RdcMan/RdcDialog.cs b/RdcMan/RdcDialog.cs index 26ba641..20281e0 100644 --- a/RdcMan/RdcDialog.cs +++ b/RdcMan/RdcDialog.cs @@ -3,15 +3,18 @@ using System.Drawing; using System.Windows.Forms; -namespace RdcMan { - public abstract class RdcDialog : Form { +namespace RdcMan +{ + public abstract class RdcDialog : Form + { protected Button _acceptButton; protected Button _cancelButton; private readonly Dictionary _errorProviders; - protected RdcDialog(string dialogTitle, string acceptButtonText) { + protected RdcDialog(string dialogTitle, string acceptButtonText) + { _errorProviders = new Dictionary(); SuspendLayout(); base.AutoScaleDimensions = new SizeF(96f, 96f); @@ -22,7 +25,8 @@ protected RdcDialog(string dialogTitle, string acceptButtonText) { base.ShowInTaskbar = false; base.StartPosition = FormStartPosition.CenterParent; Text = dialogTitle; - _acceptButton = new Button { + _acceptButton = new Button + { Text = acceptButtonText }; _cancelButton = new Button(); @@ -30,22 +34,28 @@ protected RdcDialog(string dialogTitle, string acceptButtonText) { base.Shown += ShownCallback; } - private void CancelButton_Click(object sender, EventArgs e) { - _errorProviders.ForEach(delegate (KeyValuePair kvp) { + private void CancelButton_Click(object sender, EventArgs e) + { + _errorProviders.ForEach(delegate(KeyValuePair kvp) + { kvp.Value.Clear(); }); } protected RdcDialog(string dialogTitle, string acceptButtonText, Form parentForm) - : this(dialogTitle, acceptButtonText) { - if (parentForm != null) { + : this(dialogTitle, acceptButtonText) + { + if (parentForm != null) + { base.StartPosition = FormStartPosition.Manual; base.Location = new Point(parentForm.Location.X + 10, parentForm.Location.Y + FormTools.ControlHeight); } } - public bool SetError(Control c, string text) { - if (!_errorProviders.TryGetValue(c, out var value)) { + public bool SetError(Control c, string text) + { + if (!_errorProviders.TryGetValue(c, out var value)) + { value = new ErrorProvider(); value.SetIconAlignment(c, ErrorIconAlignment.MiddleLeft); _errorProviders[c] = value; @@ -54,7 +64,8 @@ public bool SetError(Control c, string text) { return !string.IsNullOrEmpty(text); } - public virtual void InitButtons() { + public virtual void InitButtons() + { _cancelButton.TabIndex = 100; _cancelButton.Text = "ȡ"; _cancelButton.DialogResult = DialogResult.Cancel; @@ -63,32 +74,43 @@ public virtual void InitButtons() { FormTools.AddButtonsAndSizeForm(this, _acceptButton, _cancelButton); } - protected virtual void ShownCallback(object sender, EventArgs args) { + protected virtual void ShownCallback(object sender, EventArgs args) + { } - protected void Close(DialogResult dr) { + protected void Close(DialogResult dr) + { base.DialogResult = dr; Close(); } - protected void OK() { + protected void OK() + { Close(DialogResult.OK); } - protected void Cancel() { + protected void Cancel() + { Close(DialogResult.Cancel); } - protected virtual void AcceptIfValid(object sender, EventArgs e) { + protected virtual void AcceptIfValid(object sender, EventArgs e) + { if (ValidateControls(base.Controls.FlattenControls(), isValid: true)) + { OK(); + } } - public bool ValidateControls(IEnumerable controls, bool isValid) { - foreach (Control control in controls) { - if (control is ISettingControl settingControl && control.Enabled) { + public bool ValidateControls(IEnumerable controls, bool isValid) + { + foreach (Control control in controls) + { + if (control is ISettingControl settingControl && control.Enabled) + { string text = settingControl.Validate(); - if (SetError(control, text) && isValid) { + if (SetError(control, text) && isValid) + { control.Focus(); isValid = false; } diff --git a/RdcMan/RdcListView.cs b/RdcMan/RdcListView.cs index 877acfd..9a29ae5 100644 --- a/RdcMan/RdcListView.cs +++ b/RdcMan/RdcListView.cs @@ -3,19 +3,23 @@ using System.Windows.Forms; using Win32; -namespace RdcMan { - public class RdcListView : ListView { +namespace RdcMan +{ + public class RdcListView : ListView + { public static bool SupportsHeaderCheckBoxes { get; private set; } private IntPtr HeaderHandle => User.SendMessage(base.Handle, 4127u, (IntPtr)0, (IntPtr)0); public event HeaderColumnClickEventHandler HeaderCheckBoxClick; - static RdcListView() { + static RdcListView() + { SupportsHeaderCheckBoxes = Kernel.MajorVersion >= 6; } - public unsafe void SetColumnHeaderToCheckBox(int index) { + public unsafe void SetColumnHeaderToCheckBox(int index) + { if (!SupportsHeaderCheckBoxes) throw new InvalidOperationException("˲ϵͳ汾ֱ֧⸴ѡ"); if (base.Parent == null) @@ -36,24 +40,31 @@ public unsafe void SetColumnHeaderToCheckBox(int index) { User.SendMessage(headerHandle, 4620u, (IntPtr)index, (IntPtr)ptr); } - public unsafe void SetColumnHeaderChecked(int index, bool isChecked) { + public unsafe void SetColumnHeaderChecked(int index, bool isChecked) + { IntPtr headerHandle = HeaderHandle; Structs.HDITEM hDITEM = default(Structs.HDITEM); hDITEM.mask = 4u; Structs.HDITEM* ptr = &hDITEM; User.SendMessage(headerHandle, 4619u, (IntPtr)index, (IntPtr)ptr); if (isChecked) + { hDITEM.fmt |= 128; + } else + { hDITEM.fmt &= -129; - + } User.SendMessage(headerHandle, 4620u, (IntPtr)index, (IntPtr)ptr); } - protected unsafe override void WndProc(ref Message m) { - if ((long)m.Msg == 78 && this.HeaderCheckBoxClick != null) { + protected unsafe override void WndProc(ref Message m) + { + if ((long)m.Msg == 78 && this.HeaderCheckBoxClick != null) + { Structs.NMHEADER nMHEADER = (Structs.NMHEADER)Marshal.PtrToStructure(m.LParam, typeof(Structs.NMHEADER)); - if (nMHEADER.hdr.code == 4294966980u) { + if (nMHEADER.hdr.code == 4294966980u) + { Structs.HDITEM hDITEM = default(Structs.HDITEM); hDITEM.mask = 4u; Structs.HDITEM* ptr = &hDITEM; diff --git a/RdcMan/RdcMenuItem.cs b/RdcMan/RdcMenuItem.cs index f068929..ecf8b0e 100644 --- a/RdcMan/RdcMenuItem.cs +++ b/RdcMan/RdcMenuItem.cs @@ -1,16 +1,20 @@ using System; using System.Windows.Forms; -namespace RdcMan { - internal abstract class RdcMenuItem : ToolStripMenuItem { +namespace RdcMan +{ + internal abstract class RdcMenuItem : ToolStripMenuItem + { protected RdcMenuItem() { } protected RdcMenuItem(string text) - : this() { + : this() + { Text = text; } - protected override void OnClick(EventArgs e) { + protected override void OnClick(EventArgs e) + { base.OnClick(e); OnClick(); } diff --git a/RdcMan/RdcMenuStrip.cs b/RdcMan/RdcMenuStrip.cs index af2ec40..420ca67 100644 --- a/RdcMan/RdcMenuStrip.cs +++ b/RdcMan/RdcMenuStrip.cs @@ -1,21 +1,29 @@ using System.Windows.Forms; using Win32; -namespace RdcMan { - public class RdcMenuStrip : MenuStrip { +namespace RdcMan +{ + public class RdcMenuStrip : MenuStrip + { public bool IsActive { get; private set; } - public RdcMenuStrip() { - base.MenuActivate += delegate { + public RdcMenuStrip() + { + base.MenuActivate += delegate + { IsActive = true; }; - base.MenuDeactivate += delegate { + base.MenuDeactivate += delegate + { IsActive = false; - if (Program.Preferences.HideMainMenu) { + if (Program.Preferences.HideMainMenu) + { bool flag = (User.GetAsyncKeyState(164) & 0x8000) != 0; bool flag2 = (User.GetAsyncKeyState(165) & 0x8000) != 0; if (!flag && !flag2) + { ((RdcBaseForm)FindForm()).SetMainMenuVisibility(show: false); + } } }; } diff --git a/RdcMan/RdcNumericUpDown.cs b/RdcMan/RdcNumericUpDown.cs index b4f9e9b..48b6156 100644 --- a/RdcMan/RdcNumericUpDown.cs +++ b/RdcMan/RdcNumericUpDown.cs @@ -1,25 +1,36 @@ using System; using System.Windows.Forms; -namespace RdcMan { - public class RdcNumericUpDown : NumericUpDown, ISettingControl { +namespace RdcMan +{ + public class RdcNumericUpDown : NumericUpDown, ISettingControl + { public IntSetting Setting { get; set; } public new Func Validate { private get; set; } - void ISettingControl.UpdateControl() { + void ISettingControl.UpdateControl() + { if (Setting != null) + { base.Value = Setting.Value; + } } - void ISettingControl.UpdateSetting() { + void ISettingControl.UpdateSetting() + { if (Setting != null) + { Setting.Value = (int)base.Value; + } } - string ISettingControl.Validate() { + string ISettingControl.Validate() + { if (Validate != null) + { return Validate(); + } return null; } } diff --git a/RdcMan/RdcRadioButton.cs b/RdcMan/RdcRadioButton.cs index 10b502a..deca5f8 100644 --- a/RdcMan/RdcRadioButton.cs +++ b/RdcMan/RdcRadioButton.cs @@ -1,20 +1,29 @@ using System.Windows.Forms; -namespace RdcMan { - public class RdcRadioButton : RadioButton, ISettingControl { +namespace RdcMan +{ + public class RdcRadioButton : RadioButton, ISettingControl + { public BoolSetting Setting { get; set; } - void ISettingControl.UpdateControl() { + void ISettingControl.UpdateControl() + { if (Setting != null) + { base.Checked = Setting.Value; + } } - void ISettingControl.UpdateSetting() { + void ISettingControl.UpdateSetting() + { if (Setting != null) + { Setting.Value = base.Checked; + } } - string ISettingControl.Validate() { + string ISettingControl.Validate() + { return null; } } diff --git a/RdcMan/RdcSettingsProvider.cs b/RdcMan/RdcSettingsProvider.cs index ab2f928..783049c 100644 --- a/RdcMan/RdcSettingsProvider.cs +++ b/RdcMan/RdcSettingsProvider.cs @@ -5,14 +5,14 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { - public class RdcSettingsProvider : SettingsProvider { +namespace RdcMan +{ + public class RdcSettingsProvider : SettingsProvider + { //private const string SettingsRoot = "Settings"; public override string ApplicationName { - get { - return "RDCMan"; - } + get => "RDCMan"; set { } } @@ -20,42 +20,57 @@ public override string ApplicationName { private string SettingsFilename => Path.Combine(SettingsDirectory, ApplicationName + ".settings"); - public override void Initialize(string name, NameValueCollection values) { + public override void Initialize(string name, NameValueCollection values) + { base.Initialize(ApplicationName, values); } - public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection properties) { + public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection properties) + { SettingsPropertyValueCollection settingsPropertyValueCollection = new SettingsPropertyValueCollection(); XmlDocument xmlDocument = new XmlDocument(); XmlNode xmlNode = null; - try { - if (!Program.ResetPreferences) { + try + { + if (!Program.ResetPreferences) + { xmlDocument.Load(SettingsFilename); xmlNode = xmlDocument.SelectSingleNode("Settings"); } } - catch { } + catch + { + } if (xmlNode == null) + { xmlNode = xmlDocument.CreateNode(XmlNodeType.Element, "root", ""); - - foreach (SettingsProperty property in properties) { + } + foreach (SettingsProperty property in properties) + { SettingsPropertyValue settingsPropertyValue = new SettingsPropertyValue(property); XmlNode xmlNode2 = xmlNode.SelectSingleNode(property.Name); - if (xmlNode2 != null) { + if (xmlNode2 != null) + { if (property.PropertyType == typeof(XmlDocument)) + { settingsPropertyValue.SerializedValue = xmlNode2.InnerXml; + } else + { settingsPropertyValue.SerializedValue = xmlNode2.InnerText; + } } else + { settingsPropertyValue.SerializedValue = property.DefaultValue; - + } settingsPropertyValueCollection.Add(settingsPropertyValue); } return settingsPropertyValueCollection; } - public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection values) { + public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection values) + { throw new InvalidOperationException(); } } diff --git a/RdcMan/RdcTextBox.cs b/RdcMan/RdcTextBox.cs index 4d87531..76d4ba8 100644 --- a/RdcMan/RdcTextBox.cs +++ b/RdcMan/RdcTextBox.cs @@ -1,26 +1,36 @@ using System; using System.Windows.Forms; -namespace RdcMan { - public class RdcTextBox : TextBox, ISettingControl { +namespace RdcMan +{ + public class RdcTextBox : TextBox, ISettingControl + { public StringSetting Setting { get; set; } public Func Validate { private get; set; } - void ISettingControl.UpdateControl() { + void ISettingControl.UpdateControl() + { if (Setting != null) + { Text = Setting.Value; + } } - void ISettingControl.UpdateSetting() { + void ISettingControl.UpdateSetting() + { if (Setting != null) + { Setting.Value = Text; + } } - string ISettingControl.Validate() { + string ISettingControl.Validate() + { if (Validate != null) + { return Validate(); - + } return null; } } diff --git a/RdcMan/RdcTreeNode.cs b/RdcMan/RdcTreeNode.cs index a653781..a57c51d 100644 --- a/RdcMan/RdcTreeNode.cs +++ b/RdcMan/RdcTreeNode.cs @@ -4,8 +4,10 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { - public abstract class RdcTreeNode : TreeNode, ILogonCredentials { +namespace RdcMan +{ + public abstract class RdcTreeNode : TreeNode, ILogonCredentials + { //public const string PropertiesXmlNodeName = "properties"; private bool _needToUpdateInheritedSettings = true; @@ -45,10 +47,13 @@ public virtual EncryptionSettings EncryptionSettings { protected List AllSettingsGroups { get; private set; } - public virtual FileGroup FileGroup { - get { + public virtual FileGroup FileGroup + { + get + { TreeNode treeNode = this; - while (treeNode.Parent != null) { + while (treeNode.Parent != null) + { treeNode = treeNode.Parent; } return treeNode as FileGroup; @@ -61,40 +66,49 @@ public string ParentPath { public virtual bool HasProperties => true; - internal GroupBase GetReadOnlyParent() { + internal GroupBase GetReadOnlyParent() + { TreeNode treeNode = this; - do { + do + { if (treeNode is GroupBase groupBase && groupBase.IsReadOnly) + { return groupBase; - + } treeNode = treeNode.Parent; } while (treeNode != null); return null; } - public List GetPath() { + public List GetPath() + { List list = new List(); - this.VisitNodeAndParents(delegate (RdcTreeNode node) { + this.VisitNodeAndParents(delegate(RdcTreeNode node) + { list.Insert(0, node); }); return list; } - public int GetPathLength() { + public int GetPathLength() + { int len = 0; - this.VisitNodeAndParents(delegate { + this.VisitNodeAndParents(delegate + { len++; }); return len; } - protected RdcTreeNode() { + protected RdcTreeNode() + { AllSettingsGroups = new List(); InitSettings(); } - protected virtual void InitSettings() { + protected virtual void InitSettings() + { LogonCredentials = new LogonCredentials(); ConnectionSettings = new ConnectionSettings(); GatewaySettings = new GatewaySettings(); @@ -102,62 +116,83 @@ protected virtual void InitSettings() { LocalResourceSettings = new LocalResourcesSettings(); SecuritySettings = new SecuritySettings(); if (Properties != null) + { AllSettingsGroups.Add(Properties); - + } AllSettingsGroups.AddRange(new SettingsGroup[7] { LogonCredentials, ConnectionSettings, GatewaySettings, RemoteDesktopSettings, LocalResourceSettings, DisplaySettings, SecuritySettings }); } - internal void CopySettings(RdcTreeNode node, Type excludeType) { - for (int i = 0; i < AllSettingsGroups.Count; i++) { + internal void CopySettings(RdcTreeNode node, Type excludeType) + { + for (int i = 0; i < AllSettingsGroups.Count; i++) + { SettingsGroup settingsGroup = AllSettingsGroups[i]; - if (!(settingsGroup.GetType() == excludeType)) { + if (!(settingsGroup.GetType() == excludeType)) + { AllSettingsGroups[i].InheritSettingsType.Mode = node.AllSettingsGroups[i].InheritSettingsType.Mode; AllSettingsGroups[i].Copy(node.AllSettingsGroups[i]); } } } - internal SettingsGroup GetSettingsGroupByName(string name) { + internal SettingsGroup GetSettingsGroupByName(string name) + { return AllSettingsGroups.Where((SettingsGroup sg) => sg.Name.Equals(name)).FirstOrDefault(); } internal abstract void WriteXml(XmlTextWriter tw); - protected void WriteXmlSettingsGroups(XmlTextWriter tw) { - foreach (SettingsGroup allSettingsGroup in AllSettingsGroups) { + protected void WriteXmlSettingsGroups(XmlTextWriter tw) + { + foreach (SettingsGroup allSettingsGroup in AllSettingsGroups) + { allSettingsGroup.WriteXml(tw, this); } } - protected void ReadXml(Dictionary nodeActions, XmlNode xmlNode, ICollection errors) { - foreach (XmlNode childNode in xmlNode.ChildNodes) { + protected void ReadXml(Dictionary nodeActions, XmlNode xmlNode, ICollection errors) + { + foreach (XmlNode childNode in xmlNode.ChildNodes) + { nodeActions.TryGetValue(childNode.Name, out var value); - try { + try + { if (value != null) + { value(childNode, this, errors); + } else + { ReadXmlSettingsGroup(childNode, errors); + } } - catch (Exception ex) { + catch (Exception ex) + { errors.Add("ڡ{1}жȡ Xml ڵ {0} ʱ쳣{2}".InvariantFormat(childNode.GetFullPath(), base.Text, ex.Message)); } } } - protected void ReadXmlSettingsGroup(XmlNode xmlNode, ICollection errors) { + protected void ReadXmlSettingsGroup(XmlNode xmlNode, ICollection errors) + { SettingsGroup settingsGroup = AllSettingsGroups.Where((SettingsGroup i) => xmlNode.Name == i.XmlNodeName).FirstOrDefault(); - if (settingsGroup != null) { + if (settingsGroup != null) + { settingsGroup.ReadXml(xmlNode, this, errors); return; } errors.Add("{1}г Xml ڵ {0}".InvariantFormat(xmlNode.GetFullPath(), base.Text)); } - internal virtual void UpdateSettings(NodePropertiesDialog dlg) { - if (dlg != null) { + internal virtual void UpdateSettings(NodePropertiesDialog dlg) + { + if (dlg != null) + { dlg.UpdateSettings(); if (base.TreeView != null && dlg.PropertiesPage.ParentGroup != null && base.Parent != dlg.PropertiesPage.ParentGroup) + { ServerTree.Instance.MoveNode(this, dlg.PropertiesPage.ParentGroup); + } } } @@ -189,54 +224,69 @@ internal virtual void UpdateSettings(NodePropertiesDialog dlg) { public virtual bool HandleMove(RdcTreeNode childNode) => false; - public virtual void ChangeImageIndex(ImageConstants index) { + public virtual void ChangeImageIndex(ImageConstants index) + { base.ImageIndex = (int)index; base.SelectedImageIndex = (int)ServerTree.TranslateImage(index, toSelected: true); } - public virtual void CollectNodesToInvalidate(bool recurseChildren, HashSet set) { - if (recurseChildren) { + public virtual void CollectNodesToInvalidate(bool recurseChildren, HashSet set) + { + if (recurseChildren) + { foreach (RdcTreeNode node in base.Nodes) + { node.CollectNodesToInvalidate(recurseChildren, set); + } } set.Add(this); } - public void ResetInheritance() { + public void ResetInheritance() + { _needToUpdateInheritedSettings = true; } - public virtual void InvalidateNode() { + public virtual void InvalidateNode() + { _needToUpdateInheritedSettings = true; } - public bool InheritSettings() { + public bool InheritSettings() + { bool anyInherited = false; if (!_needToUpdateInheritedSettings) + { return anyInherited; - + } foreach (SettingsGroup allSettingsGroup in AllSettingsGroups) + { allSettingsGroup.InheritSettings(this, ref anyInherited); - + } _needToUpdateInheritedSettings = false; return anyInherited; } - public void DoConnectAs() { + public void DoConnectAs() + { RdcTreeNode rdcTreeNode = this; if (rdcTreeNode is ServerRef serverRef) + { rdcTreeNode = serverRef.ServerNode; - + } using ConnectAsDialog connectAsDialog = ConnectAsDialog.NewConnectAsDialog(rdcTreeNode, Program.TheForm); - if (connectAsDialog.ShowDialog() == DialogResult.OK) { + if (connectAsDialog.ShowDialog() == DialogResult.OK) + { connectAsDialog.UpdateSettings(); ConnectAs(connectAsDialog.LogonCredentials, connectAsDialog.ConnectionSettings); } } - public virtual bool AllowEdit(bool popUI) { + public virtual bool AllowEdit(bool popUI) + { GroupBase readOnlyParent = GetReadOnlyParent(); - if (readOnlyParent != null) { + if (readOnlyParent != null) + { if (popUI) FormTools.InformationDialog("{0} {1} ֻģܱ༭".CultureFormat((readOnlyParent == this) ? "" : "", readOnlyParent.Text)); @@ -245,43 +295,53 @@ public virtual bool AllowEdit(bool popUI) { return true; } - public CredentialsProfile LookupCredentialsProfile(ILogonCredentials logonCredentials) { + public CredentialsProfile LookupCredentialsProfile(ILogonCredentials logonCredentials) + { CredentialsStore credentialsProfiles = Program.CredentialsProfiles; if (logonCredentials.ProfileScope == ProfileScope.File) - + { credentialsProfiles = FileGroup.CredentialsProfiles; - + } credentialsProfiles.TryGetValue(logonCredentials.ProfileName, out var profile); return profile; } - internal void ResolveCredentials() { + internal void ResolveCredentials() + { ResolveAndFixCredentials(LogonCredentials); ResolveAndFixCredentials(GatewaySettings); } - internal bool ResolveCredentials(LogonCredentials logonCredentials) { - if (logonCredentials.ProfileName.Scope == ProfileScope.Local) { + internal bool ResolveCredentials(LogonCredentials logonCredentials) + { + if (logonCredentials.ProfileName.Scope == ProfileScope.Local) + { if (!LogonCredentials.IsCustomProfile(logonCredentials.ProfileName.Value)) + { logonCredentials.ProfileName.Value = "Custom"; - + } return true; } CredentialsProfile credentialsProfile = LookupCredentialsProfile(logonCredentials); - if (credentialsProfile != null) { + if (credentialsProfile != null) + { logonCredentials.UserName.Value = credentialsProfile.UserName; logonCredentials.Domain.Value = credentialsProfile.Domain; if (credentialsProfile.IsDecrypted) + { logonCredentials.Password.SetPlainText(credentialsProfile.Password.Value); - + } return true; } return false; } - private void ResolveAndFixCredentials(LogonCredentials logonCredentials) { + private void ResolveAndFixCredentials(LogonCredentials logonCredentials) + { if (logonCredentials != null && !ResolveCredentials(logonCredentials)) + { logonCredentials.ProfileName.Reset(); + } } } } diff --git a/RdcMan/RdgFile.cs b/RdcMan/RdgFile.cs index b1623f2..9fbc7af 100644 --- a/RdcMan/RdgFile.cs +++ b/RdcMan/RdgFile.cs @@ -7,8 +7,10 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { - internal static class RdgFile { +namespace RdcMan +{ + internal static class RdgFile + { private const int CurrentSchemaVersion = 3; private const string RDCManFileFilter = "RDCMan Groups (*.rdg)|*.rdg"; @@ -19,7 +21,8 @@ internal static class RdgFile { private static string CurrentWorkingDirectory; - public static FileGroup NewFile() { + public static FileGroup NewFile() + { using SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Title = "½ļ"; saveFileDialog.Filter = RDCManFileFilter; @@ -27,7 +30,8 @@ public static FileGroup NewFile() { saveFileDialog.CheckPathExists = true; saveFileDialog.InitialDirectory = GetWorkingDirectory(); saveFileDialog.RestoreDirectory = false; - if (saveFileDialog.ShowDialog() != DialogResult.OK) { + if (saveFileDialog.ShowDialog() != DialogResult.OK) + { return null; } FileGroup fileGroup = new FileGroup(saveFileDialog.FileName); @@ -36,7 +40,8 @@ public static FileGroup NewFile() { return fileGroup; } - public static void CloseFileGroup(FileGroup file) { + public static void CloseFileGroup(FileGroup file) + { file.AnyOrAllConnected(out var anyConnected, out var _); if (anyConnected) { DialogResult dialogResult = FormTools.YesNoDialog(" " + file.Text + " ĻӡȷҪر"); @@ -49,7 +54,8 @@ public static void CloseFileGroup(FileGroup file) { } } - public static FileGroup OpenFile() { + public static FileGroup OpenFile() + { using OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Title = ""; openFileDialog.DefaultExt = "rdg"; @@ -65,59 +71,75 @@ public static FileGroup OpenFile() { return OpenFile(openFileDialog.FileName); } - public static FileGroup OpenFile(string filename) { - using (Helpers.Timer("reading {0}", filename)) { + public static FileGroup OpenFile(string filename) + { + using (Helpers.Timer("reading {0}", filename)) + { XmlDocument xmlDocument = new XmlDocument(); XmlTextReader xmlTextReader = null; XmlNode topNode; - try { - xmlTextReader = new XmlTextReader(filename) { + try + { + xmlTextReader = new XmlTextReader(filename) + { DtdProcessing = DtdProcessing.Ignore }; xmlTextReader.WhitespaceHandling = WhitespaceHandling.None; xmlTextReader.MoveToContent(); topNode = xmlDocument.ReadNode(xmlTextReader); } - catch (Exception ex) { + catch (Exception ex) + { FormTools.ErrorDialog(ex.Message); return null; } - finally { + finally + { xmlTextReader?.Close(); } - if (topNode == null) { + if (topNode == null) + { throw new FileLoadException(filename + ": ļʽ"); } FileGroup fileGroup = new FileGroup(filename); FileGroup fileGroup2 = (from f in ServerTree.Instance.Nodes.OfType() - where f.Pathname.Equals(fileGroup.Pathname, StringComparison.OrdinalIgnoreCase) - select f).FirstOrDefault(); - if (fileGroup2 != null) { + where f.Pathname.Equals(fileGroup.Pathname, StringComparison.OrdinalIgnoreCase) + select f).FirstOrDefault(); + if (fileGroup2 != null) + { FormTools.InformationDialog("{0} Ϊ{1}".CultureFormat(fileGroup.Pathname, fileGroup2.Text)); return fileGroup2; } - try { + try + { List errors = new List(); - ServerTree.Instance.Operation(OperationBehavior.RestoreSelected | OperationBehavior.SuspendSort | OperationBehavior.SuspendUpdate | OperationBehavior.SuspendGroupChanged, delegate { + ServerTree.Instance.Operation(OperationBehavior.RestoreSelected | OperationBehavior.SuspendSort | OperationBehavior.SuspendUpdate | OperationBehavior.SuspendGroupChanged, delegate + { ServerTree.Instance.AddNode(fileGroup, ServerTree.Instance.RootNode); - if (!ReadXml(topNode, fileGroup, errors)) { + if (!ReadXml(topNode, fileGroup, errors)) + { throw new Exception(string.Empty); } }); - if (errors.Count > 0) { + if (errors.Count > 0) + { StringBuilder stringBuilder = new StringBuilder("´").AppendLine().AppendLine(); - foreach (string item in errors) { + foreach (string item in errors) + { stringBuilder.AppendLine(item); } stringBuilder.AppendLine().Append("ļδȫء棬϶ζŶʧϢǷ"); DialogResult dialogResult = FormTools.ExclamationDialog(stringBuilder.ToString(), MessageBoxButtons.YesNo); - if (dialogResult == DialogResult.No) { + if (dialogResult == DialogResult.No) + { throw new Exception(string.Empty); } } - using (Helpers.Timer("sorting root, builtin groups and file")) { + using (Helpers.Timer("sorting root, builtin groups and file")) + { ServerTree.Instance.SortRoot(); - foreach (GroupBase builtInVirtualGroup in Program.BuiltInVirtualGroups) { + foreach (GroupBase builtInVirtualGroup in Program.BuiltInVirtualGroups) + { ServerTree.Instance.SortGroup(builtInVirtualGroup); ServerTree.Instance.OnGroupChanged(builtInVirtualGroup, ChangeType.TreeChanged); } @@ -125,22 +147,27 @@ where f.Pathname.Equals(fileGroup.Pathname, StringComparison.OrdinalIgnoreCase) ServerTree.Instance.OnGroupChanged(fileGroup, ChangeType.TreeChanged); } SmartGroup.RefreshAll(fileGroup); - fileGroup.VisitNodes(delegate (RdcTreeNode node) { - if (node is GroupBase groupBase && groupBase.Properties.Expanded.Value) { + fileGroup.VisitNodes(delegate(RdcTreeNode node) + { + if (node is GroupBase groupBase && groupBase.Properties.Expanded.Value) + { groupBase.Expand(); } }); Encryption.DecryptPasswords(); fileGroup.CheckCredentials(); - fileGroup.VisitNodes(delegate (RdcTreeNode n) { + fileGroup.VisitNodes(delegate(RdcTreeNode n) + { n.ResetInheritance(); }); fileGroup.HasChangedSinceWrite = false; Program.Preferences.NeedToSave = true; return fileGroup; } - catch (Exception ex2) { - if (!string.IsNullOrEmpty(ex2.Message)) { + catch (Exception ex2) + { + if (!string.IsNullOrEmpty(ex2.Message)) + { FormTools.ErrorDialog(ex2.Message); } ServerTree.Instance.RemoveNode(fileGroup); @@ -149,19 +176,26 @@ where f.Pathname.Equals(fileGroup.Pathname, StringComparison.OrdinalIgnoreCase) } } - private static bool ReadXml(XmlNode topNode, FileGroup fileGroup, ICollection errors) { + private static bool ReadXml(XmlNode topNode, FileGroup fileGroup, ICollection errors) + { string text = "unknown"; int num = 0; - try { + try + { XmlNode namedItem = topNode.Attributes.GetNamedItem("programVersion"); text = namedItem.InnerText; } - catch { } - try { + catch + { + } + try + { XmlNode namedItem2 = topNode.Attributes.GetNamedItem("schemaVersion"); num = int.Parse(namedItem2.InnerText); } - catch { } + catch + { + } fileGroup.SchemaVersion = num; if (num > CurrentSchemaVersion) { DialogResult dialogResult = FormTools.YesNoDialog("{0} ɽ°汾 RDCMan ({1}) д޷ȷءȷʵ˲ұ˰汾棬ָɵļģʽܻᶪʧϢǷ".CultureFormat(fileGroup.GetFilename(), text)); @@ -170,21 +204,28 @@ private static bool ReadXml(XmlNode topNode, FileGroup fileGroup, ICollection nodeActions = new Dictionary(); - nodeActions["file"] = delegate (XmlNode childNode, RdcTreeNode group, ICollection errors2) { + nodeActions["file"] = delegate(XmlNode childNode, RdcTreeNode group, ICollection errors2) + { (group as GroupBase).ReadXml(childNode, errors2); }; - foreach (IBuiltInVirtualGroup virtualGroup in Program.BuiltInVirtualGroups.Where((IBuiltInVirtualGroup v) => !string.IsNullOrEmpty(v.XmlNodeName))) { - nodeActions[virtualGroup.XmlNodeName] = delegate (XmlNode childNode, RdcTreeNode group, ICollection errors2) { + foreach (IBuiltInVirtualGroup virtualGroup in Program.BuiltInVirtualGroups.Where((IBuiltInVirtualGroup v) => !string.IsNullOrEmpty(v.XmlNodeName))) + { + nodeActions[virtualGroup.XmlNodeName] = delegate(XmlNode childNode, RdcTreeNode group, ICollection errors2) + { virtualGroup.ReadXml(childNode, fileGroup, errors2); }; } - nodeActions["version"] = delegate { + nodeActions["version"] = delegate + { }; - LongRunningActionForm.PerformOperation(" " + fileGroup.Pathname, showImmediately: false, delegate { - foreach (XmlNode childNode in topNode.ChildNodes) { + LongRunningActionForm.PerformOperation(" " + fileGroup.Pathname, showImmediately: false, delegate + { + foreach (XmlNode childNode in topNode.ChildNodes) + { if (nodeActions.TryGetValue(childNode.Name, out var value)) value(childNode, fileGroup, errors); else @@ -194,56 +235,77 @@ private static bool ReadXml(XmlNode topNode, FileGroup fileGroup, ICollection()) { - if (!conditional || item.HasChangedSinceWrite) { + private static SaveResult DoSaveAll(bool conditional) + { + foreach (FileGroup item in ServerTree.Instance.Nodes.OfType()) + { + if (!conditional || item.HasChangedSinceWrite) + { SaveResult saveResult = DoSaveWithRetry(item); if (saveResult == SaveResult.Cancel) + { return saveResult; + } } } return SaveResult.Save; } - public static SaveResult DoSaveWithRetry(FileGroup file) { + public static SaveResult DoSaveWithRetry(FileGroup file) + { if (!file.AllowEdit(popUI: false)) + { return SaveResult.NoSave; - while (true) { + } + while (true) + { SaveResult saveResult = SaveFile(file); - switch (saveResult) { - case SaveResult.Retry: - break; - case SaveResult.Cancel: - return saveResult; - default: - return SaveResult.Save; + switch (saveResult) + { + case SaveResult.Retry: + break; + case SaveResult.Cancel: + return saveResult; + default: + return SaveResult.Save; } } } - public static SaveResult SaveAs(FileGroup file) { + public static SaveResult SaveAs(FileGroup file) + { using SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Title = ""; saveFileDialog.Filter = RDCManFileFilter; @@ -253,25 +315,30 @@ public static SaveResult SaveAs(FileGroup file) { saveFileDialog.InitialDirectory = Path.GetDirectoryName(file.Pathname); saveFileDialog.RestoreDirectory = false; SaveResult saveResult; - do { - switch (saveFileDialog.ShowDialog()) { - case DialogResult.Cancel: - return SaveResult.Cancel; - default: - return SaveResult.NoSave; - case DialogResult.OK: - break; + do + { + switch (saveFileDialog.ShowDialog()) + { + case DialogResult.Cancel: + return SaveResult.Cancel; + default: + return SaveResult.NoSave; + case DialogResult.OK: + break; } file.Pathname = Path.Combine(Directory.GetCurrentDirectory(), saveFileDialog.FileName); saveResult = SaveFile(file); - } while (saveResult == SaveResult.Retry); + } + while (saveResult == SaveResult.Retry); return saveResult; } - private static SaveResult SaveFile(FileGroup fileGroup) { + private static SaveResult SaveFile(FileGroup fileGroup) + { string temporaryFileName = Helpers.GetTemporaryFileName(fileGroup.Pathname, ".new"); XmlTextWriter xmlTextWriter = null; - try { + try + { xmlTextWriter = new XmlTextWriter(temporaryFileName, Encoding.UTF8); xmlTextWriter.Formatting = Formatting.Indented; xmlTextWriter.Indentation = 2; @@ -280,7 +347,8 @@ private static SaveResult SaveFile(FileGroup fileGroup) { xmlTextWriter.WriteAttributeString("programVersion", Program.TheForm.VersionText); xmlTextWriter.WriteAttributeString("schemaVersion", CurrentSchemaVersion.ToString()); fileGroup.WriteXml(xmlTextWriter); - foreach (IBuiltInVirtualGroup item in Program.BuiltInVirtualGroups.Where((IBuiltInVirtualGroup v) => !string.IsNullOrEmpty(v.XmlNodeName))) { + foreach (IBuiltInVirtualGroup item in Program.BuiltInVirtualGroups.Where((IBuiltInVirtualGroup v) => !string.IsNullOrEmpty(v.XmlNodeName))) + { item.WriteXml(xmlTextWriter, fileGroup); } xmlTextWriter.WriteEndElement(); @@ -292,7 +360,8 @@ private static SaveResult SaveFile(FileGroup fileGroup) { fileGroup.HasChangedSinceWrite = false; return SaveResult.Save; } - catch (Exception ex) { + catch (Exception ex) + { xmlTextWriter?.Close(); return FormTools.YesNoCancelDialog(ex.Message + "\n\nһΣѡȡԭʼļ") switch { DialogResult.Cancel => SaveResult.Cancel, @@ -302,19 +371,25 @@ private static SaveResult SaveFile(FileGroup fileGroup) { } } - public static bool AutoSave() { + public static bool AutoSave() + { if (Interlocked.CompareExchange(ref _saveInProgress, 1, 0) == 1) + { return false; - try { + } + try + { DoSaveAll(conditional: true); } - finally { + finally + { _saveInProgress = 0; } return true; } - public static SaveResult ShouldSaveFile(FileGroup file) { + public static SaveResult ShouldSaveFile(FileGroup file) + { if (!file.AllowEdit(popUI: false)) return SaveResult.NoSave; if (Program.Preferences.AutoSaveFiles) @@ -329,10 +404,13 @@ public static SaveResult ShouldSaveFile(FileGroup file) { }; } - private static string GetWorkingDirectory() { + private static string GetWorkingDirectory() + { FileGroup selectedFile = ServerTree.Instance.GetSelectedFile(); if (selectedFile != null) + { return selectedFile.GetDirectory(); + } return CurrentWorkingDirectory ?? Environment.GetFolderPath(Environment.SpecialFolder.Personal); } } diff --git a/RdcMan/RdpClient.cs b/RdcMan/RdpClient.cs index f9be99b..eb2cdbc 100644 --- a/RdcMan/RdpClient.cs +++ b/RdcMan/RdpClient.cs @@ -4,44 +4,53 @@ using AxMSTSCLib; using MSTSCLib; -namespace RdcMan { - public class RdpClient { - public enum ConnectionState { +namespace RdcMan +{ + public class RdpClient + { + public enum ConnectionState + { Disconnected, Connecting, Connected } - public enum ConnectionBarState { + public enum ConnectionBarState + { AutoHide, Pinned, Off } - public enum AudioRedirectionMode { + public enum AudioRedirectionMode + { Client, Remote, NoSound } - public enum AudioRedirectionQuality { + public enum AudioRedirectionQuality + { Dynamic, High, Medium } - public enum AudioCaptureRedirectionMode { + public enum AudioCaptureRedirectionMode + { DoNotRecord, Record } - public enum KeyboardHookMode { + public enum KeyboardHookMode + { Client, Remote, FullScreenClient } - public enum GatewayUsageMethod { + public enum GatewayUsageMethod + { NoneDirect, ProxyDirect, ProxyDetect, @@ -49,19 +58,22 @@ public enum GatewayUsageMethod { NoneDetect } - public enum GatewayLogonMethod { + public enum GatewayLogonMethod + { NTLM = 0, SmartCard = 1, Any = 4 } - public enum AuthenticationLevel { + public enum AuthenticationLevel + { None, Required, Warn } - public enum SmartSizeMethod { + public enum SmartSizeMethod + { None, Scale, Reconnect @@ -129,33 +141,43 @@ public enum SmartSizeMethod { private RdpClient9 _rdpClient9; - //private RdpClient10 _rdpClient10; + private RdpClient10 _rdpClient10; - public Size DesktopSize { - get { + public Size DesktopSize + { + get + { return new Size(MsRdpClient.DesktopWidth, MsRdpClient.DesktopHeight); } - set { + set + { MsRdpClient.DesktopHeight = Math.Min(MaxDesktopHeight, value.Height); MsRdpClient.DesktopWidth = Math.Min(MaxDesktopWidth, value.Width); } } - public Control Control { - get { - //if (_rdpClient10 != null) { - // return _rdpClient10; - //} - if (_rdpClient9 != null) { + public Control Control + { + get + { + if (_rdpClient10 != null) + { + return _rdpClient10; + } + if (_rdpClient9 != null) + { return _rdpClient9; } - if (_rdpClient8 != null) { + if (_rdpClient8 != null) + { return _rdpClient8; } - if (_rdpClient7 != null) { + if (_rdpClient7 != null) + { return _rdpClient7; } - if (_rdpClient6 != null) { + if (_rdpClient6 != null) + { return _rdpClient6; } return _rdpClient5; @@ -164,102 +186,136 @@ public Control Control { public IMsRdpClient MsRdpClient => GetOcx() as IMsRdpClient; - public IMsRdpClientAdvancedSettings AdvancedSettings2 { - get { - //if (_rdpClient10 != null) { - // return _rdpClient10.AdvancedSettings2; - //} - if (_rdpClient9 != null) { + public IMsRdpClientAdvancedSettings AdvancedSettings2 + { + get + { + if (_rdpClient10 != null) + { + return _rdpClient10.AdvancedSettings2; + } + if (_rdpClient9 != null) + { return _rdpClient9.AdvancedSettings2; } - if (_rdpClient8 != null) { + if (_rdpClient8 != null) + { return _rdpClient8.AdvancedSettings2; } - if (_rdpClient7 != null) { + if (_rdpClient7 != null) + { return _rdpClient7.AdvancedSettings2; } - if (_rdpClient6 != null) { + if (_rdpClient6 != null) + { return _rdpClient6.AdvancedSettings2; } return _rdpClient5.AdvancedSettings2; } } - public IMsRdpClientAdvancedSettings4 AdvancedSettings5 { - get { - //if (_rdpClient10 != null) { - // return _rdpClient10.AdvancedSettings5; - //} - if (_rdpClient9 != null) { + public IMsRdpClientAdvancedSettings4 AdvancedSettings5 + { + get + { + if (_rdpClient10 != null) + { + return _rdpClient10.AdvancedSettings5; + } + if (_rdpClient9 != null) + { return _rdpClient9.AdvancedSettings5; } - if (_rdpClient8 != null) { + if (_rdpClient8 != null) + { return _rdpClient8.AdvancedSettings5; } - if (_rdpClient7 != null) { + if (_rdpClient7 != null) + { return _rdpClient7.AdvancedSettings5; } - if (_rdpClient6 != null) { + if (_rdpClient6 != null) + { return _rdpClient6.AdvancedSettings5; } return _rdpClient5.AdvancedSettings5; } } - public IMsRdpClientAdvancedSettings5 AdvancedSettings6 { - get { - //if (_rdpClient10 != null) { - // return _rdpClient10.AdvancedSettings6; - //} - if (_rdpClient9 != null) { + public IMsRdpClientAdvancedSettings5 AdvancedSettings6 + { + get + { + if (_rdpClient10 != null) + { + return _rdpClient10.AdvancedSettings6; + } + if (_rdpClient9 != null) + { return _rdpClient9.AdvancedSettings6; } - if (_rdpClient8 != null) { + if (_rdpClient8 != null) + { return _rdpClient8.AdvancedSettings6; } - if (_rdpClient7 != null) { + if (_rdpClient7 != null) + { return _rdpClient7.AdvancedSettings6; } - if (_rdpClient6 != null) { + if (_rdpClient6 != null) + { return _rdpClient6.AdvancedSettings6; } return _rdpClient5.AdvancedSettings6; } } - public IMsRdpClientAdvancedSettings6 AdvancedSettings7 { - get { - //if (_rdpClient10 != null) { - // return _rdpClient10.AdvancedSettings7; - //} - if (_rdpClient9 != null) { + public IMsRdpClientAdvancedSettings6 AdvancedSettings7 + { + get + { + if (_rdpClient10 != null) + { + return _rdpClient10.AdvancedSettings7; + } + if (_rdpClient9 != null) + { return _rdpClient9.AdvancedSettings7; } - if (_rdpClient8 != null) { + if (_rdpClient8 != null) + { return _rdpClient8.AdvancedSettings7; } - if (_rdpClient7 != null) { + if (_rdpClient7 != null) + { return _rdpClient7.AdvancedSettings7; } - if (_rdpClient6 != null) { + if (_rdpClient6 != null) + { return _rdpClient6.AdvancedSettings7; } return null; } } - public IMsRdpClientAdvancedSettings7 AdvancedSettings8 { - get { - //if (_rdpClient10 != null) { - // return _rdpClient10.AdvancedSettings8; - //} - if (_rdpClient9 != null) { + public IMsRdpClientAdvancedSettings7 AdvancedSettings8 + { + get + { + if (_rdpClient10 != null) + { + return _rdpClient10.AdvancedSettings8; + } + if (_rdpClient9 != null) + { return _rdpClient9.AdvancedSettings8; } - if (_rdpClient8 != null) { + if (_rdpClient8 != null) + { return _rdpClient8.AdvancedSettings8; } - if (_rdpClient7 != null) { + if (_rdpClient7 != null) + { return _rdpClient7.AdvancedSettings8; } return null; @@ -270,105 +326,140 @@ public IMsRdpClientAdvancedSettings7 AdvancedSettings8 { public IMsRdpClient8 MsRdpClient8 => MsRdpClient as IMsRdpClient8; - public IMsRdpClientTransportSettings TransportSettings { - get { - //if (_rdpClient10 != null) { - // return _rdpClient10.TransportSettings; - //} - if (_rdpClient9 != null) { + public IMsRdpClientTransportSettings TransportSettings + { + get + { + if (_rdpClient10 != null) + { + return _rdpClient10.TransportSettings; + } + if (_rdpClient9 != null) + { return _rdpClient9.TransportSettings; } - if (_rdpClient8 != null) { + if (_rdpClient8 != null) + { return _rdpClient8.TransportSettings; } - if (_rdpClient7 != null) { + if (_rdpClient7 != null) + { return _rdpClient7.TransportSettings; } - if (_rdpClient6 != null) { + if (_rdpClient6 != null) + { return _rdpClient6.TransportSettings; } return _rdpClient5.TransportSettings; } } - public IMsRdpClientTransportSettings2 TransportSettings2 { - get { - //if (_rdpClient10 != null) { - // return _rdpClient10.TransportSettings2; - //} - if (_rdpClient9 != null) { + public IMsRdpClientTransportSettings2 TransportSettings2 + { + get + { + if (_rdpClient10 != null) + { + return _rdpClient10.TransportSettings2; + } + if (_rdpClient9 != null) + { return _rdpClient9.TransportSettings2; } - if (_rdpClient8 != null) { + if (_rdpClient8 != null) + { return _rdpClient8.TransportSettings2; } - if (_rdpClient7 != null) { + if (_rdpClient7 != null) + { return _rdpClient7.TransportSettings2; } - if (_rdpClient6 != null) { + if (_rdpClient6 != null) + { return _rdpClient6.TransportSettings2; } return null; } } - public IMsTscSecuredSettings SecuredSettings { - get { - //if (_rdpClient10 != null) { - // return _rdpClient10.SecuredSettings; - //} - if (_rdpClient9 != null) { + public IMsTscSecuredSettings SecuredSettings + { + get + { + if (_rdpClient10 != null) + { + return _rdpClient10.SecuredSettings; + } + if (_rdpClient9 != null) + { return _rdpClient9.SecuredSettings; } - if (_rdpClient8 != null) { + if (_rdpClient8 != null) + { return _rdpClient8.SecuredSettings; } - if (_rdpClient7 != null) { + if (_rdpClient7 != null) + { return _rdpClient7.SecuredSettings; } - if (_rdpClient6 != null) { + if (_rdpClient6 != null) + { return _rdpClient6.SecuredSettings; } return _rdpClient5.SecuredSettings; } } - public IMsRdpClientSecuredSettings SecuredSettings2 { - get { - //if (_rdpClient10 != null) { - // return _rdpClient10.SecuredSettings2; - //} - if (_rdpClient9 != null) { + public IMsRdpClientSecuredSettings SecuredSettings2 + { + get + { + if (_rdpClient10 != null) + { + return _rdpClient10.SecuredSettings2; + } + if (_rdpClient9 != null) + { return _rdpClient9.SecuredSettings2; } - if (_rdpClient8 != null) { + if (_rdpClient8 != null) + { return _rdpClient8.SecuredSettings2; } - if (_rdpClient7 != null) { + if (_rdpClient7 != null) + { return _rdpClient7.SecuredSettings2; } - if (_rdpClient6 != null) { + if (_rdpClient6 != null) + { return _rdpClient6.SecuredSettings2; } return _rdpClient5.SecuredSettings2; } } - public ITSRemoteProgram RemoteProgram { - get { - //if (_rdpClient10 != null) { - // return _rdpClient10.RemoteProgram; - //} - if (_rdpClient9 != null) { + public ITSRemoteProgram RemoteProgram + { + get + { + if (_rdpClient10 != null) + { + return _rdpClient10.RemoteProgram; + } + if (_rdpClient9 != null) + { return _rdpClient9.RemoteProgram; } - if (_rdpClient8 != null) { + if (_rdpClient8 != null) + { return _rdpClient8.RemoteProgram; } - if (_rdpClient7 != null) { + if (_rdpClient7 != null) + { return _rdpClient7.RemoteProgram; } - if (_rdpClient6 != null) { + if (_rdpClient6 != null) + { return _rdpClient6.RemoteProgram; } return _rdpClient5.RemoteProgram; @@ -449,53 +540,64 @@ public static string SmartSizeMethodToString(SmartSizeMethod method) { }; } - private RdpClient(MainForm form) { - switch (RdpClientVersion) { - //case 10: - // _rdpClient10 = new RdpClient10(form); - // break; - case 9: - _rdpClient9 = new RdpClient9(form); - break; - case 8: - _rdpClient8 = new RdpClient8(form); - break; - case 7: - _rdpClient7 = new RdpClient7(form); - break; - case 6: - _rdpClient6 = new RdpClient6(form); - break; - default: - _rdpClient5 = new RdpClient5(form); - break; - } - } - - internal static void Initialize(MainForm form) { - using (RdpClient5 rdpClient = new RdpClient5(form)) { + private RdpClient(MainForm form) + { + switch (RdpClientVersion) + { + case 10: + _rdpClient10 = new RdpClient10(form); + break; + case 9: + _rdpClient9 = new RdpClient9(form); + break; + case 8: + _rdpClient8 = new RdpClient8(form); + break; + case 7: + _rdpClient7 = new RdpClient7(form); + break; + case 6: + _rdpClient6 = new RdpClient6(form); + break; + default: + _rdpClient5 = new RdpClient5(form); + break; + } + } + + internal static void Initialize(MainForm form) + { + using (RdpClient5 rdpClient = new RdpClient5(form)) + { RdpControlVersion = rdpClient.Version; string[] array = rdpClient.Version.Split('.'); int num = int.Parse(array[2]); - if (num >= 10240) { + if (num >= 10240) + { RdpClientVersion = 9; } - else if (num >= 9600) { + else if (num >= 9600) + { RdpClientVersion = 9; } - else if (num >= 9200) { + else if (num >= 9200) + { RdpClientVersion = 8; } - else if (num >= 7600) { + else if (num >= 7600) + { RdpClientVersion = 7; } - else if (num >= 6001) { + else if (num >= 6001) + { RdpClientVersion = 6; } - else { + else + { RdpClientVersion = 5; } - if (RdpClientVersion >= 6) { + if (RdpClientVersion >= 6) + { SupportsMonitorSpanning = true; } form.RemoveFromClientPanel(rdpClient); @@ -505,124 +607,152 @@ internal static void Initialize(MainForm form) { staticClient.Control.Enabled = false; MaxDesktopWidth = 4096; MaxDesktopHeight = 2048; - if (staticClient.AdvancedSettings7 != null) { + if (staticClient.AdvancedSettings7 != null) + { SupportsGatewayCredentials = true; } - if (staticClient.AdvancedSettings8 != null) { + if (staticClient.AdvancedSettings8 != null) + { SupportsAdvancedAudioVideoRedirection = true; } - if (staticClient.ClientNonScriptable3 != null) { + if (staticClient.ClientNonScriptable3 != null) + { SupportsFineGrainedRedirection = true; } - if (staticClient.MsRdpClient8 != null) { + if (staticClient.MsRdpClient8 != null) + { SupportsRemoteSessionActions = true; } } - internal static RdpClient AllocClient(Server server, MainForm form) { + internal static RdpClient AllocClient(Server server, MainForm form) + { RdpClient rdpClient = new RdpClient(form); rdpClient._server = server; return rdpClient; } - internal static void ReleaseClient(RdpClient client) { - try { + internal static void ReleaseClient(RdpClient client) + { + try + { client._server = null; Program.TheForm.RemoveFromClientPanel(client.Control); } - finally { + finally + { AxHost rdpClient = client._rdpClient5; - if (rdpClient != null) { + if (rdpClient != null) + { client._rdpClient5 = null; rdpClient.Dispose(); } rdpClient = client._rdpClient6; - if (rdpClient != null) { + if (rdpClient != null) + { client._rdpClient6 = null; rdpClient.Dispose(); } rdpClient = client._rdpClient7; - if (rdpClient != null) { + if (rdpClient != null) + { client._rdpClient7 = null; rdpClient.Dispose(); } rdpClient = client._rdpClient8; - if (rdpClient != null) { + if (rdpClient != null) + { client._rdpClient8 = null; rdpClient.Dispose(); } rdpClient = client._rdpClient9; - if (rdpClient != null) { + if (rdpClient != null) + { client._rdpClient9 = null; rdpClient.Dispose(); } - //rdpClient = client._rdpClient10; - //if (rdpClient != null) { - // client._rdpClient10 = null; - // rdpClient.Dispose(); - //} + rdpClient = client._rdpClient10; + if (rdpClient != null) + { + client._rdpClient10 = null; + rdpClient.Dispose(); + } } } - public void SetText() { - //if (_rdpClient10 != null) { - // _rdpClient10.ConnectingText = _server.ConnectingText; - // _rdpClient10.DisconnectedText = _server.DisconnectedText; - //} - //else - if (_rdpClient9 != null) { + public void SetText() + { + if (_rdpClient10 != null) + { + _rdpClient10.ConnectingText = _server.ConnectingText; + _rdpClient10.DisconnectedText = _server.DisconnectedText; + } + else if (_rdpClient9 != null) + { _rdpClient9.ConnectingText = _server.ConnectingText; _rdpClient9.DisconnectedText = _server.DisconnectedText; } - else if (_rdpClient8 != null) { + else if (_rdpClient8 != null) + { _rdpClient8.ConnectingText = _server.ConnectingText; _rdpClient8.DisconnectedText = _server.DisconnectedText; } - else if (_rdpClient7 != null) { + else if (_rdpClient7 != null) + { _rdpClient7.ConnectingText = _server.ConnectingText; _rdpClient7.DisconnectedText = _server.DisconnectedText; } - else if (_rdpClient6 != null) { + else if (_rdpClient6 != null) + { _rdpClient6.ConnectingText = _server.ConnectingText; _rdpClient6.DisconnectedText = _server.DisconnectedText; } - else { + else + { _rdpClient5.ConnectingText = _server.ConnectingText; _rdpClient5.DisconnectedText = _server.DisconnectedText; } } - public object GetOcx() { - //if (_rdpClient10 != null) { - // return _rdpClient10.GetOcx(); - //} - if (_rdpClient9 != null) { + public object GetOcx() + { + if (_rdpClient10 != null) + { + return _rdpClient10.GetOcx(); + } + if (_rdpClient9 != null) + { return _rdpClient9.GetOcx(); } - if (_rdpClient8 != null) { + if (_rdpClient8 != null) + { return _rdpClient8.GetOcx(); } - if (_rdpClient7 != null) { + if (_rdpClient7 != null) + { return _rdpClient7.GetOcx(); } - if (_rdpClient6 != null) { + if (_rdpClient6 != null) + { return _rdpClient6.GetOcx(); } return _rdpClient5.GetOcx(); } - public void ConnectConnectionHandlers(EventHandler onConnected, EventHandler onConnecting, AxMSTSCLib.IMsTscAxEvents_OnDisconnectedEventHandler onDisconnected, AxMSTSCLib.IMsTscAxEvents_OnAutoReconnectingEventHandler onAutoReconnecting, AxMSTSCLib.IMsTscAxEvents_OnAutoReconnecting2EventHandler onAutoReconnecting2, EventHandler onAutoReconnected, AxMSTSCLib.IMsTscAxEvents_OnFocusReleasedEventHandler onFocusReleased) { - //if (_rdpClient10 != null) { - // _rdpClient10.OnConnected += onConnected; - // _rdpClient10.OnConnecting += onConnecting; - // _rdpClient10.OnDisconnected += onDisconnected; - // _rdpClient10.OnAutoReconnecting += onAutoReconnecting; - // _rdpClient10.OnAutoReconnecting2 += onAutoReconnecting2; - // _rdpClient10.OnAutoReconnected += onAutoReconnected; - // _rdpClient10.OnFocusReleased += onFocusReleased; - //} - //else - if (_rdpClient9 != null) { + public void ConnectConnectionHandlers(EventHandler onConnected, EventHandler onConnecting, AxMSTSCLib.IMsTscAxEvents_OnDisconnectedEventHandler onDisconnected, AxMSTSCLib.IMsTscAxEvents_OnAutoReconnectingEventHandler onAutoReconnecting, AxMSTSCLib.IMsTscAxEvents_OnAutoReconnecting2EventHandler onAutoReconnecting2, EventHandler onAutoReconnected, AxMSTSCLib.IMsTscAxEvents_OnFocusReleasedEventHandler onFocusReleased) + { + if (_rdpClient10 != null) + { + _rdpClient10.OnConnected += onConnected; + _rdpClient10.OnConnecting += onConnecting; + _rdpClient10.OnDisconnected += onDisconnected; + _rdpClient10.OnAutoReconnecting += onAutoReconnecting; + _rdpClient10.OnAutoReconnecting2 += onAutoReconnecting2; + _rdpClient10.OnAutoReconnected += onAutoReconnected; + _rdpClient10.OnFocusReleased += onFocusReleased; + } + else if (_rdpClient9 != null) + { _rdpClient9.OnConnected += onConnected; _rdpClient9.OnConnecting += onConnecting; _rdpClient9.OnDisconnected += onDisconnected; @@ -631,7 +761,8 @@ public void ConnectConnectionHandlers(EventHandler onConnected, EventHandler onC _rdpClient9.OnAutoReconnected += onAutoReconnected; _rdpClient9.OnFocusReleased += onFocusReleased; } - else if (_rdpClient8 != null) { + else if (_rdpClient8 != null) + { _rdpClient8.OnConnected += onConnected; _rdpClient8.OnConnecting += onConnecting; _rdpClient8.OnDisconnected += onDisconnected; @@ -640,7 +771,8 @@ public void ConnectConnectionHandlers(EventHandler onConnected, EventHandler onC _rdpClient8.OnAutoReconnected += onAutoReconnected; _rdpClient8.OnFocusReleased += onFocusReleased; } - else if (_rdpClient7 != null) { + else if (_rdpClient7 != null) + { _rdpClient7.OnConnected += onConnected; _rdpClient7.OnConnecting += onConnecting; _rdpClient7.OnDisconnected += onDisconnected; @@ -649,7 +781,8 @@ public void ConnectConnectionHandlers(EventHandler onConnected, EventHandler onC _rdpClient7.OnAutoReconnected += onAutoReconnected; _rdpClient7.OnFocusReleased += onFocusReleased; } - else if (_rdpClient6 != null) { + else if (_rdpClient6 != null) + { _rdpClient6.OnConnected += onConnected; _rdpClient6.OnConnecting += onConnecting; _rdpClient6.OnDisconnected += onDisconnected; @@ -658,7 +791,8 @@ public void ConnectConnectionHandlers(EventHandler onConnected, EventHandler onC _rdpClient6.OnAutoReconnected += onAutoReconnected; _rdpClient6.OnFocusReleased += onFocusReleased; } - else { + else + { _rdpClient5.OnConnected += onConnected; _rdpClient5.OnConnecting += onConnecting; _rdpClient5.OnDisconnected += onDisconnected; @@ -669,18 +803,20 @@ public void ConnectConnectionHandlers(EventHandler onConnected, EventHandler onC } } - public void DisconnectConnectionHandlers(EventHandler onConnected, EventHandler onConnecting, AxMSTSCLib.IMsTscAxEvents_OnDisconnectedEventHandler onDisconnected, AxMSTSCLib.IMsTscAxEvents_OnAutoReconnectingEventHandler onAutoReconnecting, AxMSTSCLib.IMsTscAxEvents_OnAutoReconnecting2EventHandler onAutoReconnecting2, EventHandler onAutoReconnected, AxMSTSCLib.IMsTscAxEvents_OnFocusReleasedEventHandler onFocusReleased) { - //if (_rdpClient10 != null) { - // _rdpClient10.OnConnected -= onConnected; - // _rdpClient10.OnConnecting -= onConnecting; - // _rdpClient10.OnDisconnected -= onDisconnected; - // _rdpClient10.OnAutoReconnecting -= onAutoReconnecting; - // _rdpClient10.OnAutoReconnecting2 -= onAutoReconnecting2; - // _rdpClient10.OnAutoReconnected -= onAutoReconnected; - // _rdpClient10.OnFocusReleased -= onFocusReleased; - //} - //else - if (_rdpClient9 != null) { + public void DisconnectConnectionHandlers(EventHandler onConnected, EventHandler onConnecting, AxMSTSCLib.IMsTscAxEvents_OnDisconnectedEventHandler onDisconnected, AxMSTSCLib.IMsTscAxEvents_OnAutoReconnectingEventHandler onAutoReconnecting, AxMSTSCLib.IMsTscAxEvents_OnAutoReconnecting2EventHandler onAutoReconnecting2, EventHandler onAutoReconnected, AxMSTSCLib.IMsTscAxEvents_OnFocusReleasedEventHandler onFocusReleased) + { + if (_rdpClient10 != null) + { + _rdpClient10.OnConnected -= onConnected; + _rdpClient10.OnConnecting -= onConnecting; + _rdpClient10.OnDisconnected -= onDisconnected; + _rdpClient10.OnAutoReconnecting -= onAutoReconnecting; + _rdpClient10.OnAutoReconnecting2 -= onAutoReconnecting2; + _rdpClient10.OnAutoReconnected -= onAutoReconnected; + _rdpClient10.OnFocusReleased -= onFocusReleased; + } + else if (_rdpClient9 != null) + { _rdpClient9.OnConnected -= onConnected; _rdpClient9.OnConnecting -= onConnecting; _rdpClient9.OnDisconnected -= onDisconnected; @@ -689,7 +825,8 @@ public void DisconnectConnectionHandlers(EventHandler onConnected, EventHandler _rdpClient9.OnAutoReconnected -= onAutoReconnected; _rdpClient9.OnFocusReleased -= onFocusReleased; } - else if (_rdpClient8 != null) { + else if (_rdpClient8 != null) + { _rdpClient8.OnConnected -= onConnected; _rdpClient8.OnConnecting -= onConnecting; _rdpClient8.OnDisconnected -= onDisconnected; @@ -698,7 +835,8 @@ public void DisconnectConnectionHandlers(EventHandler onConnected, EventHandler _rdpClient8.OnAutoReconnected -= onAutoReconnected; _rdpClient8.OnFocusReleased -= onFocusReleased; } - else if (_rdpClient7 != null) { + else if (_rdpClient7 != null) + { _rdpClient7.OnConnected -= onConnected; _rdpClient7.OnConnecting -= onConnecting; _rdpClient7.OnDisconnected -= onDisconnected; @@ -707,7 +845,8 @@ public void DisconnectConnectionHandlers(EventHandler onConnected, EventHandler _rdpClient7.OnAutoReconnected -= onAutoReconnected; _rdpClient7.OnFocusReleased -= onFocusReleased; } - else if (_rdpClient6 != null) { + else if (_rdpClient6 != null) + { _rdpClient6.OnConnected -= onConnected; _rdpClient6.OnConnecting -= onConnecting; _rdpClient6.OnDisconnected -= onDisconnected; @@ -716,7 +855,8 @@ public void DisconnectConnectionHandlers(EventHandler onConnected, EventHandler _rdpClient6.OnAutoReconnected -= onAutoReconnected; _rdpClient6.OnFocusReleased -= onFocusReleased; } - else { + else + { _rdpClient5.OnConnected -= onConnected; _rdpClient5.OnConnecting -= onConnecting; _rdpClient5.OnDisconnected -= onDisconnected; @@ -727,44 +867,50 @@ public void DisconnectConnectionHandlers(EventHandler onConnected, EventHandler } } - public void ConnectContainerHandlers(EventHandler onRequestGoFullScreen, EventHandler onRequestLeaveFullScreen, EventHandler onRequestContainerMinimize, AxMSTSCLib.IMsTscAxEvents_OnConfirmCloseEventHandler onConfirmClose, AxMSTSCLib.IMsTscAxEvents_OnFatalErrorEventHandler onFatalError) { - //if (_rdpClient10 != null) { - // _rdpClient10.OnRequestGoFullScreen += onRequestGoFullScreen; - // _rdpClient10.OnRequestLeaveFullScreen += onRequestLeaveFullScreen; - // _rdpClient10.OnRequestContainerMinimize += onRequestContainerMinimize; - // _rdpClient10.OnConfirmClose += onConfirmClose; - // _rdpClient10.OnFatalError += onFatalError; - //} - //else - if (_rdpClient9 != null) { + public void ConnectContainerHandlers(EventHandler onRequestGoFullScreen, EventHandler onRequestLeaveFullScreen, EventHandler onRequestContainerMinimize, AxMSTSCLib.IMsTscAxEvents_OnConfirmCloseEventHandler onConfirmClose, AxMSTSCLib.IMsTscAxEvents_OnFatalErrorEventHandler onFatalError) + { + if (_rdpClient10 != null) + { + _rdpClient10.OnRequestGoFullScreen += onRequestGoFullScreen; + _rdpClient10.OnRequestLeaveFullScreen += onRequestLeaveFullScreen; + _rdpClient10.OnRequestContainerMinimize += onRequestContainerMinimize; + _rdpClient10.OnConfirmClose += onConfirmClose; + _rdpClient10.OnFatalError += onFatalError; + } + else if (_rdpClient9 != null) + { _rdpClient9.OnRequestGoFullScreen += onRequestGoFullScreen; _rdpClient9.OnRequestLeaveFullScreen += onRequestLeaveFullScreen; _rdpClient9.OnRequestContainerMinimize += onRequestContainerMinimize; _rdpClient9.OnConfirmClose += onConfirmClose; _rdpClient9.OnFatalError += onFatalError; } - else if (_rdpClient8 != null) { + else if (_rdpClient8 != null) + { _rdpClient8.OnRequestGoFullScreen += onRequestGoFullScreen; _rdpClient8.OnRequestLeaveFullScreen += onRequestLeaveFullScreen; _rdpClient8.OnRequestContainerMinimize += onRequestContainerMinimize; _rdpClient8.OnConfirmClose += onConfirmClose; _rdpClient8.OnFatalError += onFatalError; } - else if (_rdpClient7 != null) { + else if (_rdpClient7 != null) + { _rdpClient7.OnRequestGoFullScreen += onRequestGoFullScreen; _rdpClient7.OnRequestLeaveFullScreen += onRequestLeaveFullScreen; _rdpClient7.OnRequestContainerMinimize += onRequestContainerMinimize; _rdpClient7.OnConfirmClose += onConfirmClose; _rdpClient7.OnFatalError += onFatalError; } - else if (_rdpClient6 != null) { + else if (_rdpClient6 != null) + { _rdpClient6.OnRequestGoFullScreen += onRequestGoFullScreen; _rdpClient6.OnRequestLeaveFullScreen += onRequestLeaveFullScreen; _rdpClient6.OnRequestContainerMinimize += onRequestContainerMinimize; _rdpClient6.OnConfirmClose += onConfirmClose; _rdpClient6.OnFatalError += onFatalError; } - else { + else + { _rdpClient5.OnRequestGoFullScreen += onRequestGoFullScreen; _rdpClient5.OnRequestLeaveFullScreen += onRequestLeaveFullScreen; _rdpClient5.OnRequestContainerMinimize += onRequestContainerMinimize; @@ -773,45 +919,50 @@ public void ConnectContainerHandlers(EventHandler onRequestGoFullScreen, EventHa } } - public void DisconnectContainerHandlers(EventHandler onRequestGoFullScreen, EventHandler onRequestLeaveFullScreen, EventHandler onRequestContainerMinimize, - AxMSTSCLib.IMsTscAxEvents_OnConfirmCloseEventHandler onConfirmClose, AxMSTSCLib.IMsTscAxEvents_OnFatalErrorEventHandler onFatalError) { - //if (_rdpClient10 != null) { - // _rdpClient10.OnRequestGoFullScreen -= onRequestGoFullScreen; - // _rdpClient10.OnRequestLeaveFullScreen -= onRequestLeaveFullScreen; - // _rdpClient10.OnRequestContainerMinimize -= onRequestContainerMinimize; - // _rdpClient10.OnConfirmClose -= onConfirmClose; - // _rdpClient10.OnFatalError -= onFatalError; - //} - //else - if (_rdpClient9 != null) { + public void DisconnectContainerHandlers(EventHandler onRequestGoFullScreen, EventHandler onRequestLeaveFullScreen, EventHandler onRequestContainerMinimize, AxMSTSCLib.IMsTscAxEvents_OnConfirmCloseEventHandler onConfirmClose, AxMSTSCLib.IMsTscAxEvents_OnFatalErrorEventHandler onFatalError) + { + if (_rdpClient10 != null) + { + _rdpClient10.OnRequestGoFullScreen -= onRequestGoFullScreen; + _rdpClient10.OnRequestLeaveFullScreen -= onRequestLeaveFullScreen; + _rdpClient10.OnRequestContainerMinimize -= onRequestContainerMinimize; + _rdpClient10.OnConfirmClose -= onConfirmClose; + _rdpClient10.OnFatalError -= onFatalError; + } + else if (_rdpClient9 != null) + { _rdpClient9.OnRequestGoFullScreen -= onRequestGoFullScreen; _rdpClient9.OnRequestLeaveFullScreen -= onRequestLeaveFullScreen; _rdpClient9.OnRequestContainerMinimize -= onRequestContainerMinimize; _rdpClient9.OnConfirmClose -= onConfirmClose; _rdpClient9.OnFatalError -= onFatalError; } - else if (_rdpClient8 != null) { + else if (_rdpClient8 != null) + { _rdpClient8.OnRequestGoFullScreen -= onRequestGoFullScreen; _rdpClient8.OnRequestLeaveFullScreen -= onRequestLeaveFullScreen; _rdpClient8.OnRequestContainerMinimize -= onRequestContainerMinimize; _rdpClient8.OnConfirmClose -= onConfirmClose; _rdpClient8.OnFatalError -= onFatalError; } - else if (_rdpClient7 != null) { + else if (_rdpClient7 != null) + { _rdpClient7.OnRequestGoFullScreen -= onRequestGoFullScreen; _rdpClient7.OnRequestLeaveFullScreen -= onRequestLeaveFullScreen; _rdpClient7.OnRequestContainerMinimize -= onRequestContainerMinimize; _rdpClient7.OnConfirmClose -= onConfirmClose; _rdpClient7.OnFatalError -= onFatalError; } - else if (_rdpClient6 != null) { + else if (_rdpClient6 != null) + { _rdpClient6.OnRequestGoFullScreen -= onRequestGoFullScreen; _rdpClient6.OnRequestLeaveFullScreen -= onRequestLeaveFullScreen; _rdpClient6.OnRequestContainerMinimize -= onRequestContainerMinimize; _rdpClient6.OnConfirmClose -= onConfirmClose; _rdpClient6.OnFatalError -= onFatalError; } - else { + else + { _rdpClient5.OnRequestGoFullScreen -= onRequestGoFullScreen; _rdpClient5.OnRequestLeaveFullScreen -= onRequestLeaveFullScreen; _rdpClient5.OnRequestContainerMinimize -= onRequestContainerMinimize; @@ -820,60 +971,72 @@ public void DisconnectContainerHandlers(EventHandler onRequestGoFullScreen, Even } } - public void Dump() { - try { - //if (_rdpClient10 != null) { - // Log.DumpObject(_rdpClient10.AdvancedSettings9); - // Log.DumpObject(_rdpClient10.SecuredSettings3); - // Log.DumpObject(_rdpClient10.TransportSettings3); - // Log.DumpObject((IMsRdpClientNonScriptable5)_rdpClient10.GetOcx()); - //} - //else - if (_rdpClient9 != null) { + public void Dump() + { + try + { + if (_rdpClient10 != null) + { + Log.DumpObject(_rdpClient10.AdvancedSettings9); + Log.DumpObject(_rdpClient10.SecuredSettings3); + Log.DumpObject(_rdpClient10.TransportSettings3); + Log.DumpObject((IMsRdpClientNonScriptable5)_rdpClient10.GetOcx()); + } + else if (_rdpClient9 != null) + { Log.DumpObject(_rdpClient9.AdvancedSettings9); Log.DumpObject(_rdpClient9.SecuredSettings3); Log.DumpObject(_rdpClient9.TransportSettings3); Log.DumpObject((IMsRdpClientNonScriptable5)_rdpClient9.GetOcx()); } - else if (_rdpClient8 != null) { + else if (_rdpClient8 != null) + { Log.DumpObject(_rdpClient8.AdvancedSettings9); Log.DumpObject(_rdpClient8.SecuredSettings3); Log.DumpObject(_rdpClient8.TransportSettings3); Log.DumpObject((IMsRdpClientNonScriptable5)_rdpClient8.GetOcx()); } - else if (_rdpClient7 != null) { + else if (_rdpClient7 != null) + { Log.DumpObject(_rdpClient7.AdvancedSettings8); Log.DumpObject(_rdpClient7.SecuredSettings3); Log.DumpObject(_rdpClient7.TransportSettings3); Log.DumpObject((IMsRdpClientNonScriptable5)_rdpClient7.GetOcx()); } - else if (_rdpClient6 != null) { + else if (_rdpClient6 != null) + { Log.DumpObject(_rdpClient6.AdvancedSettings7); Log.DumpObject(_rdpClient6.SecuredSettings2); Log.DumpObject(_rdpClient6.TransportSettings2); Log.DumpObject((IMsRdpClientNonScriptable4)_rdpClient6.GetOcx()); } - else if (_rdpClient5 != null) { + else if (_rdpClient5 != null) + { Log.DumpObject(_rdpClient5.AdvancedSettings6); Log.DumpObject(_rdpClient5.SecuredSettings2); Log.DumpObject(_rdpClient5.TransportSettings); Log.DumpObject((IMsRdpClientNonScriptable4)_rdpClient5.GetOcx()); } } - catch { + catch + { } } - public bool Resize(uint width, uint height) { - //if (_rdpClient10 != null) { - // _rdpClient10.Reconnect(width, height); - // return true; - //} - if (_rdpClient9 != null) { + public bool Resize(uint width, uint height) + { + if (_rdpClient10 != null) + { + _rdpClient10.Reconnect(width, height); + return true; + } + if (_rdpClient9 != null) + { _rdpClient9.Reconnect(width, height); return true; } - if (_rdpClient8 != null) { + if (_rdpClient8 != null) + { _rdpClient8.Reconnect(width, height); return true; } diff --git a/RdcMan/RdpClient5.cs b/RdcMan/RdpClient5.cs index dbd9028..f9022a7 100644 --- a/RdcMan/RdpClient5.cs +++ b/RdcMan/RdpClient5.cs @@ -2,19 +2,24 @@ using System.Windows.Forms; using AxMSTSCLib; -namespace RdcMan { - internal class RdpClient5 : AxMsRdpClient5, IRdpClient { - public RdpClient5(MainForm form) { +namespace RdcMan +{ + internal class RdpClient5 : AxMsRdpClient5, IRdpClient + { + public RdpClient5(MainForm form) + { ((ISupportInitialize)this).BeginInit(); Hide(); form.AddToClientPanel(this); ((ISupportInitialize)this).EndInit(); } - protected override void WndProc(ref Message m) { + protected override void WndProc(ref Message m) + { if ((long)m.Msg == 33 && !base.ContainsFocus) + { Focus(); - + } base.WndProc(ref m); } } diff --git a/RdcMan/RdpClient6.cs b/RdcMan/RdpClient6.cs index 699ee3a..fd221ed 100644 --- a/RdcMan/RdpClient6.cs +++ b/RdcMan/RdpClient6.cs @@ -2,19 +2,24 @@ using System.Windows.Forms; using AxMSTSCLib; -namespace RdcMan { - internal class RdpClient6 : AxMsRdpClient6NotSafeForScripting, IRdpClient { - public RdpClient6(MainForm form) { +namespace RdcMan +{ + internal class RdpClient6 : AxMsRdpClient6NotSafeForScripting, IRdpClient + { + public RdpClient6(MainForm form) + { ((ISupportInitialize)this).BeginInit(); Hide(); form.AddToClientPanel(this); ((ISupportInitialize)this).EndInit(); } - protected override void WndProc(ref Message m) { + protected override void WndProc(ref Message m) + { if ((long)m.Msg == 33 && !base.ContainsFocus) + { Focus(); - + } base.WndProc(ref m); } } diff --git a/RdcMan/RdpClient7.cs b/RdcMan/RdpClient7.cs index 90d4dd4..2a7ee5b 100644 --- a/RdcMan/RdpClient7.cs +++ b/RdcMan/RdpClient7.cs @@ -2,19 +2,24 @@ using System.Windows.Forms; using AxMSTSCLib; -namespace RdcMan { - internal class RdpClient7 : AxMsRdpClient7NotSafeForScripting, IRdpClient { - public RdpClient7(MainForm form) { +namespace RdcMan +{ + internal class RdpClient7 : AxMsRdpClient7NotSafeForScripting, IRdpClient + { + public RdpClient7(MainForm form) + { ((ISupportInitialize)this).BeginInit(); Hide(); form.AddToClientPanel(this); ((ISupportInitialize)this).EndInit(); } - protected override void WndProc(ref Message m) { + protected override void WndProc(ref Message m) + { if ((long)m.Msg == 33 && !base.ContainsFocus) + { Focus(); - + } base.WndProc(ref m); } } diff --git a/RdcMan/RdpClient8.cs b/RdcMan/RdpClient8.cs index 33fa692..ffaec15 100644 --- a/RdcMan/RdpClient8.cs +++ b/RdcMan/RdpClient8.cs @@ -1,9 +1,12 @@ using System.ComponentModel; using AxMSTSCLib; -namespace RdcMan { - internal class RdpClient8 : AxMsRdpClient8NotSafeForScripting, IRdpClient { - public RdpClient8(MainForm form) { +namespace RdcMan +{ + internal class RdpClient8 : AxMsRdpClient8NotSafeForScripting, IRdpClient + { + public RdpClient8(MainForm form) + { ((ISupportInitialize)this).BeginInit(); Hide(); form.AddToClientPanel(this); diff --git a/RdcMan/RdpClient9.cs b/RdcMan/RdpClient9.cs index 3ab7275..f2790b7 100644 --- a/RdcMan/RdpClient9.cs +++ b/RdcMan/RdpClient9.cs @@ -1,9 +1,12 @@ using System.ComponentModel; using AxMSTSCLib; -namespace RdcMan { - internal class RdpClient9 : AxMsRdpClient9NotSafeForScripting, IRdpClient { - public RdpClient9(MainForm form) { +namespace RdcMan +{ + internal class RdpClient9 : AxMsRdpClient9NotSafeForScripting, IRdpClient + { + public RdpClient9(MainForm form) + { ((ISupportInitialize)this).BeginInit(); Hide(); form.AddToClientPanel(this); diff --git a/RdcMan/RecentlyUsedGroup.cs b/RdcMan/RecentlyUsedGroup.cs index 866a9b1..4f3699e 100644 --- a/RdcMan/RecentlyUsedGroup.cs +++ b/RdcMan/RecentlyUsedGroup.cs @@ -3,13 +3,18 @@ using System.Drawing; using System.Windows.Forms; -namespace RdcMan { +namespace RdcMan +{ [Export(typeof(IBuiltInVirtualGroup))] - internal class RecentlyUsedGroup : BuiltInVirtualGroup, IServerRefFactory { - private class RecentlyUsedSettings : GroupSettings { - private class RecentlyUsedSettingsTabPage : SettingsTabPage { + internal class RecentlyUsedGroup : BuiltInVirtualGroup, IServerRefFactory + { + private class RecentlyUsedSettings : GroupSettings + { + private class RecentlyUsedSettingsTabPage : SettingsTabPage + { public RecentlyUsedSettingsTabPage(TabbedSettingsDialog dialog, RecentlyUsedSettings settings) - : base(dialog, settings) { + : base(dialog, settings) + { int rowIndex = 0; int num = 0; Label label = FormTools.NewLabel("Ŀ", 0, rowIndex); @@ -34,16 +39,19 @@ public RecentlyUsedSettingsTabPage(TabbedSettingsDialog dialog, RecentlyUsedSett [Setting("maxNumberOfServers", DefaultValue = 10)] public IntSetting MaxNumberOfServers { get; private set; } - static RecentlyUsedSettings() { + static RecentlyUsedSettings() + { typeof(RecentlyUsedSettings).GetSettingProperties(out _settingProperties); } public RecentlyUsedSettings() - : base("") { + : base("") + { base.InheritSettingsType.Mode = InheritanceMode.Disabled; } - public override TabPage CreateTabPage(TabbedSettingsDialog dialog) { + public override TabPage CreateTabPage(TabbedSettingsDialog dialog) + { return new RecentlyUsedSettingsTabPage(dialog, this); } } @@ -58,26 +66,36 @@ public override TabPage CreateTabPage(TabbedSettingsDialog dialog) { protected override string XmlNodeName => "recentlyUsed"; - static RecentlyUsedGroup() { + static RecentlyUsedGroup() + { Server.ConnectionStateChanged += Server_ConnectionStateChanged; Server.FocusReceived += Server_FocusReceived; } - private static void Server_FocusReceived(Server server) { + private static void Server_FocusReceived(Server server) + { if (server.ConnectionState == RdpClient.ConnectionState.Connected) + { Instance.MoveToTop(server); + } } - private static void Server_ConnectionStateChanged(ConnectionStateChangedEventArgs args) { + private static void Server_ConnectionStateChanged(ConnectionStateChangedEventArgs args) + { if (args.State == RdpClient.ConnectionState.Connected) + { Instance.MoveToTop(args.Server); + } } - public override RecentlyUsedServerRef AddReference(ServerBase serverBase) { + public override RecentlyUsedServerRef AddReference(ServerBase serverBase) + { Server server = serverBase.ServerNode; RecentlyUsedServerRef serverRef = server.FindServerRef(); - if (serverRef == null) { - ServerTree.Instance.Operation(OperationBehavior.SuspendUpdate | OperationBehavior.SuspendGroupChanged, delegate { + if (serverRef == null) + { + ServerTree.Instance.Operation(OperationBehavior.SuspendUpdate | OperationBehavior.SuspendGroupChanged, delegate + { serverRef = base.ServerRefFactory.Create(server) as RecentlyUsedServerRef; base.Nodes.Insert(0, serverRef); RemoveExtra(); @@ -87,18 +105,25 @@ public override RecentlyUsedServerRef AddReference(ServerBase serverBase) { return serverRef; } - private void RemoveExtra() { - ServerTree.Instance.Operation(OperationBehavior.SuspendUpdate | OperationBehavior.SuspendGroupChanged, delegate { + private void RemoveExtra() + { + ServerTree.Instance.Operation(OperationBehavior.SuspendUpdate | OperationBehavior.SuspendGroupChanged, delegate + { int value = (base.Properties as RecentlyUsedSettings).MaxNumberOfServers.Value; while (base.Nodes.Count > value) + { ServerTree.Instance.RemoveNode(base.Nodes[value] as RdcTreeNode); + } }); } - private void MoveToTop(Server server) { + private void MoveToTop(Server server) + { ServerRef serverRef = AddReference(server); - if (serverRef.Index > 0) { - ServerTree.Instance.Operation(OperationBehavior.RestoreSelected, delegate { + if (serverRef.Index > 0) + { + ServerTree.Instance.Operation(OperationBehavior.RestoreSelected, delegate + { base.Nodes.Remove(serverRef); base.Nodes.Insert(0, serverRef); }); @@ -106,36 +131,43 @@ private void MoveToTop(Server server) { } } - private RecentlyUsedGroup() { + private RecentlyUsedGroup() + { base.Text = ""; Instance = this; } - protected override void InitSettings() { + protected override void InitSettings() + { ((RdcTreeNode)this).Properties = new RecentlyUsedSettings(); base.AllSettingsGroups.Add(base.Properties); } - public override bool CanRemoveChildren() { + public override bool CanRemoveChildren() + { return false; } - public override void DoPropertiesDialog(Form parentForm, string activeTabName) { + public override void DoPropertiesDialog(Form parentForm, string activeTabName) + { using TabbedSettingsDialog tabbedSettingsDialog = new TabbedSettingsDialog("ʹõ", "ȷ", parentForm); tabbedSettingsDialog.AddTabPage(base.Properties.CreateTabPage(tabbedSettingsDialog)); tabbedSettingsDialog.InitButtons(); - if (tabbedSettingsDialog.ShowDialog(parentForm) == DialogResult.OK) { + if (tabbedSettingsDialog.ShowDialog(parentForm) == DialogResult.OK) + { tabbedSettingsDialog.UpdateSettings(); RemoveExtra(); ServerTree.Instance.OnGroupChanged(this, ChangeType.PropertyChanged); } } - public ServerRef Create(Server server) { + public ServerRef Create(Server server) + { return new RecentlyUsedServerRef(server); } - protected override bool ShouldWriteNode(RdcTreeNode node, FileGroup file) { + protected override bool ShouldWriteNode(RdcTreeNode node, FileGroup file) + { return file == null; } } diff --git a/RdcMan/RecentlyUsedServerRef.cs b/RdcMan/RecentlyUsedServerRef.cs index e020476..c5def94 100644 --- a/RdcMan/RecentlyUsedServerRef.cs +++ b/RdcMan/RecentlyUsedServerRef.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - internal class RecentlyUsedServerRef : ServerRef { +namespace RdcMan +{ + internal class RecentlyUsedServerRef : ServerRef + { public RecentlyUsedServerRef(Server server) : base(server) { } } diff --git a/RdcMan/ReconnectGroup.cs b/RdcMan/ReconnectGroup.cs index d00a02f..c855f86 100644 --- a/RdcMan/ReconnectGroup.cs +++ b/RdcMan/ReconnectGroup.cs @@ -1,33 +1,39 @@ using System.ComponentModel.Composition; using System.Windows.Forms; -namespace RdcMan { +namespace RdcMan +{ [Export(typeof(IBuiltInVirtualGroup))] - internal class ReconnectGroup : BuiltInVirtualGroup, IServerRefFactory { + internal class ReconnectGroup : BuiltInVirtualGroup, IServerRefFactory + { public static ReconnectGroup Instance { get; private set; } + protected override string XmlNodeName => "reconnect"; - protected override string XmlNodeName => "reconnect"; - - private ReconnectGroup() { + private ReconnectGroup() + { base.Text = ""; Instance = this; } - public override bool CanDropServers() { + public override bool CanDropServers() + { return true; } - public override DragDropEffects DropBehavior() { + public override DragDropEffects DropBehavior() + { return DragDropEffects.Copy; } - public override bool HandleMove(RdcTreeNode childNode) { + public override bool HandleMove(RdcTreeNode childNode) + { ReconnectServerRef reconnectServerRef = AddReference(childNode as ServerBase); reconnectServerRef.Start(removeAfterConnection: false); return true; } - public ServerRef Create(Server server) { + public ServerRef Create(Server server) + { return new ReconnectServerRef(server); } } diff --git a/RdcMan/ReconnectServerOptions.cs b/RdcMan/ReconnectServerOptions.cs index 05cf859..cfd7b75 100644 --- a/RdcMan/ReconnectServerOptions.cs +++ b/RdcMan/ReconnectServerOptions.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - internal enum ReconnectServerOptions { +namespace RdcMan +{ + internal enum ReconnectServerOptions + { Ask, All, None diff --git a/RdcMan/ReconnectServerRef.cs b/RdcMan/ReconnectServerRef.cs index 60905c1..2ad7453 100644 --- a/RdcMan/ReconnectServerRef.cs +++ b/RdcMan/ReconnectServerRef.cs @@ -1,98 +1,130 @@ using System.Threading; using System.Windows.Forms; -namespace RdcMan { - internal class ReconnectServerRef : ServerRef { +namespace RdcMan +{ + internal class ReconnectServerRef : ServerRef + { private bool _selectedInConnectedGroup; public bool NeedToReconnect { get; private set; } private bool RemoveAfterConnection { get; set; } - static ReconnectServerRef() { + static ReconnectServerRef() + { Server.ConnectionStateChanged += Server_ConnectionStateChanged; } - private static void Server_ConnectionStateChanged(ConnectionStateChangedEventArgs args) { + private static void Server_ConnectionStateChanged(ConnectionStateChangedEventArgs args) + { ReconnectServerRef reconnectServerRef = args.Server.FindServerRef(); - if (reconnectServerRef != null) { - switch (args.State) { - case RdpClient.ConnectionState.Connecting: - reconnectServerRef.OnConnecting(); - break; - case RdpClient.ConnectionState.Connected: - reconnectServerRef.OnConnected(); - break; - case RdpClient.ConnectionState.Disconnected: - reconnectServerRef.OnDisconnected(); - break; + if (reconnectServerRef != null) + { + switch (args.State) + { + case RdpClient.ConnectionState.Connecting: + reconnectServerRef.OnConnecting(); + break; + case RdpClient.ConnectionState.Connected: + reconnectServerRef.OnConnected(); + break; + case RdpClient.ConnectionState.Disconnected: + reconnectServerRef.OnDisconnected(); + break; } } } public ReconnectServerRef(Server server) : base(server) { } - public void Start(bool removeAfterConnection) { + public void Start(bool removeAfterConnection) + { RemoveAfterConnection = removeAfterConnection; NeedToReconnect = true; ConnectedServerRef connectedServerRef = ServerNode.FindServerRef(); - if (connectedServerRef != null) { + if (connectedServerRef != null) + { _selectedInConnectedGroup = connectedServerRef.IsSelected; if (_selectedInConnectedGroup) + { ServerTree.Instance.SelectedNode = ServerNode; + } } if (!ServerNode.IsConnected) + { ServerNode.Connect(); + } else + { ServerNode.Disconnect(); + } } - public override bool CanRemove(bool popUI) { + public override bool CanRemove(bool popUI) + { return true; } - public override void Reconnect() { + public override void Reconnect() + { NeedToReconnect = true; ServerNode.Disconnect(); } - public override void Disconnect() { + public override void Disconnect() + { NeedToReconnect = false; base.Disconnect(); } - public override void LogOff() { + public override void LogOff() + { NeedToReconnect = false; base.LogOff(); } - private void OnConnecting() { + private void OnConnecting() + { if (RemoveAfterConnection) + { NeedToReconnect = false; + } } - private void OnConnected() { + private void OnConnected() + { NeedToReconnect = false; - if (RemoveAfterConnection) { + if (RemoveAfterConnection) + { if (ServerTree.Instance.SelectedNode == this) + { ServerTree.Instance.SelectedNode = ServerNode; + } else if (_selectedInConnectedGroup && ServerTree.Instance.SelectedNode == ServerNode) + { ServerTree.Instance.SelectedNode = ServerNode.FindServerRef(); - + } ServerTree.Instance.RemoveNode(this); } } - private void OnDisconnected() { - if (NeedToReconnect) { - ThreadPool.QueueUserWorkItem(delegate { - ServerNode.ParentForm.Invoke((MethodInvoker)delegate { + private void OnDisconnected() + { + if (NeedToReconnect) + { + ThreadPool.QueueUserWorkItem(delegate + { + ServerNode.ParentForm.Invoke((MethodInvoker)delegate + { ServerNode.Connect(); }); }); } else + { ServerTree.Instance.RemoveNode(this); + } } } } diff --git a/RdcMan/RemoteDesktopSettings.cs b/RdcMan/RemoteDesktopSettings.cs index 0c736f7..39ea1c3 100644 --- a/RdcMan/RemoteDesktopSettings.cs +++ b/RdcMan/RemoteDesktopSettings.cs @@ -3,9 +3,11 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { - public class RemoteDesktopSettings : SettingsGroup { - //internal const string TabName = "Զ"; +namespace RdcMan +{ + public class RemoteDesktopSettings : SettingsGroup + { + //internal const string TabName = "Remote Desktop Settings"; private static Dictionary _settingProperties; @@ -23,26 +25,34 @@ public class RemoteDesktopSettings : SettingsGroup { [Setting("colorDepth", DefaultValue = 24)] public IntSetting ColorDepth { get; private set; } - static RemoteDesktopSettings() { + static RemoteDesktopSettings() + { typeof(RemoteDesktopSettings).GetSettingProperties(out _settingProperties); _settingProperties["size"].Attribute.DefaultValue = new Size(1024, 768); } public RemoteDesktopSettings() - : base("Զ", "remoteDesktop") { } + : base("Զ", "remoteDesktop") + { + } - public override TabPage CreateTabPage(TabbedSettingsDialog dialog) { + public override TabPage CreateTabPage(TabbedSettingsDialog dialog) + { return new RemoteDesktopTabPage(dialog, this); } - protected override void WriteSettings(XmlTextWriter tw, RdcTreeNode node) { + protected override void WriteSettings(XmlTextWriter tw, RdcTreeNode node) + { HashSet hashSet = new HashSet(); if (DesktopSizeSameAsClientAreaSize.Value || DesktopSizeFullScreen.Value) + { hashSet.Add(DesktopSize); + } base.WriteSettings(tw, node, hashSet); } - protected override void Copy(RdcTreeNode node) { + protected override void Copy(RdcTreeNode node) + { Copy(node.RemoteDesktopSettings); } } diff --git a/RdcMan/RemoteDesktopTabPage.cs b/RdcMan/RemoteDesktopTabPage.cs index 62e524a..d6286d9 100644 --- a/RdcMan/RemoteDesktopTabPage.cs +++ b/RdcMan/RemoteDesktopTabPage.cs @@ -3,8 +3,10 @@ using System.Linq; using System.Windows.Forms; -namespace RdcMan { - public class RemoteDesktopTabPage : SettingsTabPage { +namespace RdcMan +{ + public class RemoteDesktopTabPage : SettingsTabPage + { private readonly GroupBox _rdsSizeGroup; private readonly RadioButton _rdsCustomRadio; @@ -12,7 +14,8 @@ public class RemoteDesktopTabPage : SettingsTabPage { private readonly Button _rdsCustomButton; public RemoteDesktopTabPage(TabbedSettingsDialog dialog, RemoteDesktopSettings settings) - : base(dialog, settings) { + : base(dialog, settings) + { int num = 0; int rowIndex = 0; CreateInheritanceControl(ref rowIndex, ref num); @@ -46,48 +49,62 @@ public RemoteDesktopTabPage(TabbedSettingsDialog dialog, RemoteDesktopSettings s base.Controls.Add(_rdsSizeGroup); } - protected override void UpdateControls() { + protected override void UpdateControls() + { base.UpdateControls(); Size size = base.Settings.DesktopSize.Value; - if (!base.Settings.DesktopSizeSameAsClientAreaSize.Value && !base.Settings.DesktopSizeFullScreen.Value) { - RadioButton radioButton = _rdsSizeGroup.Controls.OfType().Where(delegate (RadioButton r) { + if (!base.Settings.DesktopSizeSameAsClientAreaSize.Value && !base.Settings.DesktopSizeFullScreen.Value) + { + RadioButton radioButton = _rdsSizeGroup.Controls.OfType().Where(delegate(RadioButton r) + { Size? size2 = (Size?)r.Tag; Size size3 = size; if (!size2.HasValue) + { return false; - + } return !size2.HasValue || size2.GetValueOrDefault() == size3; }).FirstOrDefault(); if (radioButton != null) + { radioButton.Checked = true; + } else + { _rdsCustomRadio.Checked = true; + } } _rdsCustomButton.Text = size.ToFormattedString(); } - protected override void UpdateSettings() { + protected override void UpdateSettings() + { base.UpdateSettings(); if (base.Settings.DesktopSizeSameAsClientAreaSize.Value || base.Settings.DesktopSizeFullScreen.Value) + { return; - + } string dim = _rdsCustomButton.Text; - if (!_rdsCustomRadio.Checked) { + if (!_rdsCustomRadio.Checked) + { dim = (from r in _rdsSizeGroup.Controls.OfType() - where r.Checked - select r).First().Text; + where r.Checked + select r).First().Text; } base.Settings.DesktopSize.Value = SizeHelper.Parse(dim); } - private void CustomSizeClick(object sender, EventArgs e) { + private void CustomSizeClick(object sender, EventArgs e) + { Button button = sender as Button; RadioButton radioButton = button.Parent.GetNextControl(button, forward: false) as RadioButton; radioButton.Checked = true; Size size = SizeHelper.Parse(button.Text); using CustomSizeDialog customSizeDialog = new CustomSizeDialog(size); if (customSizeDialog.ShowDialog() == DialogResult.OK) + { button.Text = customSizeDialog.WidthText + SizeHelper.Separator + customSizeDialog.HeightText; + } } } } diff --git a/RdcMan/RemoteDesktopsMenuItem.cs b/RdcMan/RemoteDesktopsMenuItem.cs index eebfb34..053240f 100644 --- a/RdcMan/RemoteDesktopsMenuItem.cs +++ b/RdcMan/RemoteDesktopsMenuItem.cs @@ -1,55 +1,74 @@ using System.Windows.Forms; -namespace RdcMan { - internal class RemoteDesktopsMenuItem : RdcMenuItem { - private const string AllItem = "[All]"; +namespace RdcMan +{ + internal class RemoteDesktopsMenuItem : RdcMenuItem + { + //private const string AllItem = "[All]"; private bool HasChangedSinceMenuUpdate { get; set; } - public RemoteDesktopsMenuItem() : base("Զ") { + public RemoteDesktopsMenuItem() + : base("Զ") + { base.Name = MenuNames.RemoteDesktops.ToString(); ServerTree.Instance.GroupChanged += GroupChanged; ServerTree.Instance.ServerChanged += ServerChanged; HasChangedSinceMenuUpdate = true; } - private void ServerChanged(ServerChangedEventArgs e) { + private void ServerChanged(ServerChangedEventArgs e) + { if (e.ChangeType.HasFlag(ChangeType.TreeChanged) || e.ChangeType.HasFlag(ChangeType.PropertyChanged)) + { HasChangedSinceMenuUpdate = true; + } } - private void GroupChanged(GroupChangedEventArgs e) { + private void GroupChanged(GroupChangedEventArgs e) + { if (e.ChangeType.HasFlag(ChangeType.TreeChanged) || e.ChangeType.HasFlag(ChangeType.PropertyChanged)) + { HasChangedSinceMenuUpdate = true; + } } - public override void Update() { + public override void Update() + { if (!HasChangedSinceMenuUpdate) + { return; - + } HasChangedSinceMenuUpdate = false; base.DropDownItems.Clear(); - foreach (TreeNode node in ServerTree.Instance.Nodes) { + foreach (TreeNode node in ServerTree.Instance.Nodes) + { PopulateRemoteDesktopsMenuItems(base.DropDownItems, node); } } - protected override void OnClick() { } + protected override void OnClick() + { + } - private void PopulateRemoteDesktopsMenuItems(ToolStripItemCollection items, TreeNode treeNode) { + private void PopulateRemoteDesktopsMenuItems(ToolStripItemCollection items, TreeNode treeNode) + { RdcTreeNode rdcTreeNode = treeNode as RdcTreeNode; ToolStripMenuItem toolStripMenuItem; - if (rdcTreeNode is GroupBase groupBase && (groupBase.Nodes.Count > 1 || groupBase.HasGroups)) { + if (rdcTreeNode is GroupBase groupBase && (groupBase.Nodes.Count > 1 || groupBase.HasGroups)) + { toolStripMenuItem = new ToolStripMenuItem(rdcTreeNode.Text); ServerMenuItem serverMenuItem = new ServerMenuItem(rdcTreeNode) { - Text = AllItem + Text = "[All]" }; toolStripMenuItem.DropDownItems.Add(serverMenuItem); } else + { toolStripMenuItem = new ServerMenuItem(rdcTreeNode); - - foreach (TreeNode node in rdcTreeNode.Nodes) { + } + foreach (TreeNode node in rdcTreeNode.Nodes) + { PopulateRemoteDesktopsMenuItems(toolStripMenuItem.DropDownItems, node); } items.Add(toolStripMenuItem); diff --git a/RdcMan/RemoteSessionInfo.cs b/RdcMan/RemoteSessionInfo.cs index 093c31a..0149e67 100644 --- a/RdcMan/RemoteSessionInfo.cs +++ b/RdcMan/RemoteSessionInfo.cs @@ -1,7 +1,9 @@ using Win32; -namespace RdcMan { - internal class RemoteSessionInfo { +namespace RdcMan +{ + internal class RemoteSessionInfo + { public string ClientName; public string DomainName; diff --git a/RdcMan/RemoteSessions.cs b/RdcMan/RemoteSessions.cs index d479067..1f5e35d 100644 --- a/RdcMan/RemoteSessions.cs +++ b/RdcMan/RemoteSessions.cs @@ -3,33 +3,41 @@ using System.Runtime.InteropServices; using Win32; -namespace RdcMan { - internal class RemoteSessions { +namespace RdcMan +{ + internal class RemoteSessions + { private IntPtr _hServer; private readonly ServerBase _server; - public RemoteSessions(ServerBase server) { + public RemoteSessions(ServerBase server) + { _server = server; _hServer = (IntPtr)0; } - public bool OpenServer() { + public bool OpenServer() + { _hServer = Wts.OpenServer(_server.ServerName); if (_hServer == (IntPtr)0) + { return false; - + } return true; } - public void CloseServer() { - if (_hServer != (IntPtr)0) { + public void CloseServer() + { + if (_hServer != (IntPtr)0) + { Wts.CloseServer(_hServer); _hServer = (IntPtr)0; } } - public IList QuerySessions() { + public IList QuerySessions() + { if (_hServer == (IntPtr)0) throw new Exception(" OpenServer ɹ֮ǰ QuerySessions"); if (!Wts.EnumerateSessions(_hServer, 0, 1, out var pSessionInfo, out var count)) @@ -66,11 +74,13 @@ public IList QuerySessions() { } } - public bool DisconnectSession(int id) { + public bool DisconnectSession(int id) + { return Wts.DisconnectSession(_hServer, id, wait: true); } - public bool LogOffSession(int id) { + public bool LogOffSession(int id) + { return Wts.LogOffSession(_hServer, id, wait: true); } } diff --git a/RdcMan/Rule.cs b/RdcMan/Rule.cs index 19ea5be..2f4f14b 100644 --- a/RdcMan/Rule.cs +++ b/RdcMan/Rule.cs @@ -3,15 +3,17 @@ using System.Text.RegularExpressions; using System.Xml; -namespace RdcMan { - public class Rule { - //public const string XmlNodeName = "rule"; +namespace RdcMan +{ + public class Rule + { + public const string XmlNodeName = "rule"; - //private const string PropertyXmlNodeName = "property"; + private const string PropertyXmlNodeName = "property"; - //private const string OperatorXmlNodeName = "operator"; + private const string OperatorXmlNodeName = "operator"; - //private const string ValueXmlNodeName = "value"; + private const string ValueXmlNodeName = "value"; public RuleProperty Property { get; private set; } @@ -19,7 +21,8 @@ public class Rule { public object Value { get; private set; } - public Rule(RuleProperty property, RuleOperator operation, object value) { + public Rule(RuleProperty property, RuleOperator operation, object value) + { Property = property; Operator = operation; Value = value; @@ -27,48 +30,56 @@ public Rule(RuleProperty property, RuleOperator operation, object value) { protected Rule() { } - public static Rule Create(XmlNode xmlNode, RdcTreeNode node, ICollection errors) { + public static Rule Create(XmlNode xmlNode, RdcTreeNode node, ICollection errors) + { Rule rule = new Rule(); rule.ReadXml(xmlNode, node, errors); return rule; } - public bool Evaluate(Server server) { + public bool Evaluate(Server server) + { bool isString; object obj = Property.GetValue(server, out isString); if (obj == null) + { obj = string.Empty; - + } return Regex.IsMatch((string)obj, (string)Value, RegexOptions.IgnoreCase) ^ (Operator == RuleOperator.DoesNotMatch); } - public void ReadXml(XmlNode xmlNode, RdcTreeNode node, ICollection errors) { - foreach (XmlNode childNode in xmlNode.ChildNodes) { - switch (childNode.Name) { - case "property": - Property = new RuleProperty(childNode.InnerText.ParseEnum()); - break; - case "operator": - Operator = childNode.InnerText.ParseEnum(); - break; - case "value": - Value = childNode.InnerText; - break; - default: - throw new NotImplementedException(); + public void ReadXml(XmlNode xmlNode, RdcTreeNode node, ICollection errors) + { + foreach (XmlNode childNode in xmlNode.ChildNodes) + { + switch (childNode.Name) + { + case PropertyXmlNodeName: + Property = new RuleProperty(childNode.InnerText.ParseEnum()); + break; + case OperatorXmlNodeName: + Operator = childNode.InnerText.ParseEnum(); + break; + case ValueXmlNodeName: + Value = childNode.InnerText; + break; + default: + throw new NotImplementedException(); } } } - public void WriteXml(XmlTextWriter tw) { - tw.WriteStartElement("rule"); - tw.WriteElementString("property", Property.ServerProperty.ToString()); - tw.WriteElementString("operator", Operator.ToString()); - tw.WriteElementString("value", Value.ToString()); + public void WriteXml(XmlTextWriter tw) + { + tw.WriteStartElement(XmlNodeName); + tw.WriteElementString(PropertyXmlNodeName, Property.ServerProperty.ToString()); + tw.WriteElementString(OperatorXmlNodeName, Operator.ToString()); + tw.WriteElementString(ValueXmlNodeName, Value.ToString()); tw.WriteEndElement(); } - public override string ToString() { + public override string ToString() + { return "{0} {1} {2}".InvariantFormat(Property.ServerProperty, Operator, Value); } } diff --git a/RdcMan/RuleGroup.cs b/RdcMan/RuleGroup.cs index 0e0a6ba..89ab7c2 100644 --- a/RdcMan/RuleGroup.cs +++ b/RdcMan/RuleGroup.cs @@ -2,9 +2,11 @@ using System.Linq; using System.Xml; -namespace RdcMan { - internal class RuleGroup { - //public const string XmlNodeName = "ruleGroup"; +namespace RdcMan +{ + internal class RuleGroup + { + public const string XmlNodeName = "ruleGroup"; private const string GroupingOperatorXmlNodeName = "operator"; @@ -14,24 +16,30 @@ internal class RuleGroup { public List Rules { get; private set; } - public RuleGroup(RuleGroupOperator op, IEnumerable rules) { + public RuleGroup(RuleGroupOperator op, IEnumerable rules) + { Set(op, rules); } - protected RuleGroup() { } + protected RuleGroup() + { + } - public static RuleGroup Create(XmlNode xmlNode, RdcTreeNode node, ICollection errors) { + public static RuleGroup Create(XmlNode xmlNode, RdcTreeNode node, ICollection errors) + { RuleGroup ruleGroup = new RuleGroup(); ruleGroup.ReadXml(xmlNode, node, errors); return ruleGroup; } - public void Set(RuleGroupOperator op, IEnumerable rules) { + public void Set(RuleGroupOperator op, IEnumerable rules) + { Operator = op; Rules = rules.ToList(); } - public bool Evaluate(Server server) { + public bool Evaluate(Server server) + { bool result = false; bool result2 = true; foreach (Rule rule in Rules) { @@ -43,18 +51,22 @@ public bool Evaluate(Server server) { return Operator != 0 ? result2 : result; } - public void ReadXml(XmlNode xmlNode, RdcTreeNode node, ICollection errors) { + public void ReadXml(XmlNode xmlNode, RdcTreeNode node, ICollection errors) + { Operator = xmlNode.Attributes[GroupingOperatorXmlNodeName].Value.ParseEnum(); Rules = new List(); - foreach (XmlNode childNode in xmlNode.ChildNodes) { + foreach (XmlNode childNode in xmlNode.ChildNodes) + { Rules.Add(Rule.Create(childNode, node, errors)); } } - public void WriteXml(XmlTextWriter tw) { - tw.WriteStartElement("ruleGroup"); + public void WriteXml(XmlTextWriter tw) + { + tw.WriteStartElement(XmlNodeName); tw.WriteAttributeString(GroupingOperatorXmlNodeName, Operator.ToString()); - Rules.ForEach(delegate (Rule r) { + Rules.ForEach(delegate(Rule r) + { r.WriteXml(tw); }); tw.WriteEndElement(); diff --git a/RdcMan/RuleGroupOperator.cs b/RdcMan/RuleGroupOperator.cs index 980e547..9cc74c1 100644 --- a/RdcMan/RuleGroupOperator.cs +++ b/RdcMan/RuleGroupOperator.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public enum RuleGroupOperator { +namespace RdcMan +{ + public enum RuleGroupOperator + { Any, All } diff --git a/RdcMan/RuleOperator.cs b/RdcMan/RuleOperator.cs index d58533d..6ef6c66 100644 --- a/RdcMan/RuleOperator.cs +++ b/RdcMan/RuleOperator.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public enum RuleOperator { +namespace RdcMan +{ + public enum RuleOperator + { Matches, DoesNotMatch } diff --git a/RdcMan/RuleProperty.cs b/RdcMan/RuleProperty.cs index e156492..69fc26f 100644 --- a/RdcMan/RuleProperty.cs +++ b/RdcMan/RuleProperty.cs @@ -1,29 +1,34 @@ using System; -namespace RdcMan { - public class RuleProperty { +namespace RdcMan +{ + public class RuleProperty + { public ServerProperty ServerProperty { get; private set; } - public RuleProperty(ServerProperty property) { + public RuleProperty(ServerProperty property) + { ServerProperty = property; } - public object GetValue(Server server, out bool isString) { - switch (ServerProperty) { - case ServerProperty.DisplayName: - isString = true; - return server.DisplayName; - case ServerProperty.ServerName: - isString = true; - return server.ServerName; - case ServerProperty.Comment: - isString = true; - return server.Properties.Comment.Value; - case ServerProperty.Parent: - isString = true; - return server.ParentPath; - default: - throw new NotImplementedException(); + public object GetValue(Server server, out bool isString) + { + switch (ServerProperty) + { + case ServerProperty.DisplayName: + isString = true; + return server.DisplayName; + case ServerProperty.ServerName: + isString = true; + return server.ServerName; + case ServerProperty.Comment: + isString = true; + return server.Properties.Comment.Value; + case ServerProperty.Parent: + isString = true; + return server.ParentPath; + default: + throw new NotImplementedException(); } } } diff --git a/RdcMan/SaveCredentialsDialog.cs b/RdcMan/SaveCredentialsDialog.cs index ece8ed1..a2b93c9 100644 --- a/RdcMan/SaveCredentialsDialog.cs +++ b/RdcMan/SaveCredentialsDialog.cs @@ -56,7 +56,7 @@ private string ValidateProfileName() return "{0} DZļ".InvariantFormat("Custom"); } CredentialsStore credentialsProfiles = Program.CredentialsProfiles; - string text = "Global";//Global + string text = "Global"; if (ProfileScope == ProfileScope.File) { credentialsProfiles = _file.CredentialsProfiles; diff --git a/RdcMan/SaveResult.cs b/RdcMan/SaveResult.cs index f125d4c..d5dbf12 100644 --- a/RdcMan/SaveResult.cs +++ b/RdcMan/SaveResult.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public enum SaveResult { +namespace RdcMan +{ + public enum SaveResult + { Cancel, NoSave, Save, diff --git a/RdcMan/SecuritySettings.cs b/RdcMan/SecuritySettings.cs index c868327..d3720c0 100644 --- a/RdcMan/SecuritySettings.cs +++ b/RdcMan/SecuritySettings.cs @@ -1,8 +1,10 @@ using System.Collections.Generic; using System.Windows.Forms; -namespace RdcMan { - public class SecuritySettings : SettingsGroup { +namespace RdcMan +{ + public class SecuritySettings : SettingsGroup + { //internal const string TabName = "Security Settings"; private static Dictionary _settingProperties; @@ -18,18 +20,21 @@ public class SecuritySettings : SettingsGroup { [Setting("remoteGuard")] public BoolSetting RemoteGuard { get; private set; } - static SecuritySettings() { + static SecuritySettings() + { typeof(SecuritySettings).GetSettingProperties(out _settingProperties); } public SecuritySettings() : base("ȫ", "securitySettings") { } - public override TabPage CreateTabPage(TabbedSettingsDialog dialog) { + public override TabPage CreateTabPage(TabbedSettingsDialog dialog) + { return new SecuritySettingsTabPage(dialog, this); } - protected override void Copy(RdcTreeNode node) { + protected override void Copy(RdcTreeNode node) + { Copy(node.SecuritySettings); } } diff --git a/RdcMan/SecuritySettingsTabPage.cs b/RdcMan/SecuritySettingsTabPage.cs index e20c2d7..617ecdc 100644 --- a/RdcMan/SecuritySettingsTabPage.cs +++ b/RdcMan/SecuritySettingsTabPage.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public class SecuritySettingsTabPage : SettingsTabPage { +namespace RdcMan +{ + public class SecuritySettingsTabPage : SettingsTabPage + { public SecuritySettingsTabPage(TabbedSettingsDialog dialog, SecuritySettings settings) : base(dialog, settings) { int num = 0; diff --git a/RdcMan/SelectActiveServerForm.cs b/RdcMan/SelectActiveServerForm.cs index cc9ad94..73ab9ee 100644 --- a/RdcMan/SelectActiveServerForm.cs +++ b/RdcMan/SelectActiveServerForm.cs @@ -4,15 +4,19 @@ using System.Linq; using System.Windows.Forms; -namespace RdcMan { - internal class SelectActiveServerForm : RdcDialog { - public enum Operation { +namespace RdcMan +{ + internal class SelectActiveServerForm : RdcDialog + { + public enum Operation + { SelectServer, SelectTree, MinimizeWindow } - public class SelectedObject { + public class SelectedObject + { public Operation Operation; public char Key; @@ -27,7 +31,8 @@ public SelectActiveServerForm(IEnumerable servers) BackColor = Color.White; base.ClientSize = new Size(304, FormTools.YPos(7)); int num = 0; - foreach (ServerBase item in servers.Take(10)) { + foreach (ServerBase item in servers.Take(10)) + { char key = ((num == 9) ? '0' : ((char)(49 + num))); AddButton(num / 5, num % 5, key, item.DisplayName, Operation.SelectServer, item); num++; @@ -40,12 +45,15 @@ public SelectActiveServerForm(IEnumerable servers) this.ScaleAndLayout(); } - private void AddButton(int colIndex, int rowIndex, char key, string text, Operation operation, ServerBase server) { - Button button = new Button { + private void AddButton(int colIndex, int rowIndex, char key, string text, Operation operation, ServerBase server) + { + Button button = new Button + { Location = FormTools.NewLocation(colIndex, rowIndex), FlatStyle = FlatStyle.Flat, Text = $"{key} - {text}", - Tag = new SelectedObject { + Tag = new SelectedObject + { Key = key, Operation = operation, Server = server @@ -57,36 +65,49 @@ private void AddButton(int colIndex, int rowIndex, char key, string text, Operat base.Controls.Add(button); } - private void Button_KeyDown(object sender, KeyEventArgs e) { + private void Button_KeyDown(object sender, KeyEventArgs e) + { List_KeyDownHandler(sender, e); if (base.DialogResult == DialogResult.None) + { e.Handled = false; + } } - private void Button_Click(object sender, EventArgs e) { + private void Button_Click(object sender, EventArgs e) + { SelectedObject o = (sender as Button).Tag as SelectedObject; SelectObject(o); } - private void List_KeyDownHandler(object sender, KeyEventArgs e) { + private void List_KeyDownHandler(object sender, KeyEventArgs e) + { char c = (char)e.KeyData; if (e.KeyData >= Keys.NumPad0 && e.KeyData <= Keys.NumPad9) + { c = (char)(e.KeyData - 96 + 48); + } if (c >= 'a' && c <= 'z') + { c = (char)(c - 97 + 65); - foreach (Control control in base.Controls) { - if (control.Tag is SelectedObject selectedObject && selectedObject.Key == c) { + } + foreach (Control control in base.Controls) + { + if (control.Tag is SelectedObject selectedObject && selectedObject.Key == c) + { SelectObject(selectedObject); break; } } if (e.KeyData == Keys.Escape) + { Cancel(); - + } e.Handled = true; } - private void SelectObject(SelectedObject o) { + private void SelectObject(SelectedObject o) + { Selected = o; OK(); } diff --git a/RdcMan/SelectServersDialogBase.cs b/RdcMan/SelectServersDialogBase.cs index 2176fd7..1bd4813 100644 --- a/RdcMan/SelectServersDialogBase.cs +++ b/RdcMan/SelectServersDialogBase.cs @@ -5,9 +5,11 @@ using System.Threading; using System.Windows.Forms; -namespace RdcMan { - internal class SelectServersDialogBase : RdcDialog { - protected const int DialogWidth = 500; +namespace RdcMan +{ + internal class SelectServersDialogBase : RdcDialog + { + protected const int DialogWidth = 680; private int _suspendItemChecked; @@ -24,32 +26,37 @@ public IEnumerable SelectedServers { public SelectServersDialogBase(string dialogTitle, string acceptButtonText) : base(dialogTitle, acceptButtonText) { + Width = DialogWidth; } - protected void AddLabel(string text, ref int rowIndex, ref int tabIndex) { - Label value = new Label { + protected void AddLabel(string text, ref int rowIndex, ref int tabIndex) + { + Label value = new Label + { Location = FormTools.NewLocation(0, rowIndex++), Text = text, TextAlign = ContentAlignment.MiddleLeft, - Size = new Size(500, 20) + Size = new Size(DialogWidth, 20) }; base.Controls.Add(value); } - protected void AddListView(ref int rowIndex, ref int tabIndex) { - ListView = new RdcListView { + protected void AddListView(ref int rowIndex, ref int tabIndex) + { + ListView = new RdcListView + { CheckBoxes = true, FullRowSelect = true, Location = FormTools.NewLocation(0, rowIndex++), MultiSelect = false, - Size = new Size(500, 300), + Size = new Size(DialogWidth, 300), TabIndex = tabIndex++, View = View.Details }; ListView.KeyDown += List_KeyDownHandler; ListView.MouseDoubleClick += List_MouseDoubleClick; ListView.ItemChecked += ListView_ItemChecked; - ListView.Columns.AddRange(new ColumnHeader[3] + ListView.Columns.AddRange(new ColumnHeader[4] { new ColumnHeader { Text = string.Empty, @@ -59,38 +66,51 @@ protected void AddListView(ref int rowIndex, ref int tabIndex) { Text = "", Width = 130 }, + new ColumnHeader { + Text = "IPַ", + Width = 130 + }, new ColumnHeader { Text = "", Width = 349 } }); base.Controls.Add(ListView); - if (RdcListView.SupportsHeaderCheckBoxes) { + if (RdcListView.SupportsHeaderCheckBoxes) + { ListView.SetColumnHeaderToCheckBox(0); ListView.HeaderCheckBoxClick += ListView_HeaderCheckBoxClick; } } - public void SuspendItemChecked() { + public void SuspendItemChecked() + { Interlocked.Increment(ref _suspendItemChecked); } - public void ResumeItemChecked() { + public void ResumeItemChecked() + { if (Interlocked.Decrement(ref _suspendItemChecked) == 0) + { SetHeaderCheckFromItems(); + } } - protected ListViewItem CreateListViewItem(ServerBase server) { - return new ListViewItem(new string[3] { + protected ListViewItem CreateListViewItem(ServerBase server) + { + return new ListViewItem(new string[4] + { "", server.DisplayName, + server.ServerName, server.Parent.FullPath }) { Tag = server }; } - public override void InitButtons() { + public override void InitButtons() + { base.InitButtons(); if (!RdcListView.SupportsHeaderCheckBoxes) { Button button = new Button { @@ -103,45 +123,58 @@ public override void InitButtons() { } } - private void List_MouseDoubleClick(object sender, MouseEventArgs e) { + private void List_MouseDoubleClick(object sender, MouseEventArgs e) + { if (e.Button == MouseButtons.Left) OK(); } - private void List_KeyDownHandler(object sender, KeyEventArgs e) { - if (e.KeyData == (Keys.A | Keys.Control)) { + private void List_KeyDownHandler(object sender, KeyEventArgs e) + { + if (e.KeyData == (Keys.A | Keys.Control)) + { e.Handled = true; SelectAllItems(isChecked: true); } } - private void SelectAll_Click(object sender, EventArgs e) { + private void SelectAll_Click(object sender, EventArgs e) + { SelectAllItems(isChecked: true); } - private void SelectAllItems(bool isChecked) { - try { + private void SelectAllItems(bool isChecked) + { + try + { SuspendItemChecked(); - foreach (ListViewItem item in ListView.Items) { + foreach (ListViewItem item in ListView.Items) + { item.Checked = isChecked; } } - finally { + finally + { ResumeItemChecked(); } } - private void ListView_ItemChecked(object sender, ItemCheckedEventArgs e) { + private void ListView_ItemChecked(object sender, ItemCheckedEventArgs e) + { if (_suspendItemChecked == 0) + { SetHeaderCheckFromItems(); + } } - private void SetHeaderCheckFromItems() { + private void SetHeaderCheckFromItems() + { bool isChecked = ListView.Items.OfType().All((ListViewItem i) => i.Checked); ListView.SetColumnHeaderChecked(0, isChecked); } - private void ListView_HeaderCheckBoxClick(object sender, HeaderColumnClickEventArgs e) { + private void ListView_HeaderCheckBoxClick(object sender, HeaderColumnClickEventArgs e) + { SelectAllItems(e.IsChecked); } } diff --git a/RdcMan/SelectedNodeMenuItem.cs b/RdcMan/SelectedNodeMenuItem.cs index ad45262..f578f6a 100644 --- a/RdcMan/SelectedNodeMenuItem.cs +++ b/RdcMan/SelectedNodeMenuItem.cs @@ -1,33 +1,44 @@ using System; -namespace RdcMan { - internal class SelectedNodeMenuItem : RdcMenuItem where T : RdcTreeNode { +namespace RdcMan +{ + internal class SelectedNodeMenuItem : RdcMenuItem where T : RdcTreeNode + { private readonly Action _action; public SelectedNodeMenuItem(string text, MenuNames name, Action action) - : base(text) { + : base(text) + { base.Name = name.ToString(); _action = action; } public SelectedNodeMenuItem(string text, MenuNames name, string shortcut, Action action) - : this(text, name, action) { + : this(text, name, action) + { base.ShortcutKeyDisplayString = shortcut; } - public override void Update() { + public override void Update() + { Enabled = Program.TheForm.GetSelectedNode() is T; } - protected override void OnClick() { + protected override void OnClick() + { _action(Program.TheForm.GetSelectedNode() as T); } } - internal class SelectedNodeMenuItem : SelectedNodeMenuItem { + internal class SelectedNodeMenuItem : SelectedNodeMenuItem + { public SelectedNodeMenuItem(string text, MenuNames name, Action action) - : base(text, name, action) { } + : base(text, name, action) + { + } public SelectedNodeMenuItem(string text, MenuNames name, string shortcut, Action action) - : base(text, name, shortcut, action) { } + : base(text, name, shortcut, action) + { + } } } diff --git a/RdcMan/SendKeys.cs b/RdcMan/SendKeys.cs index 1c41d87..be2438d 100644 --- a/RdcMan/SendKeys.cs +++ b/RdcMan/SendKeys.cs @@ -2,9 +2,12 @@ using MSTSCLib; using Win32; -namespace RdcMan { - internal class SendKeys { - private struct SendKeysData { +namespace RdcMan +{ + internal class SendKeys + { + private struct SendKeysData + { public const int MaxKeys = 20; public unsafe fixed short keyUp[20]; @@ -12,22 +15,27 @@ private struct SendKeysData { public unsafe fixed int keyData[20]; } - public unsafe static void Send(Keys[] keyCodes, ServerBase serverBase) { + public unsafe static void Send(Keys[] keyCodes, ServerBase serverBase) + { Server serverNode = serverBase.ServerNode; RdpClient client = serverNode.Client; IMsRdpClientNonScriptable msRdpClientNonScriptable = (IMsRdpClientNonScriptable)client.GetOcx(); int num = keyCodes.Length; - try { + try + { SendKeysData sendKeysData = default(SendKeysData); bool* ptr = (bool*)sendKeysData.keyUp; int* ptr2 = sendKeysData.keyData; int num2 = 0; - for (int i = 0; i < num && i < 10; i++) { + for (int i = 0; i < num && i < 10; i++) + { int num3 = (int)Util.MapVirtualKey((uint)keyCodes[i], 0u); sendKeysData.keyData[num2] = num3; sendKeysData.keyUp[num2++] = 0; - if (!IsModifier(keyCodes[i])) { - for (int num4 = num2 - 1; num4 >= 0; num4--) { + if (!IsModifier(keyCodes[i])) + { + for (int num4 = num2 - 1; num4 >= 0; num4--) + { sendKeysData.keyData[num2] = sendKeysData.keyData[num4]; sendKeysData.keyUp[num2++] = 1; } @@ -36,13 +44,17 @@ public unsafe static void Send(Keys[] keyCodes, ServerBase serverBase) { } } } - catch { } + catch + { + } } - private static bool IsModifier(Keys key) { + private static bool IsModifier(Keys key) + { if ((uint)(key - 16) <= 2u || (uint)(key - 91) <= 1u || (uint)(key - 162) <= 1u) + { return true; - + } return false; } } diff --git a/RdcMan/SendKeysMenuItem.cs b/RdcMan/SendKeysMenuItem.cs index f8765ee..7f92c90 100644 --- a/RdcMan/SendKeysMenuItem.cs +++ b/RdcMan/SendKeysMenuItem.cs @@ -15,8 +15,9 @@ public SendKeysMenuItem(string name, Keys[] keyCodes) { Keys keys = keyCodes[i]; if (stringBuilder.Length > 0) + { stringBuilder.Append("+"); - + } switch (keys) { case Keys.ControlKey: @@ -34,9 +35,13 @@ public SendKeysMenuItem(string name, Keys[] keyCodes) } } if (name != null) + { Text = name + " (" + stringBuilder.ToString() + ")"; + } else + { Text = stringBuilder.ToString(); + } } } } diff --git a/RdcMan/Server.cs b/RdcMan/Server.cs index 8991f3e..6f984f5 100644 --- a/RdcMan/Server.cs +++ b/RdcMan/Server.cs @@ -10,34 +10,38 @@ using MSTSCLib; using Win32; -namespace RdcMan { - public class Server : ServerBase { - private class DisconnectionReason { +namespace RdcMan +{ + public class Server : ServerBase + { + private class DisconnectionReason + { public readonly int Code; public readonly string Text; - public DisconnectionReason(int code, string text) { + public DisconnectionReason(int code, string text) + { Code = code; Text = text; } } - //public const string XmlNodeName = "server"; + public const string XmlNodeName = "server"; - //internal const string XmlDisplayNameTag = "displayName"; + internal const string XmlDisplayNameTag = "displayName"; - //internal const string XmlServerNameTag = "name"; + internal const string XmlServerNameTag = "name"; - //internal const string XmlCommentTag = "comment"; + internal const string XmlCommentTag = "comment"; - //internal const string ConnectionTypeTag = "connectionType"; + internal const string ConnectionTypeTag = "connectionType"; - //internal const string VirtualMachineIdTag = "vmId"; + internal const string VirtualMachineIdTag = "vmId"; private RdpClient.ConnectionState _connectionState; - //private const bool SimulateConnections = false; + private const bool SimulateConnections = false; private static readonly Dictionary PropertyActions; @@ -59,13 +63,20 @@ public DisconnectionReason(int code, string text) { private static readonly DisconnectionReason[] ExtendedDisconnectionReasons; - public RdpClient.ConnectionState ConnectionState { - get => _connectionState; - private set { - if (_connectionState != value) { + public RdpClient.ConnectionState ConnectionState + { + get + { + return _connectionState; + } + private set + { + if (_connectionState != value) + { _connectionState = value; Action connectionStateChanged = Server.ConnectionStateChanged; - if (connectionStateChanged != null) { + if (connectionStateChanged != null) + { ConnectionStateChangedEventArgs obj = new ConnectionStateChangedEventArgs(this, _connectionState); connectionStateChanged(obj); } @@ -81,12 +92,19 @@ private set { public override CommonDisplaySettings DisplaySettings => ((RdcTreeNode)this).DisplaySettings; - public override DisplayStates DisplayState { - get => _displayState; - set { - if (value != _displayState) { + public override DisplayStates DisplayState + { + get + { + return _displayState; + } + set + { + if (value != _displayState) + { _displayState = value; - if (value != 0) { + if (value != 0) + { SetText(); SetClientSizeProperties(); } @@ -94,62 +112,140 @@ public override DisplayStates DisplayState { } } - public override bool IsClientDocked { - get => !IsClientInitialized || ServerForm == null; + public override bool IsClientDocked + { + get + { + if (IsClientInitialized) + { + return ServerForm == null; + } + return true; + } } - public override bool IsClientUndocked { - get => IsClientInitialized && ServerForm != null; + public override bool IsClientUndocked + { + get + { + if (IsClientInitialized) + { + return ServerForm != null; + } + return false; + } } - public override RdcBaseForm ParentForm { - get => IsClientUndocked ? ServerForm : base.ParentForm; + public override RdcBaseForm ParentForm + { + get + { + if (IsClientUndocked) + { + return ServerForm; + } + return base.ParentForm; + } } private ServerForm ServerForm => Client.Control.Parent as ServerForm; - public override Size Size { - get => UseServerBox ? _serverBox.Size : _client.Control.Size; - set { + public override Size Size + { + get + { + if (!UseServerBox) + { + return _client.Control.Size; + } + return _serverBox.Size; + } + set + { if (!UseServerBox) + { _client.Control.Size = value; + } _serverBox.Size = value; } } - private bool IsClientInPanel { - get => IsClientInitialized && IsClientDocked; + private bool IsClientInPanel + { + get + { + if (IsClientInitialized) + { + return IsClientDocked; + } + return false; + } } - public override Point Location { - get => !UseServerBox ? _client.Control.Location : _serverBox.Location; - set { + public override Point Location + { + get + { if (!UseServerBox) + { + return _client.Control.Location; + } + return _serverBox.Location; + } + set + { + if (!UseServerBox) + { _client.Control.Location = value; + } _serverBox.Location = value; } } - public string ConnectedText { - get => base.IsThumbnail ? "" : "ӵ " + GetQualifiedNameForUI(); + public string ConnectedText + { + get + { + if (base.IsThumbnail) + { + return ""; + } + return "ӵ " + GetQualifiedNameForUI(); + } } - public string ConnectingText { - get => base.IsThumbnail ? "" : "ӵ " + GetQualifiedNameForUI(); + public string ConnectingText + { + get + { + if (base.IsThumbnail) + { + return ""; + } + return "ӵ " + GetQualifiedNameForUI(); + } } - public string DisconnectedText { - get { + public string DisconnectedText + { + get + { string text; - if (base.IsThumbnail) { + if (base.IsThumbnail) + { text = "Ͽ"; if (!string.IsNullOrEmpty(_disconnectionReason)) + { text += " [error]"; + } } - else { + else + { text = "δ " + GetQualifiedNameForUI(); if (!string.IsNullOrEmpty(_disconnectionReason)) + { text = text + Environment.NewLine + "[" + _disconnectionReason + "]"; + } } return text; } @@ -159,12 +255,16 @@ public string DisconnectedText { private bool IsClientInitialized => Client != null; - private bool UseServerBox { - get { - if (IsClientInPanel) { + private bool UseServerBox + { + get + { + if (IsClientInPanel) + { if (base.IsThumbnail) + { return !(ServerNode.Parent as GroupBase).DisplaySettings.SessionThumbnailPreview.Value; - + } return false; } return true; @@ -173,51 +273,69 @@ private bool UseServerBox { public override bool IsConnected => ConnectionState != RdpClient.ConnectionState.Disconnected; - public override bool IsClientFullScreen { - get => IsClientInitialized && Client.MsRdpClient.FullScreen; + public override bool IsClientFullScreen + { + get + { + if (IsClientInitialized) + { + return Client.MsRdpClient.FullScreen; + } + return false; + } } public static event Action ConnectionStateChanged; public static event Action FocusReceived; - static Server() { - PropertyActions = new Dictionary { + static Server() + { + PropertyActions = new Dictionary + { { "name", - delegate(XmlNode childNode, RdcTreeNode node, ICollection errors) { + delegate(XmlNode childNode, RdcTreeNode node, ICollection errors) + { (node as Server).Properties.ServerName.Value = childNode.InnerText; } }, { "connectionType", - delegate(XmlNode childNode, RdcTreeNode node, ICollection errors) { + delegate(XmlNode childNode, RdcTreeNode node, ICollection errors) + { Enum.TryParse(childNode.InnerText, out var result); (node as Server).Properties.ConnectionType.Value = result; } }, { "vmId", - delegate(XmlNode childNode, RdcTreeNode node, ICollection errors) { + delegate(XmlNode childNode, RdcTreeNode node, ICollection errors) + { (node as Server).Properties.VirtualMachineId.Value = childNode.InnerText; } }, { "displayName", - delegate(XmlNode childNode, RdcTreeNode node, ICollection errors) { + delegate(XmlNode childNode, RdcTreeNode node, ICollection errors) + { (node as Server).Properties.DisplayName.Value = childNode.InnerText; } }, { "comment", - delegate(XmlNode childNode, RdcTreeNode node, ICollection errors) { + delegate(XmlNode childNode, RdcTreeNode node, ICollection errors) + { XmlNode firstChild = childNode.FirstChild; if (firstChild != null) + { (node as Server).Properties.Comment.Value = childNode.InnerText; + } } } }; - DisconnectionReasons = new DisconnectionReason[31] { + DisconnectionReasons = new DisconnectionReason[31] + { new DisconnectionReason(1, ""), new DisconnectionReason(2, ""), new DisconnectionReason(3, ""), @@ -250,7 +368,8 @@ static Server() { new DisconnectionReason(50331678, ""), new DisconnectionReason(50331686, "δܿ PIN") }; - ExtendedDisconnectionReasons = new DisconnectionReason[26] { + ExtendedDisconnectionReasons = new DisconnectionReason[26] + { new DisconnectionReason(0, "ûпõĸϢ"), new DisconnectionReason(1, ""), new DisconnectionReason(2, ""), @@ -281,94 +400,127 @@ static Server() { ServerTree.Instance.ServerChanged += OnServerChanged; } - protected Server() { + protected Server() + { _serverRefList = new List(); ChangeImageIndex(ImageConstants.DisconnectedServer); } - private static void OnServerChanged(ServerChangedEventArgs e) { - if (!e.ChangeType.HasFlag(ChangeType.PropertyChanged) || e.Server is not Server server) + private static void OnServerChanged(ServerChangedEventArgs e) + { + if (!e.ChangeType.HasFlag(ChangeType.PropertyChanged) || !(e.Server is Server server)) + { return; - - server.VisitServerRefs(delegate (ServerRef r) { + } + server.VisitServerRefs(delegate(ServerRef r) + { GroupBase group = r.Parent as GroupBase; if (ServerTree.Instance.SortGroup(group)) + { ServerTree.Instance.OnGroupChanged(group, ChangeType.InvalidateUI); + } }); } - public void SuspendFullScreenBehavior() { + public void SuspendFullScreenBehavior() + { Interlocked.Increment(ref _noFullScreenBehavior); } - public void ResumeFullScreenBehavior() { + public void ResumeFullScreenBehavior() + { Interlocked.Decrement(ref _noFullScreenBehavior); } - public string GetQualifiedNameForUI() { + public string GetQualifiedNameForUI() + { SplitName(base.ServerName, out var serverName, out var _); if (base.DisplayName.Equals(serverName, StringComparison.OrdinalIgnoreCase)) + { return base.DisplayName; - + } return $"{base.DisplayName} ({serverName})"; } - private void SetText() { + private void SetText() + { _serverBox.SetText(); if (IsClientInitialized) + { _client.SetText(); + } } - public string GetConnectionStateText() { - return ConnectionState switch { - RdpClient.ConnectionState.Disconnected => DisconnectedText, - RdpClient.ConnectionState.Connecting => ConnectingText, - RdpClient.ConnectionState.Connected => ConnectedText, + public string GetConnectionStateText() + { + return ConnectionState switch + { + RdpClient.ConnectionState.Disconnected => DisconnectedText, + RdpClient.ConnectionState.Connecting => ConnectingText, + RdpClient.ConnectionState.Connected => ConnectedText, _ => "<ȡı>", }; } - protected override void InitSettings() { + protected override void InitSettings() + { ((RdcTreeNode)this).Properties = new ServerSettings(); ((RdcTreeNode)this).DisplaySettings = new ServerDisplaySettings(); base.InitSettings(); } - internal override void Focus() { + internal override void Focus() + { if (!IsClientUndocked && UseServerBox) + { _serverBox.Focus(); + } else + { _client.Control.Focus(); + } } - internal override void FocusConnectedClient() { + internal override void FocusConnectedClient() + { if (IsConnected && IsClientInitialized) + { _client.Control.Focus(); + } } - internal void SetNormalView() { + internal void SetNormalView() + { DisplayState = DisplayStates.Normal; Size = Program.TheForm.GetClientSize(); Location = new Point(0, 0); EnableDisableClient(); } - internal bool Resize() { + internal bool Resize() + { bool flag = (IsClientDocked && DisplaySettings.SmartSizeDockedWindow.Value == RdpClient.SmartSizeMethod.Reconnect) || (!IsClientDocked && DisplaySettings.SmartSizeUndockedWindow.Value == RdpClient.SmartSizeMethod.Reconnect); - return IsClientInitialized && flag && _client.Resize((uint)Size.Width, (uint)Size.Height); + if (IsClientInitialized && flag) + { + return _client.Resize((uint)Size.Width, (uint)Size.Height); + } + return false; } - internal void SetThumbnailView(int left, int top, int width, int height) { + internal void SetThumbnailView(int left, int top, int width, int height) + { DisplayState = DisplayStates.Thumbnail; Size = new Size(width, height); Location = new Point(left, top); EnableDisableClient(); } - internal override void ScreenCapture() { + internal override void ScreenCapture() + { Control control = Client.Control; Graphics graphics = null; - try { + try + { Point point = control.PointToScreen(control.Location); Size size = control.Size; Bitmap bitmap = new Bitmap(size.Width, size.Height); @@ -376,30 +528,41 @@ internal override void ScreenCapture() { graphics.CopyFromScreen(point.X, point.Y, 0, 0, bitmap.Size); Clipboard.SetDataObject(bitmap); } - catch (Exception ex) { + catch (Exception ex) + { FormTools.ErrorDialog("ỰĻʱ" + ex.Message); } - finally { + finally + { graphics?.Dispose(); } } - protected void InitRequiredForDisplay() { + protected void InitRequiredForDisplay() + { _serverBox = new ServerBox(this); } - private void AddToClientPanel() { + private void AddToClientPanel() + { if (_serverBox.Parent == null) + { Program.TheForm.AddToClientPanel(_serverBox); + } } - private void RemoveFromClientPanel() { + private void RemoveFromClientPanel() + { if (_serverBox.Parent != null) + { Program.TheForm.RemoveFromClientPanel(_serverBox); + } } - private void InitClient() { - if (!IsClientInitialized) { + private void InitClient() + { + if (!IsClientInitialized) + { _client = RdpClient.AllocClient(this, Program.TheForm); _client.ConnectConnectionHandlers(OnConnected, OnConnecting, OnDisconnected, OnAutoReconnecting, OnAutoReconnecting2, OnAutoReconnected, OnFocusReleased); _client.ConnectContainerHandlers(OnRequestGoFullScreen, OnRequestLeaveFullScreen, OnRequestContainerMinimize, OnConfirmClose, OnFatalError); @@ -410,15 +573,18 @@ private void InitClient() { _client.Control.Location = _serverBox.Location; SetClientSizeProperties(); SetText(); - if (!UseServerBox && _serverBox.Visible) { + if (!UseServerBox && _serverBox.Visible) + { _client.Control.Show(); _serverBox.Hide(); } } } - private void DestroyClient() { - if (IsClientInitialized) { + private void DestroyClient() + { + if (IsClientInitialized) + { _client.DisconnectConnectionHandlers(OnConnected, OnConnecting, OnDisconnected, OnAutoReconnecting, OnAutoReconnecting2, OnAutoReconnected, OnFocusReleased); _client.DisconnectContainerHandlers(OnRequestGoFullScreen, OnRequestLeaveFullScreen, OnRequestContainerMinimize, OnConfirmClose, OnFatalError); RdpClient client = _client; @@ -427,11 +593,13 @@ private void DestroyClient() { } } - internal static Server CreateForAddDialog() { + internal static Server CreateForAddDialog() + { return new Server(); } - public static Server Create(string serverName, string displayName, GroupBase group) { + public static Server Create(string serverName, string displayName, GroupBase group) + { Server server = new Server(); server.Properties.ServerName.Value = serverName; server.Properties.DisplayName.Value = displayName; @@ -439,13 +607,15 @@ public static Server Create(string serverName, string displayName, GroupBase gro return server; } - internal static Server Create(ServerPropertiesDialog dlg) { + internal static Server Create(ServerPropertiesDialog dlg) + { Server server = dlg.AssociatedNode as Server; server.FinishConstruction(dlg.PropertiesPage.ParentGroup); return server; } - internal static Server Create(string name, ServerPropertiesDialog dlg) { + internal static Server Create(string name, ServerPropertiesDialog dlg) + { Server node = dlg.AssociatedNode as Server; Server server = new Server(); server.CopySettings(node, null); @@ -455,115 +625,152 @@ internal static Server Create(string name, ServerPropertiesDialog dlg) { return server; } - internal static Server Create(XmlNode xmlNode, GroupBase group, ICollection errors) { + internal static Server Create(XmlNode xmlNode, GroupBase group, ICollection errors) + { Server server = new Server(); server.ReadXml(xmlNode, errors); server.FinishConstruction(group); return server; } - protected void FinishConstruction(GroupBase group) { + protected void FinishConstruction(GroupBase group) + { if (string.IsNullOrEmpty(base.DisplayName)) + { Properties.DisplayName.Value = base.ServerName; - + } base.Text = base.DisplayName; InitRequiredForDisplay(); ServerTree.Instance.AddNode(this, group); } - private void ReadXml(XmlNode xmlNode, ICollection errors) { + private void ReadXml(XmlNode xmlNode, ICollection errors) + { ReadXml(PropertyActions, xmlNode, errors); } - public override void OnRemoving() { - VisitServerRefs(delegate (ServerRef r) { + public override void OnRemoving() + { + VisitServerRefs(delegate(ServerRef r) + { r.OnRemoveServer(); }); _serverRefList.Clear(); if (IsClientUndocked) + { ServerForm.Close(); - + } Hide(); _serverBox.Dispose(); _serverBox = null; DestroyClient(); } - internal override void Show() { + internal override void Show() + { AddToClientPanel(); if (UseServerBox) + { _serverBox.Show(); + } else + { _client.Control.Show(); + } } - internal override void Hide() { - if (DisplayState != 0) { + internal override void Hide() + { + if (DisplayState != 0) + { DisplayState = DisplayStates.Invalid; _serverBox.Hide(); RemoveFromClientPanel(); if (IsClientInPanel) + { _client.Control.Hide(); + } } } - public override void Connect() { + public override void Connect() + { ConnectAs(null, null); } - public override void ConnectAs(LogonCredentials logonCredentials, ConnectionSettings connectionSettings) { + public override void ConnectAs(LogonCredentials logonCredentials, ConnectionSettings connectionSettings) + { InitClient(); - lock (_connectionStateLock) { + lock (_connectionStateLock) + { if (IsConnected) + { return; - + } InheritSettings(); ResolveCredentials(); if (logonCredentials == null) + { logonCredentials = base.LogonCredentials; + } else + { ResolveCredentials(logonCredentials); - + } if (connectionSettings == null) + { connectionSettings = base.ConnectionSettings; - + } string text = "()"; - try { + try + { IMsRdpClientAdvancedSettings advancedSettings = _client.AdvancedSettings2; IMsRdpClientAdvancedSettings6 advancedSettings2 = _client.AdvancedSettings7; IMsRdpClientAdvancedSettings7 advancedSettings3 = _client.AdvancedSettings8; IMsRdpClientNonScriptable4 msRdpClientNonScriptable = (IMsRdpClientNonScriptable4)_client.GetOcx(); SplitName(base.ServerName, out var serverName, out var port); if (port == -1) + { port = base.ConnectionSettings.Port.Value; - + } text = ""; _client.MsRdpClient.Server = serverName; string userName = CredentialsUI.GetUserName(logonCredentials.UserName.Value); string value = logonCredentials.Domain.Value; - if (!string.IsNullOrEmpty(userName)) { + if (!string.IsNullOrEmpty(userName)) + { text = "û"; _client.MsRdpClient.UserName = userName; } else + { _client.MsRdpClient.UserName = null; - - if (!string.IsNullOrEmpty(value)) { + } + if (!string.IsNullOrEmpty(value)) + { text = ""; if (value.Equals("[server]", StringComparison.OrdinalIgnoreCase)) + { _client.MsRdpClient.Domain = base.ServerName; + } else if (value.Equals("[display]", StringComparison.OrdinalIgnoreCase)) + { _client.MsRdpClient.Domain = base.DisplayName; + } else + { _client.MsRdpClient.Domain = value; + } } else + { _client.MsRdpClient.Domain = null; - + } text = ""; if (logonCredentials.Password.IsDecrypted && !string.IsNullOrEmpty(logonCredentials.Password.Value)) + { advancedSettings.ClearTextPassword = logonCredentials.Password.Value; - + } advancedSettings.keepAliveInterval = 60000; advancedSettings2.HotKeyAltEsc = (int)Program.Preferences.HotKeyAltEsc; advancedSettings2.HotKeyAltSpace = (int)Program.Preferences.HotKeyAltSpace; @@ -577,8 +784,11 @@ public override void ConnectAs(LogonCredentials logonCredentials, ConnectionSett _client.SecuredSettings2.KeyboardHookMode = (int)base.LocalResourceSettings.KeyboardHookMode.Value; RdpClient.ConnectionBarState connectionBarState = Program.Preferences.ConnectionBarState; if (connectionBarState == RdpClient.ConnectionBarState.Off) + { advancedSettings.DisplayConnectionBar = false; - else { + } + else + { advancedSettings.DisplayConnectionBar = true; advancedSettings.PinConnectionBar = connectionBarState == RdpClient.ConnectionBarState.Pinned; } @@ -587,7 +797,8 @@ public override void ConnectAs(LogonCredentials logonCredentials, ConnectionSett advancedSettings.GrabFocusOnConnect = false; text = ""; ConfigureGateway(); - if (Properties.ConnectionType.Value == ConnectionType.VirtualMachineConsoleConnect) { + if (Properties.ConnectionType.Value == ConnectionType.VirtualMachineConsoleConnect) + { advancedSettings3.PCB = Properties.VirtualMachineId.Value; advancedSettings.RDPPort = 2179; advancedSettings.ConnectToServerConsole = true; @@ -596,24 +807,28 @@ public override void ConnectAs(LogonCredentials logonCredentials, ConnectionSett advancedSettings2.EnableCredSspSupport = true; advancedSettings3.NegotiateSecurityLayer = false; } - else { + else + { text = "˿"; advancedSettings.RDPPort = port; advancedSettings.BitmapPeristence = (Program.Preferences.PersistentBitmapCaching ? 1 : 0); text = "ؾϢ"; string text2 = base.ConnectionSettings.LoadBalanceInfo.Value; - if (!string.IsNullOrEmpty(text2)) { + if (!string.IsNullOrEmpty(text2)) + { if (text2.Length % 2 == 1) + { text2 += " "; - + } text2 += Environment.NewLine; byte[] bytes = Encoding.UTF8.GetBytes(text2); advancedSettings.LoadBalanceInfo = Encoding.Unicode.GetString(bytes); } text = "ӵ̨"; if (advancedSettings2 != null) + { advancedSettings2.ConnectToAdministerServer = connectionSettings.ConnectToConsole.Value; - + } advancedSettings.ConnectToServerConsole = connectionSettings.ConnectToConsole.Value; text = ""; _client.SecuredSettings.StartProgram = base.ConnectionSettings.StartProgram.Value; @@ -623,23 +838,28 @@ public override void ConnectAs(LogonCredentials logonCredentials, ConnectionSett advancedSettings.EnableWindowsKey = 1; text = "Դ"; _client.SecuredSettings2.AudioRedirectionMode = (int)base.LocalResourceSettings.AudioRedirectionMode.Value; - if (advancedSettings3 != null) { + if (advancedSettings3 != null) + { advancedSettings3.AudioQualityMode = (uint)base.LocalResourceSettings.AudioRedirectionQuality.Value; advancedSettings3.AudioCaptureRedirectionMode = base.LocalResourceSettings.AudioCaptureRedirectionMode.Value == RdpClient.AudioCaptureRedirectionMode.Record; - if (RdpClient.SupportsPanning) { + if (RdpClient.SupportsPanning) + { advancedSettings3.EnableSuperPan = Program.Preferences.EnablePanning; advancedSettings3.SuperPanAccelerationFactor = (uint)Program.Preferences.PanningAcceleration; } } - if (RdpClient.SupportsFineGrainedRedirection) { + if (RdpClient.SupportsFineGrainedRedirection) + { IMsRdpDriveCollection driveCollection = _client.ClientNonScriptable3.DriveCollection; - for (uint num = 0u; num < driveCollection.DriveCount; num++) { + for (uint num = 0u; num < driveCollection.DriveCount; num++) + { IMsRdpDrive msRdpDrive = driveCollection.get_DriveByIndex(num); string item = msRdpDrive.Name.Substring(0, msRdpDrive.Name.Length - 1); msRdpDrive.RedirectionState = base.LocalResourceSettings.RedirectDrivesList.Value.Contains(item); } } - else { + else + { advancedSettings.RedirectDrives = base.LocalResourceSettings.RedirectDrives.Value; } advancedSettings.RedirectPorts = base.LocalResourceSettings.RedirectPorts.Value; @@ -652,11 +872,13 @@ public override void ConnectAs(LogonCredentials logonCredentials, ConnectionSett _client.MsRdpClient.ColorDepth = base.RemoteDesktopSettings.ColorDepth.Value; text = "ȫ"; _client.AdvancedSettings5.AuthenticationLevel = (uint)base.SecuritySettings.AuthenticationLevel.Value; - if (advancedSettings2 != null) { + if (advancedSettings2 != null) + { advancedSettings2.EnableCredSspSupport = true; msRdpClientNonScriptable.PromptForCredentials = false; msRdpClientNonScriptable.NegotiateSecurityLayer = true; - if (base.SecuritySettings.RemoteGuard.Value) { + if (base.SecuritySettings.RemoteGuard.Value) + { text = "ȫ - Զƾݱ"; IMsRdpExtendedSettings msRdpExtendedSettings = (IMsRdpExtendedSettings)_client.GetOcx(); object pValue = true; @@ -664,7 +886,8 @@ public override void ConnectAs(LogonCredentials logonCredentials, ConnectionSett pValue = true; msRdpExtendedSettings.set_Property("DisableCredentialsDelegation", ref pValue); } - else if (base.SecuritySettings.RestrictedAdmin.Value) { + else if (base.SecuritySettings.RestrictedAdmin.Value) + { text = "ȫ - ޹Ա"; IMsRdpExtendedSettings msRdpExtendedSettings2 = (IMsRdpExtendedSettings)_client.GetOcx(); object pValue = true; @@ -676,11 +899,13 @@ public override void ConnectAs(LogonCredentials logonCredentials, ConnectionSett } text = "ͻ"; _disconnectionReason = string.Empty; - using (Helpers.Timer("invoking connect on {0} client", base.DisplayName)) { + using (Helpers.Timer("invoking connect on {0} client", base.DisplayName)) + { _client.MsRdpClient.Connect(); } } - catch (Exception ex) { + catch (Exception ex) + { ConnectionState = RdpClient.ConnectionState.Disconnected; _disconnectionReason = "ʱ"; FormTools.ErrorDialog("漰Ĵ '" + text + "':\n" + ex.Message); @@ -689,93 +914,116 @@ public override void ConnectAs(LogonCredentials logonCredentials, ConnectionSett } } - internal void DumpSessionState() { - using (Helpers.Timer("dumping session state of {0}", base.DisplayName)) { + internal void DumpSessionState() + { + using (Helpers.Timer("dumping session state of {0}", base.DisplayName)) + { _client.Dump(); } } - internal static void SplitName(string qualifiedName, out string serverName, out int port) { + internal static void SplitName(string qualifiedName, out string serverName, out int port) + { string[] array = qualifiedName.Split(new char[1] { ':' }, StringSplitOptions.RemoveEmptyEntries); serverName = ((array.Length != 0) ? array[0] : string.Empty); if (array.Length != 2 || !int.TryParse(array[1], out port)) + { port = -1; + } } - private void ConfigureGateway() { + private void ConfigureGateway() + { IMsRdpClientTransportSettings transportSettings = _client.TransportSettings; - if (base.GatewaySettings.UseGatewayServer.Value) { + if (base.GatewaySettings.UseGatewayServer.Value) + { uint gatewayUsageMethod = ((!base.GatewaySettings.BypassGatewayForLocalAddresses.Value) ? 1u : 2u); transportSettings.GatewayProfileUsageMethod = 1u; transportSettings.GatewayUsageMethod = gatewayUsageMethod; - uint num = (transportSettings.GatewayCredsSource = (uint)base.GatewaySettings.LogonMethod.Value); + transportSettings.GatewayCredsSource = (uint)base.GatewaySettings.LogonMethod.Value; transportSettings.GatewayHostname = base.GatewaySettings.HostName.Value; IMsRdpClientTransportSettings2 transportSettings2 = _client.TransportSettings2; - if (transportSettings2 != null) { + if (transportSettings2 != null) + { transportSettings2.GatewayCredSharing = (base.GatewaySettings.CredentialSharing.Value ? 1u : 0u); - if (base.GatewaySettings.LogonMethod.Value == RdpClient.GatewayLogonMethod.NTLM) { + if (base.GatewaySettings.LogonMethod.Value == RdpClient.GatewayLogonMethod.NTLM) + { transportSettings2.GatewayUsername = base.GatewaySettings.UserName.Value; transportSettings2.GatewayDomain = base.GatewaySettings.Domain.Value; transportSettings2.GatewayPassword = base.GatewaySettings.Password.Value; } } } - else { + else + { transportSettings.GatewayProfileUsageMethod = 0u; transportSettings.GatewayUsageMethod = 0u; } } - public override void Reconnect() { + public override void Reconnect() + { Log.Write("Begin reconnect to {0}", base.DisplayName); ReconnectServerRef reconnectServerRef = ReconnectGroup.Instance.AddReference(this); reconnectServerRef.Start(removeAfterConnection: true); } - public override void Disconnect() { - using (Helpers.Timer("invoking disconnect on the {0} client", base.DisplayName)) { + public override void Disconnect() + { + using (Helpers.Timer("invoking disconnect on the {0} client", base.DisplayName)) + { if (!IsConnected) + { return; - - try { + } + try + { _client.MsRdpClient.Disconnect(); } - catch (Exception ex) { + catch (Exception ex) + { Log.Write("Error disconnection: {0}", ex.Message); } } } - public override void LogOff() { + public override void LogOff() + { Log.Write("Begin logoff from {0}", base.DisplayName); if (IsConnected) + { ThreadPool.QueueUserWorkItem(LogOffWorkerProc, this); + } } - private static void LogOffWorkerProc(object o) { + private static void LogOffWorkerProc(object o) + { Server server = o as Server; RemoteSessions remoteSessions = new RemoteSessions(server); bool success = true; string reason = string.Empty; - try { - if (!remoteSessions.OpenServer()) { + try + { + if (!remoteSessions.OpenServer()) + { success = false; reason = "޷Զ̻Ự"; return; } IList list = remoteSessions.QuerySessions(); - if (list == null) { + if (list == null) + { success = false; reason = "޷öԶ̻Ự"; return; } int num = -1; - foreach (RemoteSessionInfo item in list) { - if (item.State == Wts.ConnectstateClass.Active - && item.ClientName.Equals(Environment.MachineName, StringComparison.OrdinalIgnoreCase) - && item.UserName.Equals(server._client.MsRdpClient.UserName, StringComparison.OrdinalIgnoreCase) - && item.DomainName.Equals(server._client.MsRdpClient.Domain, StringComparison.OrdinalIgnoreCase)) { - if (num != -1) { + foreach (RemoteSessionInfo item in list) + { + if (item.State == Wts.ConnectstateClass.Active && item.ClientName.Equals(Environment.MachineName, StringComparison.OrdinalIgnoreCase) && item.UserName.Equals(server._client.MsRdpClient.UserName, StringComparison.OrdinalIgnoreCase) && item.DomainName.Equals(server._client.MsRdpClient.Domain, StringComparison.OrdinalIgnoreCase)) + { + if (num != -1) + { success = false; reason = "Ự޷ȷҪעĻỰ"; return; @@ -783,226 +1031,300 @@ private static void LogOffWorkerProc(object o) { num = item.SessionId; } } - if (success) { + if (success) + { success = remoteSessions.LogOffSession(num); reason = "עỰ API ʧ"; } } - catch { + catch + { success = false; reason = "ڲ"; } - finally { + finally + { remoteSessions.CloseServer(); - Program.TheForm.Invoke((MethodInvoker)delegate { + Program.TheForm.Invoke((MethodInvoker)delegate + { server.LogOffResultCallback(success, reason); }); } } - private void LogOffResultCallback(bool success, string text) { + private void LogOffResultCallback(bool success, string text) + { Log.Write("End logoff from {0}", base.DisplayName); if (!success) + { FormTools.ErrorDialog("޷ " + base.DisplayName + " ע \r\nԭ" + text); + } } - private void OnConnecting(object sender, EventArgs e) { - lock (_connectionStateLock) { + private void OnConnecting(object sender, EventArgs e) + { + lock (_connectionStateLock) + { Log.Write("OnConnecting {0}", base.DisplayName); UpdateOnConnectionStateChange(ImageConstants.ConnectingServer, RdpClient.ConnectionState.Connecting); } } - private void OnConnected(object sender, EventArgs e) { - lock (_connectionStateLock) { + private void OnConnected(object sender, EventArgs e) + { + lock (_connectionStateLock) + { Log.Write("OnConnected {0}", base.DisplayName); Location = new Point(Location.X, Location.Y); UpdateOnConnectionStateChange(ImageConstants.ConnectedServer, RdpClient.ConnectionState.Connected); if (ServerTree.Instance.SelectedNode is ServerBase serverBase && serverBase.ServerNode == this) + { Focus(); + } } } - private void OnDisconnected(object sender, IMsTscAxEvents_OnDisconnectedEvent e) { - lock (_connectionStateLock) { + private void OnDisconnected(object sender, IMsTscAxEvents_OnDisconnectedEvent e) + { + lock (_connectionStateLock) + { Log.Write("OnDisconnected {0}: discReason={1} extendedDisconnectReason={2}", base.DisplayName, e.discReason, _client.MsRdpClient.ExtendedDisconnectReason); _disconnectionReason = string.Empty; DisconnectionReason disconnectionReason = null; - if (_client.MsRdpClient.ExtendedDisconnectReason != 0) { + if (_client.MsRdpClient.ExtendedDisconnectReason != 0) + { disconnectionReason = ExtendedDisconnectionReasons.SingleOrDefault((DisconnectionReason r) => r.Code == (int)_client.MsRdpClient.ExtendedDisconnectReason); if (disconnectionReason == null) + { _disconnectionReason = $"δ֪չϿԭ {_client.MsRdpClient.ExtendedDisconnectReason}"; + } } - else if (e != null) { + else if (e != null) + { disconnectionReason = DisconnectionReasons.SingleOrDefault((DisconnectionReason r) => r.Code == e.discReason); if (disconnectionReason == null) + { _disconnectionReason = $"ԭ {e.discReason}"; + } } if (disconnectionReason != null) + { _disconnectionReason = disconnectionReason.Text; - - if (_client.MsRdpClient.FullScreen) { + } + if (_client.MsRdpClient.FullScreen) + { ParentForm.LeaveFullScreenClient(this); _client.MsRdpClient.FullScreen = false; } - if (IsClientDocked) { + if (IsClientDocked) + { if (_client.Control.Visible) + { _serverBox.Show(); - + } DestroyClient(); } UpdateOnConnectionStateChange(ImageConstants.DisconnectedServer, RdpClient.ConnectionState.Disconnected); } } - private void OnAutoReconnecting(object sender, IMsTscAxEvents_OnAutoReconnectingEvent e) { + private AutoReconnectContinueState OnAutoReconnecting(object sender, IMsTscAxEvents_OnAutoReconnectingEvent e) + { Log.Write("OnAutoReconnecting {0}: disconnectReason={1} attemptCount={2}", base.DisplayName, e.disconnectReason, e.attemptCount); - } + return AutoReconnectContinueState.autoReconnectContinueAutomatic; - private void OnAutoReconnecting2(object sender, IMsTscAxEvents_OnAutoReconnecting2Event e) { + } + + private void OnAutoReconnecting2(object sender, IMsTscAxEvents_OnAutoReconnecting2Event e) + { Log.Write("OnAutoReconnecting2 {0}: disconnectReason={1} networkAvailable={2} attemptCount={3} maxAttemptCount={4}", base.DisplayName, e.disconnectReason, e.networkAvailable, e.attemptCount, e.maxAttemptCount); } - private void OnAutoReconnected(object sender, EventArgs e) { + private void OnAutoReconnected(object sender, EventArgs e) + { Log.Write("OnAutoReconnected {0}", base.DisplayName); } - private void UpdateOnConnectionStateChange(ImageConstants image, RdpClient.ConnectionState state) { - using (Helpers.Timer("changing connection state of {0} to {1}", base.DisplayName, state)) { + private void UpdateOnConnectionStateChange(ImageConstants image, RdpClient.ConnectionState state) + { + using (Helpers.Timer("changing connection state of {0} to {1}", base.DisplayName, state)) + { ChangeImageIndex(image); ConnectionState = state; if (_serverBox != null) + { _serverBox.SetText(); + } } } - private void OnFocusReleased(object sender, IMsTscAxEvents_OnFocusReleasedEvent e) { + private void OnFocusReleased(object sender, IMsTscAxEvents_OnFocusReleasedEvent e) + { Log.Write("OnFocusReleased {0}: direction={1}", base.DisplayName, e.iDirection); NodeHelper.SelectNewActiveConnection(e.iDirection == -1); } - private void OnConfirmClose(object sender, IMsTscAxEvents_OnConfirmCloseEvent e) { - e.pfAllowClose = true; + private bool OnConfirmClose(object sender, IMsTscAxEvents_OnConfirmCloseEvent e) + { + //e.pfAllowClose = true; + return true; } - private void OnRequestContainerMinimize(object sender, EventArgs e) { + private void OnRequestContainerMinimize(object sender, EventArgs e) + { Log.Write("OnRequestContainerMinimize {0}", base.DisplayName); ParentForm.WindowState = FormWindowState.Minimized; } - private void OnRequestGoFullScreen(object sender, EventArgs e) { + private void OnRequestGoFullScreen(object sender, EventArgs e) + { Log.Write("OnRequestGoFullScreen {0}", base.DisplayName); if (_noFullScreenBehavior <= 0) + { ParentForm.GoFullScreenClient(this, Program.Preferences.FullScreenWindowIsTopMost); + } } - public void SetClientSizeProperties() { - if (IsClientFullScreen) { + public void SetClientSizeProperties() + { + if (IsClientFullScreen) + { Client.AdvancedSettings2.SmartSizing = false; return; } InheritSettings(); if (IsClientInPanel) + { Client.AdvancedSettings2.SmartSizing = base.IsThumbnail || DisplaySettings.SmartSizeDockedWindow.Value == RdpClient.SmartSizeMethod.Scale; + } else if (IsClientInitialized) + { Client.AdvancedSettings2.SmartSizing = DisplaySettings.SmartSizeUndockedWindow.Value == RdpClient.SmartSizeMethod.Scale; + } } - private void OnRequestLeaveFullScreen(object sender, EventArgs e) { + private void OnRequestLeaveFullScreen(object sender, EventArgs e) + { Log.Write("OnRequestLeaveFullScreen {0}", base.DisplayName); - if (_noFullScreenBehavior <= 0) { + if (_noFullScreenBehavior <= 0) + { ParentForm.LeaveFullScreenClient(this); if (!base.IsThumbnail) + { SetNormalView(); + } } } - private void OnFatalError(object sender, IMsTscAxEvents_OnFatalErrorEvent e) { + private void OnFatalError(object sender, IMsTscAxEvents_OnFatalErrorEvent e) + { Log.Write("OnFatalError {0}: errorCode={1}", base.DisplayName, e.errorCode); } - public void AddServerRef(ServerRef serverRef) { + public void AddServerRef(ServerRef serverRef) + { _serverRefList.Add(serverRef); } - public TServerRef FindServerRef() where TServerRef : ServerRef { + public TServerRef FindServerRef() where TServerRef : ServerRef + { return _serverRefList.FirstOrDefault((ServerRef r) => r is TServerRef) as TServerRef; } - public TServerRef FindServerRef(GroupBase parent) where TServerRef : ServerRef { + public TServerRef FindServerRef(GroupBase parent) where TServerRef : ServerRef + { return _serverRefList.FirstOrDefault((ServerRef r) => r is TServerRef && r.Parent == parent) as TServerRef; } - public void RemoveServerRef(ServerRef serverRef) { + public void RemoveServerRef(ServerRef serverRef) + { _serverRefList.Remove(serverRef); } - public void VisitServerRefs(Action action) { + public void VisitServerRefs(Action action) + { ServerRef[] array = new ServerRef[_serverRefList.Count]; _serverRefList.CopyTo(array); array.ForEach(action); } - public override void ChangeImageIndex(ImageConstants index) { + public override void ChangeImageIndex(ImageConstants index) + { base.ChangeImageIndex(index); - VisitServerRefs(delegate (ServerRef r) { + VisitServerRefs(delegate(ServerRef r) + { r.ChangeImageIndex(index); }); } - public void SendRemoteAction(RemoteSessionActionType action) { + public void SendRemoteAction(RemoteSessionActionType action) + { IMsRdpClient8 msRdpClient = _client.MsRdpClient8; msRdpClient.SendRemoteAction(action); } - internal override void UpdateSettings(NodePropertiesDialog nodeDialog) { + internal override void UpdateSettings(NodePropertiesDialog nodeDialog) + { base.UpdateSettings(nodeDialog); if (!(nodeDialog is ServerPropertiesDialog)) + { return; - + } base.Text = base.DisplayName; - if (base.TreeView != null) { + if (base.TreeView != null) + { SetText(); - VisitServerRefs(delegate (ServerRef r) { + VisitServerRefs(delegate(ServerRef r) + { r.Text = base.Text; }); } } - internal void UpdateFromTemplate(Server template) { + internal void UpdateFromTemplate(Server template) + { CopySettings(template, typeof(ServerSettings)); } - public override void DoPropertiesDialog(Form parentForm, string activeTabName) { + public override void DoPropertiesDialog(Form parentForm, string activeTabName) + { using ServerPropertiesDialog serverPropertiesDialog = ServerPropertiesDialog.NewPropertiesDialog(this, parentForm); serverPropertiesDialog.SetActiveTab(activeTabName); - if (serverPropertiesDialog.ShowDialog() == DialogResult.OK) { + if (serverPropertiesDialog.ShowDialog() == DialogResult.OK) + { UpdateSettings(serverPropertiesDialog); ServerTree.Instance.OnNodeChanged(this, ChangeType.PropertyChanged); ServerTree.Instance.OnGroupChanged(base.Parent as GroupBase, ChangeType.InvalidateUI); } } - public override void CollectNodesToInvalidate(bool recurseChildren, HashSet set) { + public override void CollectNodesToInvalidate(bool recurseChildren, HashSet set) + { set.Add(this); - _serverRefList.ForEach(delegate (ServerRef r) { + _serverRefList.ForEach(delegate(ServerRef r) + { r.CollectNodesToInvalidate(recurseChildren, set); }); } - internal override void WriteXml(XmlTextWriter tw) { + internal override void WriteXml(XmlTextWriter tw) + { tw.WriteStartElement("server"); WriteXmlSettingsGroups(tw); tw.WriteEndElement(); } - public override bool CanDropOnTarget(RdcTreeNode targetNode) { + public override bool CanDropOnTarget(RdcTreeNode targetNode) + { GroupBase groupBase = (targetNode as GroupBase) ?? (targetNode.Parent as GroupBase); - if (groupBase != null) { - if (groupBase.CanDropServers()) { + if (groupBase != null) + { + if (groupBase.CanDropServers()) + { if (groupBase.DropBehavior() != DragDropEffects.Copy) + { return AllowEdit(popUI: false); - + } return true; } return false; @@ -1010,15 +1332,18 @@ public override bool CanDropOnTarget(RdcTreeNode targetNode) { return false; } - public override bool ConfirmRemove(bool askUser) { - if (IsConnected) { - FormTools.InformationDialog(base.Text + " һỰɾ֮ǰҪȶϿӡ"); + public override bool ConfirmRemove(bool askUser) + { + if (IsConnected) + { + FormTools.InformationDialog(base.Text + "һỰɾ֮ǰҪȶϿӡ"); return false; } return base.ConfirmRemove(askUser); } - private Size GetRemoteDesktopSize() { + private Size GetRemoteDesktopSize() + { if (base.RemoteDesktopSettings.DesktopSizeSameAsClientAreaSize.Value) return IsClientDocked ? Program.TheForm.GetClientSize() : ServerForm.ClientSize; @@ -1028,70 +1353,89 @@ private Size GetRemoteDesktopSize() { return base.RemoteDesktopSettings.DesktopSize.Value; } - internal override void GoFullScreen() { - if (IsConnected) { + internal override void GoFullScreen() + { + if (IsConnected) + { RdpClient client = Client; - if (client != null) { + if (client != null) + { client.Control.Enabled = true; client.MsRdpClient.FullScreen = true; } } } - internal override void LeaveFullScreen() { - if (IsConnected) { - RdpClient client = Client; - if (client != null) - client.MsRdpClient.FullScreen = false; + internal override void LeaveFullScreen() + { + if (IsConnected) + { + if (Client != null) + { + Client.MsRdpClient.FullScreen = false; + } } } - internal override void Undock() { - if (IsClientDocked) { + internal override void Undock() + { + if (IsClientDocked) + { InitClient(); Program.TheForm.RemoveFromClientPanel(_client.Control); bool visible = _client.Control.Visible; _client.Control.Enabled = true; ServerForm form = new ServerForm(this); - Program.PluginAction(delegate (IPlugin p) { + Program.PluginAction(delegate(IPlugin p) + { p.OnUndockServer(form); }); Program.ShowForm(form); _serverBox.SetText(); if (visible) + { _serverBox.Show(); + } } } - internal override void Dock() { - if (IsClientUndocked) { + internal override void Dock() + { + if (IsClientUndocked) + { ServerForm.Close(); return; } _serverBox.SetText(); - if (!IsConnected) { + if (!IsConnected) + { DestroyClient(); return; } Program.TheForm.AddToClientPanel(_client.Control); SetClientSizeProperties(); - if (_serverBox.Visible && !UseServerBox) { + if (_serverBox.Visible && !UseServerBox) + { _client.Control.Size = _serverBox.Size; _client.Control.Location = _serverBox.Location; _serverBox.Hide(); } else + { _client.Control.Hide(); - + } EnableDisableClient(); } - private void ClientGotFocus(object sender, EventArgs args) { + private void ClientGotFocus(object sender, EventArgs args) + { Server.FocusReceived?.Invoke(this); } - internal void EnableDisableClient() { - if (IsClientInitialized && IsClientDocked) { + internal void EnableDisableClient() + { + if (IsClientInitialized && IsClientDocked) + { GroupBase groupBase = base.Parent as GroupBase; groupBase.InheritSettings(); Client.Control.Enabled = !base.IsThumbnail || groupBase.DisplaySettings.AllowThumbnailSessionInteraction.Value; diff --git a/RdcMan/ServerBase.cs b/RdcMan/ServerBase.cs index 547c115..fb32547 100644 --- a/RdcMan/ServerBase.cs +++ b/RdcMan/ServerBase.cs @@ -1,9 +1,12 @@ using System.Drawing; using System.Windows.Forms; -namespace RdcMan { - public abstract class ServerBase : RdcTreeNode { - public enum DisplayStates { +namespace RdcMan +{ + public abstract class ServerBase : RdcTreeNode + { + public enum DisplayStates + { Invalid, Normal, Thumbnail @@ -37,15 +40,20 @@ public enum DisplayStates { public abstract Server ServerNode { get; } - public override bool ConfirmRemove(bool askUser) { + public override bool ConfirmRemove(bool askUser) + { if (!CanRemove(popUI: true)) + { return false; - - if (askUser) { + } + if (askUser) + { string text = "ӡ{2}ɾ{0}{1}".InvariantFormat(base.Text, RemoveTypeDescription, base.Parent.Text); DialogResult dialogResult = FormTools.YesNoDialog(ParentForm, text, MessageBoxDefaultButton.Button1); if (dialogResult != DialogResult.Yes) + { return false; + } } return true; } diff --git a/RdcMan/ServerBox.cs b/RdcMan/ServerBox.cs index c48ee9d..f3ffdaa 100644 --- a/RdcMan/ServerBox.cs +++ b/RdcMan/ServerBox.cs @@ -2,19 +2,44 @@ using System.Drawing; using System.Windows.Forms; -namespace RdcMan { - public class ServerBox : Label { +namespace RdcMan +{ + public class ServerBox : Label + { private Server _server; - public ServerBox(Server server) { + public ServerBox(Server server) + { _server = server; BackColor = Color.White; BorderStyle = BorderStyle.FixedSingle; TextAlign = ContentAlignment.MiddleCenter; Hide(); } + /// + /// δͣʱ˫Զʾ lzpong 2023/05/19 + /// + /// + protected override void OnMouseDown(MouseEventArgs e) { + if (e.Button == MouseButtons.Left) { + if (e.Clicks == 1) { + //Focus(); + return; + } + ServerTree.Instance.SelectedNode = _server; + _server.Connect(); + _server.Focus(); + } + } - public void SetText() { + public void DbClickShow() { + ServerTree.Instance.SelectedNode = _server; + _server.Connect(); + _server.Focus(); + } + + public void SetText() + { string text = _server.GetConnectionStateText(); if (_server.IsClientUndocked) text = text + Environment.NewLine + "{ δͣ }"; diff --git a/RdcMan/ServerChangedEventArgs.cs b/RdcMan/ServerChangedEventArgs.cs index 1a336f1..51cef8e 100644 --- a/RdcMan/ServerChangedEventArgs.cs +++ b/RdcMan/ServerChangedEventArgs.cs @@ -1,12 +1,15 @@ using System; -namespace RdcMan { - public class ServerChangedEventArgs : EventArgs { +namespace RdcMan +{ + public class ServerChangedEventArgs : EventArgs + { public ServerBase Server { get; private set; } public ChangeType ChangeType { get; private set; } - public ServerChangedEventArgs(ServerBase server, ChangeType changeType) { + public ServerChangedEventArgs(ServerBase server, ChangeType changeType) + { Server = server; ChangeType = changeType; } diff --git a/RdcMan/ServerDisplaySettings.cs b/RdcMan/ServerDisplaySettings.cs index 02f32d7..32b1d6e 100644 --- a/RdcMan/ServerDisplaySettings.cs +++ b/RdcMan/ServerDisplaySettings.cs @@ -1,17 +1,21 @@ using System.Collections.Generic; using System.Windows.Forms; -namespace RdcMan { - public class ServerDisplaySettings : CommonDisplaySettings { +namespace RdcMan +{ + public class ServerDisplaySettings : CommonDisplaySettings + { private static Dictionary _settingProperties; protected override Dictionary SettingProperties => _settingProperties; - static ServerDisplaySettings() { + static ServerDisplaySettings() + { typeof(ServerDisplaySettings).GetSettingProperties(out _settingProperties); } - public override TabPage CreateTabPage(TabbedSettingsDialog dialog) { + public override TabPage CreateTabPage(TabbedSettingsDialog dialog) + { return new ServerDisplaySettingsTabPage(dialog, this); } } diff --git a/RdcMan/ServerDisplaySettingsTabPage.cs b/RdcMan/ServerDisplaySettingsTabPage.cs index 0ee2697..fb73a2d 100644 --- a/RdcMan/ServerDisplaySettingsTabPage.cs +++ b/RdcMan/ServerDisplaySettingsTabPage.cs @@ -1,7 +1,10 @@ -namespace RdcMan { - public class ServerDisplaySettingsTabPage : DisplaySettingsTabPage { +namespace RdcMan +{ + public class ServerDisplaySettingsTabPage : DisplaySettingsTabPage + { public ServerDisplaySettingsTabPage(TabbedSettingsDialog dialog, ServerDisplaySettings settings) - : base(dialog, settings) { + : base(dialog, settings) + { Create(out var _, out var _); } } diff --git a/RdcMan/ServerForm.cs b/RdcMan/ServerForm.cs index e1076e7..83be8c3 100644 --- a/RdcMan/ServerForm.cs +++ b/RdcMan/ServerForm.cs @@ -3,8 +3,10 @@ using System.Drawing; using System.Windows.Forms; -namespace RdcMan { - internal class ServerForm : RdcBaseForm, IUndockedServerForm { +namespace RdcMan +{ + internal class ServerForm : RdcBaseForm, IUndockedServerForm + { private static readonly Dictionary> Shortcuts; private static readonly List ServerForms; @@ -35,24 +37,29 @@ internal class ServerForm : RdcBaseForm, IUndockedServerForm { ServerBase IUndockedServerForm.Server => _server; - static ServerForm() { + static ServerForm() + { ServerForms = new List(); - Shortcuts = new Dictionary> { + Shortcuts = new Dictionary> + { { Keys.Return, - delegate(ServerForm f) { + delegate(ServerForm f) + { f._server.Connect(); } }, { Keys.Return | Keys.Shift, - delegate(ServerForm f) { + delegate(ServerForm f) + { f._server.DoConnectAs(); } }, { Keys.Return | Keys.Alt, - delegate(ServerForm f) { + delegate(ServerForm f) + { f._server.DoPropertiesDialog(); } } @@ -61,36 +68,46 @@ static ServerForm() { ServerTree.Instance.ServerChanged += OnServerChanged; } - private static void OnGroupChanged(GroupChangedEventArgs e) { + private static void OnGroupChanged(GroupChangedEventArgs e) + { if (!e.ChangeType.HasFlag(ChangeType.PropertyChanged)) + { return; - - using (Helpers.Timer("updating server form settings from group {0}", e.Group.Text)) { + } + using (Helpers.Timer("updating server form settings from group {0}", e.Group.Text)) + { if (e.Group == ServerTree.Instance.RootNode) + { UpdateFromGlobalSettings(); - + } UpdateFromServerSettings(); } } - private static void OnServerChanged(ServerChangedEventArgs e) { + private static void OnServerChanged(ServerChangedEventArgs e) + { if (!e.ChangeType.HasFlag(ChangeType.PropertyChanged)) + { return; - - using (Helpers.Timer("updating server form settings from server {0}", e.Server.DisplayName)) { + } + using (Helpers.Timer("updating server form settings from server {0}", e.Server.DisplayName)) + { UpdateFromServerSettings(); } } - private static void UpdateFromServerSettings() { - ServerForms.ForEach(delegate (ServerForm f) { + private static void UpdateFromServerSettings() + { + ServerForms.ForEach(delegate(ServerForm f) + { f._server.InheritSettings(); f._server.SetClientSizeProperties(); f.SetTitle(); }); } - public ServerForm(Server server) { + public ServerForm(Server server) + { _server = server; server.InheritSettings(); base.Icon = Program.TheForm.Icon; @@ -105,55 +122,67 @@ public ServerForm(Server server) { ServerForms.Add(this); } - private static void UpdateFromGlobalSettings() { - ServerForms.ForEach(delegate (ServerForm f) { + private static void UpdateFromGlobalSettings() + { + ServerForms.ForEach(delegate(ServerForm f) + { f.SetMainMenuVisibility(); f.SetClientSize(f._clientSize); }); } - public override void SetClientSize(Size size) { + public override void SetClientSize(Size size) + { int num = ((!Program.Preferences.HideMainMenu) ? _menuPanel.Height : 0); base.ClientSize = new Size(size.Width, size.Height + num); } - public override Size GetClientSize() { + public override Size GetClientSize() + { return _clientSize; } - protected override void OnShown(EventArgs e) { + protected override void OnShown(EventArgs e) + { _server.Client.Control.Show(); } - protected override void OnClosed(EventArgs e) { + protected override void OnClosed(EventArgs e) + { ServerForms.Remove(this); _server.LeaveFullScreen(); base.Controls.Remove(_server.Client.Control); _server.Dock(); } - protected override void OnSizeChanged(EventArgs e) { + protected override void OnSizeChanged(EventArgs e) + { base.OnSizeChanged(e); int num = ((!Program.Preferences.HideMainMenu) ? _menuPanel.Height : 0); if (_clientSize.Width != 0 && _clientSize.Height != -num) + { _savedClientSize = _clientSize; - + } _clientSize = new Size(base.ClientSize.Width, base.ClientSize.Height - num); LayoutContent(); - if (_clientSize.Width != 0 && _clientSize.Height != -num && (_savedClientSize.Width != _clientSize.Width || _savedClientSize.Height != _clientSize.Height)) { + if (_clientSize.Width != 0 && _clientSize.Height != -num && (_savedClientSize.Width != _clientSize.Width || _savedClientSize.Height != _clientSize.Height)) + { _server.Size = _clientSize; _server.Resize(); } } - protected override void LayoutContent() { + protected override void LayoutContent() + { int num = ((!Program.Preferences.HideMainMenu) ? _menuPanel.Height : 0); _server.Client.Control.Bounds = new Rectangle(0, num, _clientSize.Width, _clientSize.Height); _menuPanel.Width = base.ClientSize.Width; } - protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { - if (!_menuStrip.IsActive && Shortcuts.TryGetValue(keyData, out var value)) { + protected override bool ProcessCmdKey(ref Message msg, Keys keyData) + { + if (!_menuStrip.IsActive && Shortcuts.TryGetValue(keyData, out var value)) + { value(this); return true; } @@ -218,7 +247,8 @@ protected void CreateMainMenu() { })); } - protected override void UpdateMainMenu() { + protected override void UpdateMainMenu() + { UpdateMenuItems(_menuStrip.Items); bool isConnected = _server.IsConnected; _sessionConnectServerMenuItem.Enabled = !isConnected; @@ -226,14 +256,16 @@ protected override void UpdateMainMenu() { _sessionReconnectServerMenuItem.Enabled = isConnected; _sessionSendKeysMenuItem.Enabled = isConnected; if (RdpClient.SupportsRemoteSessionActions) + { _sessionRemoteActionsMenuItem.Enabled = isConnected; - + } _sessionDisconnectServerMenuItem.Enabled = isConnected; _sessionFullScreenMenuItem.Enabled = isConnected; _sessionScreenCaptureMenuItem.Enabled = isConnected; } - private void SetTitle() { + private void SetTitle() + { Text = _server.GetQualifiedNameForUI(); } } diff --git a/RdcMan/ServerLabel.cs b/RdcMan/ServerLabel.cs index f0c973b..53025ef 100644 --- a/RdcMan/ServerLabel.cs +++ b/RdcMan/ServerLabel.cs @@ -3,9 +3,11 @@ using System.Drawing; using System.Windows.Forms; -namespace RdcMan { - internal class ServerLabel : Button { - private static readonly ContextMenuStrip _menu; +namespace RdcMan +{ + internal class ServerLabel : Button + { + private static ContextMenuStrip _menu; public new static int Height { get; private set; } @@ -15,17 +17,20 @@ internal class ServerLabel : Button { public int ThumbnailIndex { get; set; } - static ServerLabel() { + static ServerLabel() + { _menu = new ContextMenuStrip(); _menu.Opening += MenuPopup; - Button button = new Button { + Button button = new Button + { FlatStyle = FlatStyle.Flat, Font = new Font(ServerTree.Instance.Font, FontStyle.Bold) }; Height = button.Height; } - public ServerLabel(ServerBase node) { + public ServerLabel(ServerBase node) + { AssociatedNode = node; Server = node.ServerNode; base.Enabled = true; @@ -39,13 +44,17 @@ public ServerLabel(ServerBase node) { UpdateVisual(); } - public void CopyServerData() { + public void CopyServerData() + { Text = Server.DisplayName; } - protected override void OnMouseDown(MouseEventArgs e) { - if (e.Button == MouseButtons.Left) { - if (e.Clicks == 1) { + protected override void OnMouseDown(MouseEventArgs e) + { + if (e.Button == MouseButtons.Left) + { + if (e.Clicks == 1) + { Focus(); return; } @@ -55,7 +64,8 @@ protected override void OnMouseDown(MouseEventArgs e) { } } - private static void MenuPopup(object sender, CancelEventArgs e) { + private static void MenuPopup(object sender, CancelEventArgs e) + { _menu.Items.Clear(); ServerLabel serverLabel = (sender as ContextMenuStrip).SourceControl as ServerLabel; ServerBase server = serverLabel.AssociatedNode; @@ -64,32 +74,40 @@ private static void MenuPopup(object sender, CancelEventArgs e) { _menu.Items.Add(new DelegateMenuItem("չ(&E)", MenuNames.SessionExpand, delegate { ServerTree.Instance.SelectedNode = server; if (server.IsConnected) + { server.Focus(); + } })); MenuHelper.AddDockingMenuItems(_menu, server); _menu.Items.Add("-"); MenuHelper.AddMaintenanceMenuItems(_menu, server); - Program.PluginAction(delegate (IPlugin p) { + Program.PluginAction(delegate(IPlugin p) + { p.OnContextMenu(_menu, server); }); e.Cancel = false; } - protected override void OnGotFocus(EventArgs e) { + protected override void OnGotFocus(EventArgs e) + { UpdateVisual(); } - protected override void OnLostFocus(EventArgs e) { + protected override void OnLostFocus(EventArgs e) + { Program.TheForm.RecordLastFocusedServerLabel(this); UpdateVisual(); } - protected void UpdateVisual() { - if (Focused) { + protected void UpdateVisual() + { + if (Focused) + { ForeColor = SystemColors.ActiveCaptionText; BackColor = SystemColors.ActiveCaption; } - else { + else + { ForeColor = SystemColors.InactiveCaptionText; BackColor = SystemColors.InactiveCaption; } diff --git a/RdcMan/ServerMenuItem.cs b/RdcMan/ServerMenuItem.cs index 8997307..800af5d 100644 --- a/RdcMan/ServerMenuItem.cs +++ b/RdcMan/ServerMenuItem.cs @@ -1,16 +1,23 @@ -namespace RdcMan { - internal class ServerMenuItem : RdcMenuItem { - public ServerMenuItem(RdcTreeNode node) { +namespace RdcMan +{ + internal class ServerMenuItem : RdcMenuItem + { + public ServerMenuItem(RdcTreeNode node) + { base.Tag = node; Text = node.Text; } - public override void Update() { + public override void Update() + { if (base.DropDownItems.Count == 0) + { base.Checked = ServerTree.Instance.SelectedNode == base.Tag; + } } - protected override void OnClick() { + protected override void OnClick() + { ServerTree.Instance.SelectedNode = (RdcTreeNode)base.Tag; } } diff --git a/RdcMan/ServerPropertiesDialog.cs b/RdcMan/ServerPropertiesDialog.cs index aebc1a3..90ca1fa 100644 --- a/RdcMan/ServerPropertiesDialog.cs +++ b/RdcMan/ServerPropertiesDialog.cs @@ -1,53 +1,65 @@ using System.Windows.Forms; -namespace RdcMan { - internal class ServerPropertiesDialog : NodePropertiesDialog { +namespace RdcMan +{ + internal class ServerPropertiesDialog : NodePropertiesDialog + { private ServerPropertiesDialog(Server server, string dialogTitle, string acceptButtonText, Form parentForm) - : base(server, dialogTitle, acceptButtonText, parentForm) { } + : base(server, dialogTitle, acceptButtonText, parentForm) + { + } - private void CreateServerPropertiesPage(RdcTreeNode settings) { + private void CreateServerPropertiesPage(RdcTreeNode settings) + { ServerPropertiesTabPage page = (ServerPropertiesTabPage)(base.PropertiesPage = settings.Properties.CreateTabPage(this) as ServerPropertiesTabPage); AddTabPage(page); base.PropertiesPage.ParentGroupChanged += base.PopulateCredentialsProfiles; } - private void CreateImportServersPage(RdcTreeNode settings) { + private void CreateImportServersPage(RdcTreeNode settings) + { ImportServersPropertiesPage page = (ImportServersPropertiesPage)(base.PropertiesPage = new ImportServersPropertiesPage(this)); AddTabPage(page); base.PropertiesPage.ParentGroupChanged += base.PopulateCredentialsProfiles; } - public static ServerPropertiesDialog NewAddDialog(GroupBase parent) { + public static ServerPropertiesDialog NewAddDialog(GroupBase parent) + { Server server = Server.CreateForAddDialog(); ServerPropertiesDialog serverPropertiesDialog = new ServerPropertiesDialog(server, "ӷ", "", null); serverPropertiesDialog.CreateServerPropertiesPage(server); serverPropertiesDialog.CreateControls(server); - if (!serverPropertiesDialog.PropertiesPage.PopulateParentDropDown(null, parent)) { + if (!serverPropertiesDialog.PropertiesPage.PopulateParentDropDown(null, parent)) + { serverPropertiesDialog.Dispose(); return null; } return serverPropertiesDialog; } - public static ServerPropertiesDialog NewImportDialog(GroupBase parent) { + public static ServerPropertiesDialog NewImportDialog(GroupBase parent) + { Server server = Server.CreateForAddDialog(); ServerPropertiesDialog serverPropertiesDialog = new ServerPropertiesDialog(server, "", "", null); serverPropertiesDialog.CreateImportServersPage(server); serverPropertiesDialog.CreateControls(server); - if (!serverPropertiesDialog.PropertiesPage.PopulateParentDropDown(null, parent)) { + if (!serverPropertiesDialog.PropertiesPage.PopulateParentDropDown(null, parent)) + { serverPropertiesDialog.Dispose(); return null; } return serverPropertiesDialog; } - public static ServerPropertiesDialog NewPropertiesDialog(Server server, Form parentForm) { + public static ServerPropertiesDialog NewPropertiesDialog(Server server, Form parentForm) + { ServerPropertiesDialog serverPropertiesDialog = new ServerPropertiesDialog(server, server.DisplayName + " ", "ȷ", parentForm); serverPropertiesDialog.CreateServerPropertiesPage(server); serverPropertiesDialog.CreateControls(server); if (server.FileGroup == null) + { serverPropertiesDialog.PropertiesPage.SetParentDropDown(server.Parent as GroupBase); - + } serverPropertiesDialog.PropertiesPage.PopulateParentDropDown(null, server.Parent as GroupBase); return serverPropertiesDialog; } diff --git a/RdcMan/ServerPropertiesTabPage.cs b/RdcMan/ServerPropertiesTabPage.cs index 326b604..b461a4a 100644 --- a/RdcMan/ServerPropertiesTabPage.cs +++ b/RdcMan/ServerPropertiesTabPage.cs @@ -3,72 +3,87 @@ using System.Drawing; using System.Windows.Forms; -namespace RdcMan { - internal class ServerPropertiesTabPage : NodePropertiesPage { - private readonly RdcTextBox _serverNameTextBox; +namespace RdcMan +{ + internal class ServerPropertiesTabPage : NodePropertiesPage + { + private RdcTextBox _serverNameTextBox; - private readonly RdcCheckBox _vmConsoleConnectCheckBox; + private RdcCheckBox _vmConsoleConnectCheckBox; - private readonly Label _vmIdLabel; + private Label _vmIdLabel; - private readonly RdcTextBox _vmIdTextBox; + private RdcTextBox _vmIdTextBox; - private readonly RdcTextBox _displayNameTextBox; + private RdcTextBox _displayNameTextBox; private bool _displayNameUserCreated; public List ExpandedServerNames { get; private set; } public ServerPropertiesTabPage(TabbedSettingsDialog dialog, ServerSettings settings) - : base(dialog, settings, "") { - int num = 0; + : base(dialog, settings, "") + { + int tabIndex = 0; int rowIndex = 0; - _displayNameTextBox = FormTools.AddLabeledTextBox(this, "ʾ(&D)", base.Settings.DisplayName, ref rowIndex, ref num); + _displayNameTextBox = FormTools.AddLabeledTextBox(this, "ʾ(&D)", base.Settings.DisplayName, ref rowIndex, ref tabIndex); _displayNameTextBox.Enabled = true; _displayNameTextBox.TextChanged += DisplayNameChanged; _displayNameTextBox.Validate = ValidateDisplayName; - _serverNameTextBox = FormTools.AddLabeledTextBox(this, "ַ(&S)", base.Settings.ServerName, ref rowIndex, ref num); + _serverNameTextBox = FormTools.AddLabeledTextBox(this, "ַ(&S)", base.Settings.ServerName, ref rowIndex, ref tabIndex); _serverNameTextBox.Enabled = true; _serverNameTextBox.TextChanged += ServerNameChanged; _serverNameTextBox.Validate = ValidateServerName; - _vmConsoleConnectCheckBox = FormTools.NewCheckBox("&VM console connect", 0, rowIndex, num++, 140); + // (Windows/Linux) + FormTools.AddLabeledValueDropDown(this, "(&T)", base.Settings.ServerType, ref rowIndex, ref tabIndex, (string v)=>v.ToString(), new string[2] { + "Windows", + "Linux" + }); + + _vmConsoleConnectCheckBox = FormTools.NewCheckBox("&VM console connect", 0, rowIndex, tabIndex++, 140); _vmConsoleConnectCheckBox.CheckedChanged += VMConsoleConnectCheckBox_CheckedChanged; _vmIdLabel = new Label { Location = FormTools.NewLocation(1, rowIndex++), Size = new Size(30, FormTools.ControlHeight), Text = "&ID", - TextAlign = ContentAlignment.MiddleLeft + TextAlign = ContentAlignment.MiddleLeft, + Visible = false }; _vmIdTextBox = new RdcTextBox { Location = new Point(_vmIdLabel.Right, _vmIdLabel.Top), Setting = base.Settings.VirtualMachineId, Size = new Size(FormTools.TextBoxWidth - _vmIdLabel.Width, FormTools.ControlHeight), - TabIndex = num++ + TabIndex = tabIndex++, + Visible = false }; _displayNameUserCreated = !base.Settings.ServerName.Value.Equals(base.Settings.DisplayName.Value); - AddParentCombo(ref rowIndex, ref num); - AddComment(ref rowIndex, ref num).Setting = base.Settings.Comment; + AddParentCombo(ref rowIndex, ref tabIndex); + AddComment(ref rowIndex, ref tabIndex).Setting = base.Settings.Comment; _vmIdTextBox.Enabled = false; - base.Controls.Add(_vmConsoleConnectCheckBox, _vmIdLabel, _vmIdTextBox); + base.Controls.Add(_vmConsoleConnectCheckBox, _vmIdLabel, _vmIdTextBox); base.FocusControl = _displayNameTextBox; } - protected override bool CanBeParent(GroupBase group) { + protected override bool CanBeParent(GroupBase group) + { return group.CanAddServers(); } - protected override void UpdateControls() { + protected override void UpdateControls() + { base.UpdateControls(); _vmIdTextBox.Enabled = false; _vmConsoleConnectCheckBox.Checked = base.Settings.ConnectionType.Value == ConnectionType.VirtualMachineConsoleConnect; } - protected override void UpdateSettings() { + protected override void UpdateSettings() + { base.UpdateSettings(); base.Settings.ConnectionType.Value = (_vmConsoleConnectCheckBox.Checked ? ConnectionType.VirtualMachineConsoleConnect : ConnectionType.Normal); } - private string ValidateServerName() { + private string ValidateServerName() + { _serverNameTextBox.Text = _serverNameTextBox.Text.Trim(); string text = _serverNameTextBox.Text; if (text.Length == 0) @@ -77,28 +92,33 @@ private string ValidateServerName() { return "впո"; if (text.IndexOf('/') != -1 || text.IndexOf('\\') != -1) return "вʹб"; - try { + try + { List list = new List(StringUtilities.ExpandPattern(text)); if (list.Count > 1 && list.Count > 20 && FormTools.YesNoDialog("չΪ " + list.Count + "ȷ") == DialogResult.No) return "չ"; ExpandedServerNames = list; } - catch (ArgumentException ex) { + catch (ArgumentException ex) + { return ex.Message; } return null; } - private void ServerNameChanged(object sender, EventArgs e) { - if (!_displayNameUserCreated) { + private void ServerNameChanged(object sender, EventArgs e) + { + if (!_displayNameUserCreated) + { Server.SplitName(_serverNameTextBox.Text, out var serverName, out var _); _displayNameTextBox.Text = serverName; _displayNameUserCreated = false; } } - private string ValidateDisplayName() { + private string ValidateDisplayName() + { _displayNameTextBox.Text = _displayNameTextBox.Text.Trim(); string text = _displayNameTextBox.Text; if (text.Length == 0) @@ -107,14 +127,16 @@ private string ValidateDisplayName() { return null; } - private void DisplayNameChanged(object sender, EventArgs e) { + private void DisplayNameChanged(object sender, EventArgs e) + { _displayNameUserCreated = true; } - private void VMConsoleConnectCheckBox_CheckedChanged(object sender, EventArgs e) { + private void VMConsoleConnectCheckBox_CheckedChanged(object sender, EventArgs e) + { bool @checked = _vmConsoleConnectCheckBox.Checked; - //_vmIdLabel.Visible = @checked; - //_vmIdTextBox.Visible = @checked; + _vmIdLabel.Visible = @checked; + _vmIdTextBox.Visible = @checked; _vmIdTextBox.Enabled = @checked; EnableTabsEventArgs enableTabsEventArgs = new EnableTabsEventArgs { Enabled = !@checked, diff --git a/RdcMan/ServerProperty.cs b/RdcMan/ServerProperty.cs index b74bb22..5f569cb 100644 --- a/RdcMan/ServerProperty.cs +++ b/RdcMan/ServerProperty.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public enum ServerProperty { +namespace RdcMan +{ + public enum ServerProperty + { DisplayName, ServerName, Parent, diff --git a/RdcMan/ServerRef.cs b/RdcMan/ServerRef.cs index 9f3cf2c..6eef565 100644 --- a/RdcMan/ServerRef.cs +++ b/RdcMan/ServerRef.cs @@ -4,9 +4,11 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { - public abstract class ServerRef : ServerBase { - private readonly Server _server; +namespace RdcMan +{ + public abstract class ServerRef : ServerBase + { + private Server _server; public override Server ServerNode => _server; @@ -26,143 +28,181 @@ public abstract class ServerRef : ServerBase { public override string RemoveTypeDescription => ""; - public override DisplayStates DisplayState { - get { + public override DisplayStates DisplayState + { + get + { return _server.DisplayState; } - set { + set + { _server.DisplayState = value; } } - public override Size Size { - get { + public override Size Size + { + get + { return _server.Size; } - set { + set + { _server.Size = value; } } - public override Point Location { - get { + public override Point Location + { + get + { return _server.Location; } - set { + set + { _server.Location = value; } } - protected ServerRef(Server server) { + protected ServerRef(Server server) + { _server = server; _server.AddServerRef(this); base.Text = server.Text; ChangeImageIndex(ImageConstants.DisconnectedServer); } - protected override void InitSettings() { } + protected override void InitSettings() + { + } - public override string ToString() { + public override string ToString() + { return $"{GetType().Name}: {base.Text}"; } - internal override void Show() { + internal override void Show() + { _server.Show(); } - internal override void Hide() { + internal override void Hide() + { _server.Hide(); } - public override void Connect() { + public override void Connect() + { _server.Connect(); } - public override void ConnectAs(LogonCredentials logonSettings, ConnectionSettings connectionsettings) { + public override void ConnectAs(LogonCredentials logonSettings, ConnectionSettings connectionsettings) + { _server.ConnectAs(logonSettings, connectionsettings); } - public override void Reconnect() { + public override void Reconnect() + { _server.Reconnect(); } - public override void Disconnect() { + public override void Disconnect() + { _server.Disconnect(); } - public override void LogOff() { + public override void LogOff() + { _server.LogOff(); } - public override void DoPropertiesDialog(Form parentForm, string activeTabName) { + public override void DoPropertiesDialog(Form parentForm, string activeTabName) + { _server.DoPropertiesDialog(parentForm, activeTabName); } - public override bool CanRemove(bool popUI) { + public override bool CanRemove(bool popUI) + { return false; } - public override bool CanDropOnTarget(RdcTreeNode targetNode) { + public override bool CanDropOnTarget(RdcTreeNode targetNode) + { GroupBase groupBase = (targetNode as GroupBase) ?? (targetNode.Parent as GroupBase); - switch (groupBase.DropBehavior()) { - case DragDropEffects.Copy: - return groupBase.CanDropServers(); - case DragDropEffects.Link: - if (groupBase.CanDropServers()) - return AllowEdit(popUI: false); - return false; - default: - return false; + switch (groupBase.DropBehavior()) + { + case DragDropEffects.Copy: + return groupBase.CanDropServers(); + case DragDropEffects.Link: + if (groupBase.CanDropServers()) + { + return AllowEdit(popUI: false); + } + return false; + default: + return false; } } - public override void CollectNodesToInvalidate(bool recurseChildren, HashSet set) { + public override void CollectNodesToInvalidate(bool recurseChildren, HashSet set) + { set.Add(this); set.Add(base.Parent as RdcTreeNode); } - internal override void WriteXml(XmlTextWriter tw) { + internal override void WriteXml(XmlTextWriter tw) + { throw new NotImplementedException(); } - public sealed override void ChangeImageIndex(ImageConstants index) { + public sealed override void ChangeImageIndex(ImageConstants index) + { base.ImageIndex = _server.ImageIndex; base.SelectedImageIndex = _server.SelectedImageIndex; } - internal override void Focus() { + internal override void Focus() + { _server.Focus(); } - internal override void FocusConnectedClient() { + internal override void FocusConnectedClient() + { _server.FocusConnectedClient(); } - internal virtual void OnRemoveServer() { + internal virtual void OnRemoveServer() + { ServerTree.Instance.RemoveNode(this); } - public override void OnRemoving() { + public override void OnRemoving() + { _server.RemoveServerRef(this); } - internal override void GoFullScreen() { + internal override void GoFullScreen() + { _server.GoFullScreen(); } - internal override void LeaveFullScreen() { + internal override void LeaveFullScreen() + { _server.LeaveFullScreen(); } - internal override void Undock() { + internal override void Undock() + { _server.Undock(); } - internal override void Dock() { + internal override void Dock() + { _server.Dock(); } - internal override void ScreenCapture() { + internal override void ScreenCapture() + { _server.ScreenCapture(); } } diff --git a/RdcMan/ServerSettings.cs b/RdcMan/ServerSettings.cs index 86325e4..bd3c776 100644 --- a/RdcMan/ServerSettings.cs +++ b/RdcMan/ServerSettings.cs @@ -2,8 +2,10 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { - public class ServerSettings : CommonNodeSettings { +namespace RdcMan +{ + public class ServerSettings : CommonNodeSettings + { //internal const string TabName = "Server Settings"; private static Dictionary _settingProperties; @@ -18,28 +20,38 @@ public class ServerSettings : CommonNodeSettings { [Setting("vmId")] public StringSetting VirtualMachineId { get; private set; } + /* (Windows/Linux)*/ + [Setting("serverType", DefaultValue = "Windows")] + public StringSetting ServerType { get; private set; } protected override Dictionary SettingProperties => _settingProperties; - static ServerSettings() { + static ServerSettings() + { typeof(ServerSettings).GetSettingProperties(out _settingProperties); } public ServerSettings() : base("") { } - public override TabPage CreateTabPage(TabbedSettingsDialog dialog) { + public override TabPage CreateTabPage(TabbedSettingsDialog dialog) + { return new ServerPropertiesTabPage(dialog, this); } - protected override void WriteSettings(XmlTextWriter tw, RdcTreeNode node) { + protected override void WriteSettings(XmlTextWriter tw, RdcTreeNode node) + { HashSet hashSet = new HashSet(); if (ConnectionType.Value == RdcMan.ConnectionType.Normal) { hashSet.Add(ConnectionType); hashSet.Add(VirtualMachineId); } + if (ServerName.Value.Equals(DisplayName.Value)) hashSet.Add(DisplayName); + //ӷ + if (string.IsNullOrEmpty(ServerType.Value)) + hashSet.Add(ServerType); if (string.IsNullOrEmpty(base.Comment.Value)) hashSet.Add(base.Comment); @@ -47,7 +59,8 @@ protected override void WriteSettings(XmlTextWriter tw, RdcTreeNode node) { base.WriteSettings(tw, node, hashSet); } - protected override void Copy(RdcTreeNode node) { + protected override void Copy(RdcTreeNode node) + { if (node is ServerBase serverBase) Copy(serverBase.Properties); } diff --git a/RdcMan/ServerTree.cs b/RdcMan/ServerTree.cs index 94ee647..775dac8 100644 --- a/RdcMan/ServerTree.cs +++ b/RdcMan/ServerTree.cs @@ -7,38 +7,51 @@ using System.Threading; using System.Windows.Forms; -namespace RdcMan { - internal class ServerTree : TreeView, IServerTree { - private class RootNodeGroup : GroupBase { - public RootNodeGroup() { +namespace RdcMan +{ + internal class ServerTree : TreeView, IServerTree + { + private class RootNodeGroup : GroupBase + { + public RootNodeGroup() + { base.Text = "[root]"; } - public override void OnRemoving() { + public override void OnRemoving() + { throw new NotImplementedException(); } - public override void DoPropertiesDialog(Form parentForm, string activeTabName) { + public override void DoPropertiesDialog(Form parentForm, string activeTabName) + { throw new NotImplementedException(); } - protected override void InitSettings() { } + protected override void InitSettings() + { + } } - private class InvalidateComparer : IComparer { - public int Compare(RdcTreeNode x, RdcTreeNode y) { + private class InvalidateComparer : IComparer + { + public int Compare(RdcTreeNode x, RdcTreeNode y) + { int ordinal = GetOrdinal(x); int ordinal2 = GetOrdinal(y); return ordinal - ordinal2; } - private int GetOrdinal(RdcTreeNode node) { + private int GetOrdinal(RdcTreeNode node) + { if (node is Server) + { return 9999; - + } if (node is ServerRef) + { return 8888; - + } return node.GetPathLength(); } } @@ -85,13 +98,15 @@ private int GetOrdinal(RdcTreeNode node) { internal event Action GroupChanged; - static ServerTree() { + static ServerTree() + { NotFocusedForeColor = Color.FromKnownColor(KnownColor.ControlDark); NotFocusedBackColor = Color.White; FocusedForeColor = Color.Black; FocusedBackColor = Color.White; ImageConstantLookup = new ImageConstants[2, 9]; - foreach (ImageConstants item in Helpers.EnumValues()) { + foreach (ImageConstants item in Helpers.EnumValues()) + { ImageConstantLookup[0, (int)item] = item; ImageConstantLookup[1, (int)item] = item; } @@ -102,84 +117,108 @@ static ServerTree() { Instance = new ServerTree(); } - private ServerTree() { + private ServerTree() + { base.BorderStyle = BorderStyle.None; AllowDrop = true; base.Scrollable = true; base.HideSelection = false; - _delayedFocusTimer = new System.Threading.Timer(delegate { + _delayedFocusTimer = new System.Threading.Timer(delegate + { CheckDelayedFocusServer(); }, null, -1, -1); } - internal FileGroup GetSelectedFile() { + internal FileGroup GetSelectedFile() + { FileGroup result = null; TreeNode treeNode = base.SelectedNode; if (treeNode != null) + { result = (treeNode as RdcTreeNode).FileGroup; - + } return result; } - internal void Operation(OperationBehavior behavior, Action operation) { + internal void Operation(OperationBehavior behavior, Action operation) + { RdcTreeNode rdcTreeNode = base.SelectedNode as RdcTreeNode; - try { + try + { if (behavior.HasFlag(OperationBehavior.SuspendUpdate)) + { BeginUpdate(); - + } if (behavior.HasFlag(OperationBehavior.SuspendSort)) + { SuspendSort(); - + } if (behavior.HasFlag(OperationBehavior.SuspendSelect)) + { SuspendSelect(); - + } if (behavior.HasFlag(OperationBehavior.SuspendGroupChanged)) + { SuspendGroupChanged(); - + } if (behavior.HasFlag(OperationBehavior.RestoreSelected)) + { base.SelectedNode = null; - + } operation(); } - finally { - if (behavior.HasFlag(OperationBehavior.RestoreSelected)) { + finally + { + if (behavior.HasFlag(OperationBehavior.RestoreSelected)) + { base.SelectedNode = rdcTreeNode; Program.TheForm.SetTitle(); } if (behavior.HasFlag(OperationBehavior.SuspendGroupChanged)) + { ResumeGroupChanged(); - + } if (behavior.HasFlag(OperationBehavior.SuspendSelect)) + { ResumeSelect(); - + } if (behavior.HasFlag(OperationBehavior.SuspendSort)) + { ResumeSort(); - + } if (behavior.HasFlag(OperationBehavior.SuspendUpdate)) + { EndUpdate(); + } } } - internal void UpdateColors() { - if (Program.Preferences.DimNodesWhenInactive) { - if (Focused) { + internal void UpdateColors() + { + if (Program.Preferences.DimNodesWhenInactive) + { + if (Focused) + { ForeColor = FocusedForeColor; BackColor = FocusedBackColor; } - else { + else + { ForeColor = NotFocusedForeColor; BackColor = NotFocusedBackColor; } } - else { + else + { ForeColor = FocusedForeColor; BackColor = FocusedBackColor; } } - internal void Init(Assembly myAssembly) { + internal void Init(Assembly myAssembly) + { base.ImageList = new ImageList(); - base.ImageList.ColorDepth = ColorDepth.Depth8Bit; + base.ImageList.ColorDepth = ColorDepth.Depth32Bit; base.ImageList.ImageSize = new Size(16, 16); base.ImageList.Images.Add(new Icon(myAssembly.GetManifestResourceStream("Resources.disconnected.ico"))); base.ImageList.Images.Add(new Icon(myAssembly.GetManifestResourceStream("Resources.connecting.ico"))); @@ -188,64 +227,85 @@ internal void Init(Assembly myAssembly) { base.ImageList.Images.Add(new Icon(myAssembly.GetManifestResourceStream("Resources.connectedselected.ico"))); base.ImageList.Images.Add(new Icon(myAssembly.GetManifestResourceStream("Resources.group.ico"))); base.ImageList.Images.Add(new Icon(myAssembly.GetManifestResourceStream("Resources.smartgroup.ico"))); - base.ImageList.Images.Add(new Icon(myAssembly.GetManifestResourceStream("Resources.app.ico"))); + base.ImageList.Images.Add(new Icon(myAssembly.GetManifestResourceStream("Resources.default.ico"))); ContextMenuStrip contextMenuStrip = new ContextMenuStrip(); contextMenuStrip.Opening += OnContextMenu; ContextMenuStrip = contextMenuStrip; } - public void AddNode(RdcTreeNode node, GroupBase parent) { + public void AddNode(RdcTreeNode node, GroupBase parent) + { if (node == null) + { throw new ArgumentNullException("node"); - + } if (!(node is ServerBase) && !(node is GroupBase)) + { throw new ArgumentOutOfRangeException("node", "ڵ ServerBase GroupBase "); - + } if (parent == null) + { throw new ArgumentNullException("parent"); - + } if (parent == RootNode) + { base.Nodes.Add(node); - else { + } + else + { parent.Nodes.Add(node); this.SortGroup(parent); } OnGroupChanged(parent, ChangeType.TreeChanged); } - public void RemoveNode(RdcTreeNode node) { + public void RemoveNode(RdcTreeNode node) + { if (node == null) + { throw new ArgumentNullException("node"); - + } TreeNode treeNode = base.SelectedNode; TreeNodeCollection parentNodes = ((node.Parent != null) ? node.Parent.Nodes : base.Nodes); - if (treeNode != null) { + if (treeNode != null) + { bool inSelectedPath = false; - (treeNode as RdcTreeNode).VisitNodeAndParents(delegate (RdcTreeNode n) { + (treeNode as RdcTreeNode).VisitNodeAndParents(delegate(RdcTreeNode n) + { if (n == node) + { inSelectedPath = true; + } }); - if (inSelectedPath) { + if (inSelectedPath) + { (treeNode as RdcTreeNode).Hide(); node.Hide(); treeNode = ((node.Index > 0) ? parentNodes[node.Index - 1] : ((node.Index >= parentNodes.Count - 1) ? node.Parent : parentNodes[node.Index + 1])); base.SelectedNode = null; } } - Operation(OperationBehavior.RestoreSelected, delegate { + Operation(OperationBehavior.RestoreSelected, delegate + { GroupBase groupBase = node.Parent as GroupBase; node.OnRemoving(); parentNodes.Remove(node); if (groupBase != null) + { OnGroupChanged(groupBase, ChangeType.TreeChanged); + } }); base.SelectedNode = treeNode; } - private void CheckDelayedFocusServer() { - lock (_delayedFocusSyncObject) { - if (_delayedFocusServer != null) { - Program.TheForm.Invoke((MethodInvoker)delegate { + private void CheckDelayedFocusServer() + { + lock (_delayedFocusSyncObject) + { + if (_delayedFocusServer != null) + { + Program.TheForm.Invoke((MethodInvoker)delegate + { _delayedFocusServer.FocusConnectedClient(); }); } @@ -253,90 +313,120 @@ private void CheckDelayedFocusServer() { } } - private void SetDelayedFocusServer(ServerBase server) { - lock (_delayedFocusSyncObject) { + private void SetDelayedFocusServer(ServerBase server) + { + lock (_delayedFocusSyncObject) + { _delayedFocusServer = server; _delayedFocusTimer.Change(100, -1); } } - protected override void OnGotFocus(EventArgs e) { + protected override void OnGotFocus(EventArgs e) + { base.OnGotFocus(e); UpdateColors(); } - protected override void OnLostFocus(EventArgs e) { + protected override void OnLostFocus(EventArgs e) + { base.OnLostFocus(e); UpdateColors(); } - protected override void OnMouseDown(MouseEventArgs e) { + protected override void OnMouseDown(MouseEventArgs e) + { if (e.Button == MouseButtons.Right) + { _contextViaMouse = true; + } else + { base.OnMouseDown(e); + } } - protected override void OnBeforeSelect(TreeViewCancelEventArgs e) { + protected override void OnBeforeSelect(TreeViewCancelEventArgs e) + { base.OnBeforeSelect(e); - if (_noSelectCounter <= 0 && base.SelectedNode != null) { + if (_noSelectCounter <= 0 && base.SelectedNode != null) + { RdcTreeNode rdcTreeNode = base.SelectedNode as RdcTreeNode; if (!(rdcTreeNode is ServerBase serverBase) || serverBase.IsClientUndocked || !serverBase.IsClientFullScreen) + { rdcTreeNode.Hide(); + } } } - protected override void OnAfterSelect(TreeViewEventArgs e) { + protected override void OnAfterSelect(TreeViewEventArgs e) + { if (_noSelectCounter > 0) + { return; - - if (base.SelectedNode is RdcTreeNode rdcTreeNode) { - if (rdcTreeNode is ServerBase serverBase) { + } + if (base.SelectedNode is RdcTreeNode rdcTreeNode) + { + if (rdcTreeNode is ServerBase serverBase) + { if (serverBase.IsClientUndocked || !serverBase.IsClientFullScreen) + { serverBase.ServerNode.SetNormalView(); + } if (!Helpers.IsControlKeyPressed && Program.Preferences.FocusOnClick && e.Action == TreeViewAction.ByMouse && serverBase.IsConnected) + { SetDelayedFocusServer(serverBase); + } } if (!rdcTreeNode.IsVisible) + { rdcTreeNode.EnsureVisible(); - + } rdcTreeNode.Show(); } Program.TheForm.SetTitle(); base.OnAfterSelect(e); } - private void OnContextMenu(object sender, CancelEventArgs e) { + private void OnContextMenu(object sender, CancelEventArgs e) + { RdcTreeNode contextNode = base.SelectedNode as RdcTreeNode; - if (_contextViaMouse) { + if (_contextViaMouse) + { Point point = PointToClient(Control.MousePosition); contextNode = GetNodeAt(point.X, point.Y) as RdcTreeNode; _contextViaMouse = false; this.SelectedNode = contextNode; //Ҽѡ } PopulateNodeContextMenu(ContextMenuStrip, contextNode); - Program.PluginAction(delegate (IPlugin p) { + Program.PluginAction(delegate(IPlugin p) + { p.OnContextMenu(ContextMenuStrip, contextNode); }); e.Cancel = false; } - private void PopulateNodeContextMenu(ContextMenuStrip menu, RdcTreeNode node) { + private void PopulateNodeContextMenu(ContextMenuStrip menu, RdcTreeNode node) + { menu.Items.Clear(); - if (node == null) { - if (AnyOpenedEditableFiles()) { + if (node == null) + { + if (AnyOpenedEditableFiles()) + { menu.Items.Add(new DelegateMenuItem("ӷ(&A)...", MenuNames.EditAddServer, AddNodeDialogHelper.AddServersDialog)); menu.Items.Add(new DelegateMenuItem("(&I)...", MenuNames.EditImportServers, AddNodeDialogHelper.ImportServersDialog)); menu.Items.Add("-"); menu.Items.Add(new DelegateMenuItem("(&G)...", MenuNames.EditAddGroup, AddNodeDialogHelper.AddGroupDialog)); } - else { + else + { ToolStripMenuItem toolStripMenuItem = new ToolStripMenuItem("򿪻򴴽ļ"); toolStripMenuItem.Enabled = false; menu.Items.Add(toolStripMenuItem); } } - else if (node is GroupBase groupBase) { + else if (node is GroupBase groupBase) + { groupBase.AnyOrAllConnected(out var anyConnected, out var allConnected); ToolStripMenuItem toolStripMenuItem = new DelegateMenuItem("(&C)", MenuNames.SessionConnect, groupBase.Connect) { Enabled = !allConnected @@ -414,40 +504,50 @@ private void PopulateNodeContextMenu(ContextMenuStrip menu, RdcTreeNode node) { } } - public bool AnyOpenedEditableFiles() { + public bool AnyOpenedEditableFiles() + { return base.Nodes.OfType().Any((FileGroup file) => file.AllowEdit(popUI: false)); } - private TreeNode FindNodeInList(TreeNodeCollection nodes, string name) { + private TreeNode FindNodeInList(TreeNodeCollection nodes, string name) + { return (from TreeNode node in nodes - where node.Text == name - select node).FirstOrDefault(); + where node.Text == name + select node).FirstOrDefault(); } - public TreeNode FindNodeByName(string name) { + public TreeNode FindNodeByName(string name) + { if (name == RootNode.Text) + { return RootNode; - + } string[] array = name.Split(new string[1] { base.PathSeparator }, StringSplitOptions.None); TreeNodeCollection treeNodeCollection = base.Nodes; TreeNode treeNode = null; string[] array2 = array; - foreach (string name2 in array2) { + foreach (string name2 in array2) + { treeNode = FindNodeInList(treeNodeCollection, name2); if (treeNode == null) + { break; - + } treeNodeCollection = treeNode.Nodes; } return treeNode; } - public void ConfirmRemove(RdcTreeNode node, bool askUser) { + public void ConfirmRemove(RdcTreeNode node, bool askUser) + { if (node.ConfirmRemove(askUser)) + { RemoveNode(node); + } } - private void DoRemoveChildren(RdcTreeNode node) { + private void DoRemoveChildren(RdcTreeNode node) + { GroupBase groupBase = node as GroupBase; if (groupBase.Nodes.Count > 0) { DialogResult dialogResult = FormTools.YesNoDialog("ɾ " + groupBase.Text + " "); @@ -457,16 +557,19 @@ private void DoRemoveChildren(RdcTreeNode node) { groupBase.RemoveChildren(); } - protected override void OnItemDrag(ItemDragEventArgs e) { + protected override void OnItemDrag(ItemDragEventArgs e) + { base.OnItemDrag(e); RdcTreeNode rdcTreeNode = (_draggedNode = e.Item as RdcTreeNode); _preDragSelectedNode = base.SelectedNode; DoDragDrop(_draggedNode, DragDropEffects.Move); } - protected override void OnQueryContinueDrag(QueryContinueDragEventArgs e) { + protected override void OnQueryContinueDrag(QueryContinueDragEventArgs e) + { base.OnQueryContinueDrag(e); - if ((e.KeyState & 3) == 0) { + if ((e.KeyState & 3) == 0) + { SuspendSelect(); base.SelectedNode = _preDragSelectedNode; _preDragSelectedNode = null; @@ -474,16 +577,19 @@ protected override void OnQueryContinueDrag(QueryContinueDragEventArgs e) { } } - protected override void OnDragOver(DragEventArgs e) { + protected override void OnDragOver(DragEventArgs e) + { base.OnDragOver(e); Point pt = PointToClient(new Point(e.X, e.Y)); - if (GetNodeAt(pt) is RdcTreeNode targetNode && _draggedNode.CanDropOnTarget(targetNode)) { + if (GetNodeAt(pt) is RdcTreeNode targetNode && _draggedNode.CanDropOnTarget(targetNode)) + { SuspendSelect(); base.SelectedNode = targetNode; ResumeSelect(); e.Effect = e.AllowedEffect; } - else { + else + { SuspendSelect(); base.SelectedNode = _draggedNode; ResumeSelect(); @@ -491,71 +597,92 @@ protected override void OnDragOver(DragEventArgs e) { } } - protected override void OnDragDrop(DragEventArgs e) { + protected override void OnDragDrop(DragEventArgs e) + { base.OnDragDrop(e); Point pt = PointToClient(new Point(e.X, e.Y)); - if (GetNodeAt(pt) is RdcTreeNode rdcTreeNode) { + if (GetNodeAt(pt) is RdcTreeNode rdcTreeNode) + { GroupBase groupBase = (rdcTreeNode as GroupBase) ?? (rdcTreeNode.Parent as GroupBase); if (groupBase != _draggedNode && groupBase != _draggedNode.Parent) + { MoveNode(_draggedNode, groupBase); + } } } - protected override void OnNodeMouseDoubleClick(TreeNodeMouseClickEventArgs e) { + protected override void OnNodeMouseDoubleClick(TreeNodeMouseClickEventArgs e) + { base.OnNodeMouseDoubleClick(e); - if (e.Button == MouseButtons.Left && !Helpers.IsControlKeyPressed && base.SelectedNode is ServerBase serverBase) { + if (e.Button == MouseButtons.Left && !Helpers.IsControlKeyPressed && base.SelectedNode is ServerBase serverBase) + { serverBase.Connect(); SetDelayedFocusServer(serverBase); } } - public void MoveNode(RdcTreeNode node, GroupBase newParent) { + public void MoveNode(RdcTreeNode node, GroupBase newParent) + { if (newParent != null && newParent.HandleMove(node)) return; - - Operation(OperationBehavior.RestoreSelected, delegate { - if (node.Parent == null) { + Operation(OperationBehavior.RestoreSelected, delegate + { + if (node.Parent == null) + { base.Nodes.Remove(node); OnGroupChanged(RootNode, ChangeType.TreeChanged); } - else { + else + { if (node is ServerBase && (node as ServerBase).ServerNode is TemporaryServer temporaryServer) + { node = temporaryServer; - + } GroupBase groupBase = node.Parent as GroupBase; groupBase.Nodes.Remove(node); OnGroupChanged(groupBase, ChangeType.TreeChanged); } - if (newParent == null) { + if (newParent == null) + { base.Nodes.Add(node); OnGroupChanged(RootNode, ChangeType.TreeChanged); } - else { + else + { newParent.Nodes.Add(node); OnGroupChanged(newParent, ChangeType.TreeChanged); } OnNodeChanged(node, ChangeType.TreeChanged); if (!node.IsVisible) + { node.EnsureVisible(); + } }); } - public void OnGroupChanged(GroupBase group, ChangeType changeType) { + public void OnGroupChanged(GroupBase group, ChangeType changeType) + { if (_noGroupChanged > 0 || group == null) + { return; - + } Log.Write("OnGroupChanged({1}) {0}", group.Text, changeType); HashSet set = new HashSet(); - if (group == RootNode) { - if (changeType.HasFlag(ChangeType.PropertyChanged)) { - base.Nodes.VisitNodes(delegate (RdcTreeNode n) { + if (group == RootNode) + { + if (changeType.HasFlag(ChangeType.PropertyChanged)) + { + base.Nodes.VisitNodes(delegate(RdcTreeNode n) + { set.Add(n); }); } } - else { + else + { group.CollectNodesToInvalidate(recurseChildren: true, set); - group.VisitParents(delegate (RdcTreeNode parent) { + group.VisitParents(delegate(RdcTreeNode parent) + { parent.CollectNodesToInvalidate(recurseChildren: false, set); }); } @@ -563,56 +690,71 @@ public void OnGroupChanged(GroupBase group, ChangeType changeType) { this.GroupChanged?.Invoke(new GroupChangedEventArgs(group, changeType)); } - public void OnNodeChanged(RdcTreeNode node, ChangeType changeType) { + public void OnNodeChanged(RdcTreeNode node, ChangeType changeType) + { Log.Write("OnNodeChanged({1}) {0}", node.Text, changeType); if (this.SortNode(node) && node.Parent is GroupBase group) + { OnGroupChanged(group, ChangeType.InvalidateUI); - + } if (node is GroupBase group2) + { OnGroupChanged(group2, changeType); + } else + { OnServerChanged(node as ServerBase, changeType); - + } Program.TheForm.SetTitle(); } - private void OnServerChanged(ServerBase serverBase, ChangeType changeType) { + private void OnServerChanged(ServerBase serverBase, ChangeType changeType) + { HashSet set = new HashSet(); serverBase.CollectNodesToInvalidate(recurseChildren: false, set); InvalidateNodes(set); this.ServerChanged?.Invoke(new ServerChangedEventArgs(serverBase, changeType)); } - public void SuspendSelect() { + public void SuspendSelect() + { Interlocked.Increment(ref _noSelectCounter); } - public void ResumeSelect() { + public void ResumeSelect() + { Interlocked.Decrement(ref _noSelectCounter); } - public void SuspendSort() { + public void SuspendSort() + { Interlocked.Increment(ref _noSortCounter); } - public void ResumeSort() { + public void ResumeSort() + { Interlocked.Decrement(ref _noSortCounter); } - public void SuspendGroupChanged() { + public void SuspendGroupChanged() + { Interlocked.Increment(ref _noGroupChanged); } - public void ResumeGroupChanged() { + public void ResumeGroupChanged() + { Interlocked.Decrement(ref _noGroupChanged); } - public static ImageConstants TranslateImage(ImageConstants index, bool toSelected) { + public static ImageConstants TranslateImage(ImageConstants index, bool toSelected) + { return ImageConstantLookup[toSelected ? 1 : 0, (int)index]; } - private void InvalidateNodes(HashSet set) { - foreach (RdcTreeNode item in set.OrderByDescending((RdcTreeNode n) => n, new InvalidateComparer())) { + private void InvalidateNodes(HashSet set) + { + foreach (RdcTreeNode item in set.OrderByDescending((RdcTreeNode n) => n, new InvalidateComparer())) + { item.InvalidateNode(); } } diff --git a/RdcMan/ServerTreeLocationMenuItem.cs b/RdcMan/ServerTreeLocationMenuItem.cs index 5977072..bf1313e 100644 --- a/RdcMan/ServerTreeLocationMenuItem.cs +++ b/RdcMan/ServerTreeLocationMenuItem.cs @@ -1,18 +1,24 @@ using System.Windows.Forms; -namespace RdcMan { - internal class ServerTreeLocationMenuItem : EnumMenuItem { - protected override DockStyle Value { - get { +namespace RdcMan +{ + internal class ServerTreeLocationMenuItem : EnumMenuItem + { + protected override DockStyle Value + { + get + { return Program.TheForm.ServerTreeLocation; } - set { + set + { Program.TheForm.ServerTreeLocation = value; } } public ServerTreeLocationMenuItem(string text, DockStyle value) - : base(text, value) { + : base(text, value) + { } } } diff --git a/RdcMan/ServerTreeVisibilityMenuItem.cs b/RdcMan/ServerTreeVisibilityMenuItem.cs index 07753c2..747ca49 100644 --- a/RdcMan/ServerTreeVisibilityMenuItem.cs +++ b/RdcMan/ServerTreeVisibilityMenuItem.cs @@ -1,16 +1,22 @@ -namespace RdcMan { - internal class ServerTreeVisibilityMenuItem : EnumMenuItem { - protected override ControlVisibility Value { - get { +namespace RdcMan +{ + internal class ServerTreeVisibilityMenuItem : EnumMenuItem + { + protected override ControlVisibility Value + { + get + { return Program.TheForm.ServerTreeVisibility; } - set { + set + { Program.TheForm.ServerTreeVisibility = value; } } public ServerTreeVisibilityMenuItem(string text, ControlVisibility value) - : base(text, value) { + : base(text, value) + { } } } diff --git a/RdcMan/SessionListSortComparer.cs b/RdcMan/SessionListSortComparer.cs index df85d4b..40cb2c9 100644 --- a/RdcMan/SessionListSortComparer.cs +++ b/RdcMan/SessionListSortComparer.cs @@ -1,22 +1,29 @@ using System.Collections; using System.Windows.Forms; -namespace RdcMan { - public class SessionListSortComparer : IComparer { +namespace RdcMan +{ + public class SessionListSortComparer : IComparer + { private readonly int[] _sortOrder; - public SessionListSortComparer(int[] sortOrder) { + public SessionListSortComparer(int[] sortOrder) + { _sortOrder = sortOrder; } - public int Compare(object obj1, object obj2) { + public int Compare(object obj1, object obj2) + { ListViewItem listViewItem = obj1 as ListViewItem; ListViewItem listViewItem2 = obj2 as ListViewItem; int[] sortOrder = _sortOrder; - foreach (int index in sortOrder) { + foreach (int index in sortOrder) + { int num = string.Compare(listViewItem.SubItems[index].Text, listViewItem2.SubItems[index].Text); if (num != 0) + { return num; + } } return string.Compare(listViewItem.SubItems[0].Text, listViewItem2.SubItems[0].Text); } diff --git a/RdcMan/Setting.cs b/RdcMan/Setting.cs index 53bbb53..3ef10c3 100644 --- a/RdcMan/Setting.cs +++ b/RdcMan/Setting.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public abstract class Setting : BaseSetting { +namespace RdcMan +{ + public abstract class Setting : BaseSetting + { public new T Value { get => base.Value; set => base.Value = value; diff --git a/RdcMan/SettingAttribute.cs b/RdcMan/SettingAttribute.cs index d1b44b2..ce708d3 100644 --- a/RdcMan/SettingAttribute.cs +++ b/RdcMan/SettingAttribute.cs @@ -1,15 +1,18 @@ using System; -namespace RdcMan { +namespace RdcMan +{ [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)] - public class SettingAttribute : Attribute { + public class SettingAttribute : Attribute + { public string XmlName { get; set; } public object DefaultValue { get; set; } public bool IsObsolete { get; set; } - public SettingAttribute(string xmlName) { + public SettingAttribute(string xmlName) + { XmlName = xmlName; } } diff --git a/RdcMan/SettingExtensions.cs b/RdcMan/SettingExtensions.cs index 6ba7a24..e7db04b 100644 --- a/RdcMan/SettingExtensions.cs +++ b/RdcMan/SettingExtensions.cs @@ -2,16 +2,22 @@ using System.Collections.Generic; using System.Reflection; -namespace RdcMan { - public static class SettingExtensions { - public static void GetSettingProperties(this Type type, out Dictionary settingProperties) { +namespace RdcMan +{ + public static class SettingExtensions + { + public static void GetSettingProperties(this Type type, out Dictionary settingProperties) + { settingProperties = new Dictionary(StringComparer.OrdinalIgnoreCase); PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - foreach (PropertyInfo propertyInfo in properties) { + foreach (PropertyInfo propertyInfo in properties) + { object[] customAttributes = propertyInfo.GetCustomAttributes(typeof(SettingAttribute), inherit: false); - if (customAttributes.Length == 1) { + if (customAttributes.Length == 1) + { SettingAttribute settingAttribute = (SettingAttribute)customAttributes[0]; - settingProperties[settingAttribute.XmlName] = new SettingProperty { + settingProperties[settingAttribute.XmlName] = new SettingProperty + { Property = propertyInfo, Attribute = settingAttribute }; diff --git a/RdcMan/SettingProperty.cs b/RdcMan/SettingProperty.cs index 95181cb..125fa88 100644 --- a/RdcMan/SettingProperty.cs +++ b/RdcMan/SettingProperty.cs @@ -1,7 +1,9 @@ using System.Reflection; -namespace RdcMan { - public class SettingProperty { +namespace RdcMan +{ + public class SettingProperty + { public PropertyInfo Property; public SettingAttribute Attribute; diff --git a/RdcMan/SettingsGroup.cs b/RdcMan/SettingsGroup.cs index a0070ed..ba99d86 100644 --- a/RdcMan/SettingsGroup.cs +++ b/RdcMan/SettingsGroup.cs @@ -3,8 +3,10 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { - public abstract class SettingsGroup { +namespace RdcMan +{ + public abstract class SettingsGroup + { public string Name { get; private set; } public string XmlNodeName { get; private set; } @@ -13,11 +15,13 @@ public abstract class SettingsGroup { protected abstract Dictionary SettingProperties { get; } - internal SettingsGroup(string name, string xmlNodeName) { + internal SettingsGroup(string name, string xmlNodeName) + { XmlNodeName = xmlNodeName; Name = name; InheritSettingsType = new InheritSettingsType(); - foreach (SettingProperty value2 in SettingProperties.Values) { + foreach (SettingProperty value2 in SettingProperties.Values) + { ISetting value = (ISetting)Activator.CreateInstance(value2.Property.PropertyType, value2.Attribute.DefaultValue); value2.Property.SetValue(this, value, null); } @@ -25,21 +29,27 @@ internal SettingsGroup(string name, string xmlNodeName) { public abstract TabPage CreateTabPage(TabbedSettingsDialog dialog); - public override string ToString() { + public override string ToString() + { return Name; } - internal void ReadXml(XmlNode xmlNode, RdcTreeNode node, ICollection errors) { + internal void ReadXml(XmlNode xmlNode, RdcTreeNode node, ICollection errors) + { InheritanceMode result = InheritSettingsType.Mode; - if (result != InheritanceMode.Disabled) { - try { + if (result != InheritanceMode.Disabled) + { + try + { string value = xmlNode.Attributes["inherit"].Value; - if (!Enum.TryParse(value, out result)) { + if (!Enum.TryParse(value, out result)) + { errors.Add("{1} е̳ģʽ{0}".InvariantFormat(value, xmlNode.GetFullPath())); result = InheritanceMode.None; } } - catch { + catch + { errors.Add("{0} δָ̳ģʽ".InvariantFormat(xmlNode.GetFullPath())); result = InheritanceMode.None; } @@ -75,25 +85,32 @@ internal void ReadXml(XmlNode xmlNode, RdcTreeNode node, ICollection err } } - internal void WriteXml(XmlTextWriter tw, RdcTreeNode node) { - if (InheritSettingsType.Mode != 0) { + internal void WriteXml(XmlTextWriter tw, RdcTreeNode node) + { + if (InheritSettingsType.Mode != 0) + { tw.WriteStartElement(XmlNodeName); if (InheritSettingsType.Mode != InheritanceMode.Disabled) + { InheritSettingsType.WriteXml(tw); - + } WriteSettings(tw, node); tw.WriteEndElement(); } } - protected virtual void WriteSettings(XmlTextWriter tw, RdcTreeNode node) { + protected virtual void WriteSettings(XmlTextWriter tw, RdcTreeNode node) + { WriteSettings(tw, node, null); } - protected virtual void WriteSettings(XmlTextWriter tw, RdcTreeNode node, HashSet exclusionSet) { - foreach (SettingProperty value in SettingProperties.Values) { + protected virtual void WriteSettings(XmlTextWriter tw, RdcTreeNode node, HashSet exclusionSet) + { + foreach (SettingProperty value in SettingProperties.Values) + { ISetting setting = (ISetting)value.Property.GetValue(this, null); - if ((exclusionSet == null || !exclusionSet.Contains(setting)) && !value.Attribute.IsObsolete) { + if ((exclusionSet == null || !exclusionSet.Contains(setting)) && !value.Attribute.IsObsolete) + { tw.WriteStartElement(value.Attribute.XmlName); setting.WriteXml(tw, node); tw.WriteEndElement(); @@ -101,21 +118,26 @@ protected virtual void WriteSettings(XmlTextWriter tw, RdcTreeNode node, HashSet } } - internal void InheritSettings(RdcTreeNode node, ref bool anyInherited) { + internal void InheritSettings(RdcTreeNode node, ref bool anyInherited) + { GroupBase inheritedSettingsNode = InheritSettingsType.GetInheritedSettingsNode(node); - if (inheritedSettingsNode != null) { + if (inheritedSettingsNode != null) + { inheritedSettingsNode.InheritSettings(); Copy(inheritedSettingsNode); anyInherited = true; } } - protected virtual void Copy(RdcTreeNode node) { + protected virtual void Copy(RdcTreeNode node) + { throw new NotImplementedException(); } - internal void Copy(SettingsGroup source) { - foreach (SettingProperty value in SettingProperties.Values) { + internal void Copy(SettingsGroup source) + { + foreach (SettingProperty value in SettingProperties.Values) + { ISetting setting = (ISetting)value.Property.GetValue(this, null); ISetting source2 = (ISetting)value.Property.GetValue(source, null); setting.Copy(source2); diff --git a/RdcMan/SettingsTabPage.cs b/RdcMan/SettingsTabPage.cs index 668bb15..3effa77 100644 --- a/RdcMan/SettingsTabPage.cs +++ b/RdcMan/SettingsTabPage.cs @@ -3,12 +3,16 @@ using System.Linq; using System.Windows.Forms; -namespace RdcMan { - public class SettingsTabPage : TabPage, ISettingsTabPage { +namespace RdcMan +{ + public class SettingsTabPage : TabPage, ISettingsTabPage + { private const string InvalidSuffix = " (!)"; - InheritanceControl ISettingsTabPage.InheritanceControl { - get { + InheritanceControl ISettingsTabPage.InheritanceControl + { + get + { throw new NotImplementedException(); } } @@ -17,13 +21,16 @@ InheritanceControl ISettingsTabPage.InheritanceControl { protected Control FocusControl { get; set; } - void ISettingsTabPage.UpdateControls() { + void ISettingsTabPage.UpdateControls() + { UpdateControls(); } - bool ISettingsTabPage.Validate() { + bool ISettingsTabPage.Validate() + { string text = Text.Replace(" (!)", string.Empty); - if (IsValid()) { + if (IsValid()) + { Text = text; return true; } @@ -31,28 +38,35 @@ bool ISettingsTabPage.Validate() { return false; } - void ISettingsTabPage.UpdateSettings() { + void ISettingsTabPage.UpdateSettings() + { UpdateSettings(); } - protected virtual void UpdateControls() { - foreach (ISettingControl item in base.Controls.FlattenControls().OfType()) { + protected virtual void UpdateControls() + { + foreach (ISettingControl item in base.Controls.FlattenControls().OfType()) + { item.UpdateControl(); } } - protected virtual bool IsValid() { + protected virtual bool IsValid() + { RdcDialog rdcDialog = FindForm() as RdcDialog; return rdcDialog.ValidateControls(base.Controls.FlattenControls(), isValid: true); } - protected virtual void UpdateSettings() { - foreach (ISettingControl item in base.Controls.FlattenControls().OfType()) { + protected virtual void UpdateSettings() + { + foreach (ISettingControl item in base.Controls.FlattenControls().OfType()) + { item.UpdateSetting(); } } } - public abstract class SettingsTabPage : SettingsTabPage, ISettingsTabPage where TSettingsGroup : SettingsGroup { + public abstract class SettingsTabPage : SettingsTabPage, ISettingsTabPage where TSettingsGroup : SettingsGroup + { protected InheritanceControl InheritanceControl { get; private set; } protected TSettingsGroup Settings { get; private set; } @@ -62,9 +76,12 @@ public abstract class SettingsTabPage : SettingsTabPage, ISettin InheritanceControl ISettingsTabPage.InheritanceControl => InheritanceControl; protected SettingsTabPage(TabbedSettingsDialog dialog, TSettingsGroup settingsGroup) - : this(dialog, settingsGroup, settingsGroup.Name) { } + : this(dialog, settingsGroup, settingsGroup.Name) + { + } - protected SettingsTabPage(TabbedSettingsDialog dialog, TSettingsGroup settingsGroup, string name) { + protected SettingsTabPage(TabbedSettingsDialog dialog, TSettingsGroup settingsGroup, string name) + { Dialog = dialog; Settings = settingsGroup; base.Location = FormTools.TopLeftLocation(); @@ -72,36 +89,47 @@ protected SettingsTabPage(TabbedSettingsDialog dialog, TSettingsGroup settingsGr Text = name; } - protected void CreateInheritanceControl(ref int rowIndex, ref int tabIndex) { - if (Settings.InheritSettingsType.Mode != InheritanceMode.Disabled) { + protected void CreateInheritanceControl(ref int rowIndex, ref int tabIndex) + { + if (Settings.InheritSettingsType.Mode != InheritanceMode.Disabled) + { InheritanceControl = new InheritanceControl(Dialog, Settings.Name); InheritanceControl.Create(this, ref rowIndex, ref tabIndex); } } - void ISettingsTabPage.UpdateControls() { + void ISettingsTabPage.UpdateControls() + { UpdateControls(); } - void ISettingsTabPage.UpdateSettings() { + void ISettingsTabPage.UpdateSettings() + { UpdateSettings(); } - protected override void UpdateControls() { + protected override void UpdateControls() + { if (InheritanceControl != null) + { InheritanceControl.UpdateControlsFromSettings(Settings.InheritSettingsType); - else { - foreach (Control item in base.Controls.FlattenControls()) { + } + else + { + foreach (Control item in base.Controls.FlattenControls()) + { item.Enabled = true; } } base.UpdateControls(); } - protected override void UpdateSettings() { + protected override void UpdateSettings() + { if (InheritanceControl != null) + { Settings.InheritSettingsType.Mode = InheritanceControl.GetInheritanceMode(); - + } base.UpdateSettings(); } } diff --git a/RdcMan/SizeHelper.cs b/RdcMan/SizeHelper.cs index f61f368..4a3018a 100644 --- a/RdcMan/SizeHelper.cs +++ b/RdcMan/SizeHelper.cs @@ -1,29 +1,35 @@ using System; using System.Drawing; -namespace RdcMan { - public static class SizeHelper { +namespace RdcMan +{ + public static class SizeHelper + { public static Size[] StockSizes; public static readonly string Separator = " x "; public static readonly string AltSeparator = ", "; - public static Size Parse(string dim) { + public static Size Parse(string dim) + { string[] array = dim.Split(new string[2] { Separator, AltSeparator }, StringSplitOptions.None); if (array.Length != 2) - throw new InvalidOperationException("Bad Size string {0}".InvariantFormat(dim)); - + { + throw new InvalidOperationException("Bad Size string '{0}'".InvariantFormat(dim)); + } return FromString(array[0], array[1]); } - public static Size FromString(string widthStr, string heightStr) { + public static Size FromString(string widthStr, string heightStr) + { int width = int.Parse(widthStr); int height = int.Parse(heightStr); return new Size(width, height); } - public static string ToFormattedString(this Size size) { + public static string ToFormattedString(this Size size) + { return "{0}{1}{2}".InvariantFormat(size.Width, Separator, size.Height); } } diff --git a/RdcMan/SizeSetting.cs b/RdcMan/SizeSetting.cs index 7f862c3..51c1f7c 100644 --- a/RdcMan/SizeSetting.cs +++ b/RdcMan/SizeSetting.cs @@ -1,19 +1,24 @@ using System.Drawing; using System.Xml; -namespace RdcMan { - public class SizeSetting : Setting { +namespace RdcMan +{ + public class SizeSetting : Setting + { public SizeSetting(object o) : base(o) { } - public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) { + public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) + { base.Value = SizeHelper.Parse(xmlNode.FirstChild.InnerText); } - public override void WriteXml(XmlTextWriter tw, RdcTreeNode node) { + public override void WriteXml(XmlTextWriter tw, RdcTreeNode node) + { tw.WriteString(base.Value.ToFormattedString()); } - public override string ToString() { + public override string ToString() + { return base.Value.ToFormattedString(); } } diff --git a/RdcMan/SmartGroup.cs b/RdcMan/SmartGroup.cs index e648c6d..5b751ea 100644 --- a/RdcMan/SmartGroup.cs +++ b/RdcMan/SmartGroup.cs @@ -4,11 +4,13 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { - internal class SmartGroup : VirtualGroup { +namespace RdcMan +{ + internal class SmartGroup : VirtualGroup + { internal const string XmlNodeName = "smartGroup"; - private static readonly List AllSmartGroups; + private static List AllSmartGroups; protected new static Dictionary NodeActions; @@ -16,31 +18,37 @@ internal class SmartGroup : VirtualGroup { public RuleGroup RuleGroup { get; private set; } - static SmartGroup() { + static SmartGroup() + { AllSmartGroups = new List(); NodeActions = new Dictionary(GroupBase.NodeActions); - NodeActions["ruleGroup"] = delegate (XmlNode childNode, RdcTreeNode node, ICollection errors) { + NodeActions["ruleGroup"] = delegate(XmlNode childNode, RdcTreeNode node, ICollection errors) + { (node as SmartGroup).RuleGroup = RuleGroup.Create(childNode, node, errors); }; ServerTree.Instance.GroupChanged += OnGroupChanged; ServerTree.Instance.ServerChanged += OnServerChanged; } - protected SmartGroup() { + protected SmartGroup() + { AllSmartGroups.Add(this); } - protected override void InitSettings() { + protected override void InitSettings() + { ((RdcTreeNode)this).Properties = new SmartGroupSettings(); base.AllSettingsGroups.Add(Properties); RuleGroup = new RuleGroup(RuleGroupOperator.All, Enumerable.Empty()); } - public static SmartGroup CreateForAdd() { + public static SmartGroup CreateForAdd() + { return new SmartGroup(); } - public static SmartGroup Create(SmartGroupPropertiesDialog dlg) { + public static SmartGroup Create(SmartGroupPropertiesDialog dlg) + { SmartGroup smartGroup = dlg.AssociatedNode as SmartGroup; smartGroup.UpdateSettings(dlg); smartGroup.FinishConstruction(dlg.PropertiesPage.ParentGroup); @@ -48,7 +56,8 @@ public static SmartGroup Create(SmartGroupPropertiesDialog dlg) { return smartGroup; } - public static SmartGroup Create(XmlNode xmlNode, GroupBase parent, ICollection errors) { + public static SmartGroup Create(XmlNode xmlNode, GroupBase parent, ICollection errors) + { SmartGroup smartGroup = new SmartGroup(); smartGroup.FinishConstruction(parent); smartGroup.ReadXml(xmlNode, errors); @@ -56,69 +65,90 @@ public static SmartGroup Create(XmlNode xmlNode, GroupBase parent, ICollection process) { - scope?.VisitParents(delegate (RdcTreeNode parent) { - foreach (SmartGroup item in parent.Nodes.OfType()) { + private static void RefreshScope(GroupBase scope, Action process) + { + scope?.VisitParents(delegate(RdcTreeNode parent) + { + foreach (SmartGroup item in parent.Nodes.OfType()) + { process(item); } }); } - public sealed override void DoPropertiesDialog(Form parentForm, string activeTabName) { + public sealed override void DoPropertiesDialog(Form parentForm, string activeTabName) + { using SmartGroupPropertiesDialog smartGroupPropertiesDialog = SmartGroupPropertiesDialog.NewPropertiesDialog(this, parentForm); smartGroupPropertiesDialog.SetActiveTab(activeTabName); - if (smartGroupPropertiesDialog.ShowDialog() == DialogResult.OK) { + if (smartGroupPropertiesDialog.ShowDialog() == DialogResult.OK) + { UpdateSettings(smartGroupPropertiesDialog); Refresh(); } } - public sealed override bool CanRemoveChildren() { + public sealed override bool CanRemoveChildren() + { return false; } - internal override void ReadXml(XmlNode xmlNode, ICollection errors) { + internal override void ReadXml(XmlNode xmlNode, ICollection errors) + { ReadXml(NodeActions, xmlNode, errors); } - internal override void WriteXml(XmlTextWriter tw) { + internal override void WriteXml(XmlTextWriter tw) + { tw.WriteStartElement("smartGroup"); Properties.Expanded.Value = base.IsExpanded; WriteXmlSettingsGroups(tw); @@ -126,53 +156,70 @@ internal override void WriteXml(XmlTextWriter tw) { tw.WriteEndElement(); } - public void Refresh() { + public void Refresh() + { bool changed = false; - using (Helpers.Timer("refreshing smart group {0}", base.Text)) { - ServerTree.Instance.Operation(OperationBehavior.SuspendSort | OperationBehavior.SuspendUpdate | OperationBehavior.SuspendGroupChanged, delegate { + using (Helpers.Timer("refreshing smart group {0}", base.Text)) + { + ServerTree.Instance.Operation(OperationBehavior.SuspendSort | OperationBehavior.SuspendUpdate | OperationBehavior.SuspendGroupChanged, delegate + { HashSet set = new HashSet(); - base.Nodes.ForEach(delegate (TreeNode s) { + base.Nodes.ForEach(delegate(TreeNode s) + { set.Add(s as SmartServerRef); }); - this.GetParentNodes().VisitNodes(delegate (RdcTreeNode node) { + this.GetParentNodes().VisitNodes(delegate(RdcTreeNode node) + { if (node is VirtualGroup) + { return NodeVisitorResult.NoRecurse; - if (node is Server server) { + } + if (node is Server server) + { SmartServerRef item = UpdateForServer(server, ref changed); set.Remove(item); } return NodeVisitorResult.Continue; }); - if (set.Count > 0) { + if (set.Count > 0) + { changed = true; - set.ForEach(delegate (SmartServerRef s) { + set.ForEach(delegate(SmartServerRef s) + { ServerTree.Instance.RemoveNode(s); }); } }); } - if (changed) { + if (changed) + { ServerTree.Instance.SortGroup(this); ServerTree.Instance.OnGroupChanged(this, ChangeType.InvalidateUI); } } - private SmartServerRef UpdateForServer(Server server, ref bool changed) { + private SmartServerRef UpdateForServer(Server server, ref bool changed) + { SmartServerRef smartServerRef = server.FindServerRef(this); bool flag = RuleGroup != null && RuleGroup.Evaluate(server); - if (smartServerRef != null != flag) { + if (smartServerRef != null != flag) + { changed = true; - if (flag) { + if (flag) + { smartServerRef = new SmartServerRef(server); ServerTree.Instance.AddNode(smartServerRef, this); } else + { ServerTree.Instance.RemoveNode(smartServerRef); + } } return smartServerRef; } - private void FinishConstruction(GroupBase parent) { + private void FinishConstruction(GroupBase parent) + { ServerTree.Instance.AddNode(this, parent); ChangeImageIndex(ImageConstants.SmartGroup); } diff --git a/RdcMan/SmartGroupPropertiesDialog.cs b/RdcMan/SmartGroupPropertiesDialog.cs index 2e99c5c..a4f1c8e 100644 --- a/RdcMan/SmartGroupPropertiesDialog.cs +++ b/RdcMan/SmartGroupPropertiesDialog.cs @@ -1,11 +1,16 @@ using System.Windows.Forms; -namespace RdcMan { - internal class SmartGroupPropertiesDialog : NodePropertiesDialog { +namespace RdcMan +{ + internal class SmartGroupPropertiesDialog : NodePropertiesDialog + { protected SmartGroupPropertiesDialog(SmartGroup group, string dialogTitle, string acceptButtonText, Form parentForm) - : base(group, dialogTitle, acceptButtonText, parentForm) { } + : base(group, dialogTitle, acceptButtonText, parentForm) + { + } - public override void CreateControls(RdcTreeNode settings) { + public override void CreateControls(RdcTreeNode settings) + { TabPage tabPage = settings.Properties.CreateTabPage(this); base.PropertiesPage = tabPage as INodePropertiesPage; AddTabPage(tabPage); @@ -13,21 +18,25 @@ public override void CreateControls(RdcTreeNode settings) { this.ScaleAndLayout(); } - public static SmartGroupPropertiesDialog NewAddDialog(GroupBase parent) { + public static SmartGroupPropertiesDialog NewAddDialog(GroupBase parent) + { SmartGroup smartGroup = SmartGroup.CreateForAdd(); SmartGroupPropertiesDialog smartGroupPropertiesDialog = new SmartGroupPropertiesDialog(smartGroup, "", "", null); if (parent != null && !parent.CanAddGroups()) + { parent = null; - + } smartGroupPropertiesDialog.CreateControls(smartGroup); - if (!smartGroupPropertiesDialog.PropertiesPage.PopulateParentDropDown(null, parent)) { + if (!smartGroupPropertiesDialog.PropertiesPage.PopulateParentDropDown(null, parent)) + { smartGroupPropertiesDialog.Dispose(); return null; } return smartGroupPropertiesDialog; } - public static SmartGroupPropertiesDialog NewPropertiesDialog(SmartGroup group, Form parentForm) { + public static SmartGroupPropertiesDialog NewPropertiesDialog(SmartGroup group, Form parentForm) + { SmartGroupPropertiesDialog smartGroupPropertiesDialog = new SmartGroupPropertiesDialog(group, group.Text + " ", "ȷ", parentForm); smartGroupPropertiesDialog.CreateControls(group); smartGroupPropertiesDialog.PropertiesPage.PopulateParentDropDown(group, group.Parent as GroupBase); diff --git a/RdcMan/SmartGroupPropertiesTabPage.cs b/RdcMan/SmartGroupPropertiesTabPage.cs index 229ddce..28f52a6 100644 --- a/RdcMan/SmartGroupPropertiesTabPage.cs +++ b/RdcMan/SmartGroupPropertiesTabPage.cs @@ -5,9 +5,12 @@ using System.Text.RegularExpressions; using System.Windows.Forms; -namespace RdcMan { - internal class SmartGroupPropertiesTabPage : GroupBasePropertiesTabPage { - private class SmartRuleControl : Control { +namespace RdcMan +{ + internal class SmartGroupPropertiesTabPage : GroupBasePropertiesTabPage + { + private class SmartRuleControl : Control + { private readonly ValueComboBox _propertyCombo; private readonly ValueComboBox _operatorCombo; @@ -28,33 +31,39 @@ private class SmartRuleControl : Control { public int Index { get; set; } - public SmartRuleControl(Rule rule, ref int tabIndex) { - _propertyCombo = new ValueComboBox(Helpers.EnumValues(), (ServerProperty v) => v.ToString()) { + public SmartRuleControl(Rule rule, ref int tabIndex) + { + _propertyCombo = new ValueComboBox(Helpers.EnumValues(), (ServerProperty v) => v.ToString()) + { Location = new Point(0, 0), Width = 100, TabIndex = tabIndex++, SelectedValue = ServerProperty.DisplayName }; - _operatorCombo = new ValueComboBox(Helpers.EnumValues(), (RuleOperator v) => v.ToString()) { + _operatorCombo = new ValueComboBox(Helpers.EnumValues(), (RuleOperator v) => v.ToString()) + { Location = new Point(_propertyCombo.Right + 4, 0), Width = 100, TabIndex = tabIndex++, SelectedValue = RuleOperator.Matches }; - _valueTextBox = new TextBox { + _valueTextBox = new TextBox + { Enabled = true, Location = new Point(_operatorCombo.Right + 4, 0), Width = RuleWidth - (_operatorCombo.Right + 4) - 48, TabIndex = tabIndex++ }; - DeleteButton = new Button { + DeleteButton = new Button + { Enabled = true, Location = new Point(_valueTextBox.Right + 4, 0), Size = new Size(20, FormTools.ControlHeight), TabIndex = tabIndex++, Text = "-" }; - AddButton = new Button { + AddButton = new Button + { Enabled = true, Location = new Point(DeleteButton.Right + 4, 0), Size = new Size(20, FormTools.ControlHeight), @@ -64,7 +73,8 @@ public SmartRuleControl(Rule rule, ref int tabIndex) { base.Controls.Add(_propertyCombo, _operatorCombo, _valueTextBox, DeleteButton, AddButton); base.Size = new Size(RuleWidth, RuleHeight); base.TabStop = false; - if (rule != null) { + if (rule != null) + { _propertyCombo.SelectedValue = rule.Property.ServerProperty; _operatorCombo.SelectedValue = rule.Operator; _valueTextBox.Text = rule.Value.ToString(); @@ -85,33 +95,38 @@ public SmartRuleControl(Rule rule, ref int tabIndex) { private int _nextRuleTabIndex; public SmartGroupPropertiesTabPage(TabbedSettingsDialog dialog, SmartGroupSettings settings) - : base(dialog, settings, settings.Name) { + : base(dialog, settings, settings.Name) + { _ruleGroup = ((dialog as SmartGroupPropertiesDialog).AssociatedNode as SmartGroup).RuleGroup; int rowIndex = 0; int nextRuleTabIndex = 0; AddGroupName(ref rowIndex, ref nextRuleTabIndex); AddParentCombo(ref rowIndex, ref nextRuleTabIndex); rowIndex++; - Label label = new Label { + Label label = new Label + { Location = FormTools.NewLocation(0, rowIndex++), Text = "ƥķ", TextAlign = ContentAlignment.MiddleLeft, Size = new Size(110, FormTools.ControlHeight) }; - _anyAllCombo = new ValueComboBox(Helpers.EnumValues(), (RuleGroupOperator v) => v.ToString()) { + _anyAllCombo = new ValueComboBox(Helpers.EnumValues(), (RuleGroupOperator v) => v.ToString()) + { Location = new Point(label.Right, label.Top), Size = new Size(50, FormTools.ControlHeight), TabIndex = nextRuleTabIndex++, SelectedValue = RuleGroupOperator.All }; - Label label2 = new Label { + Label label2 = new Label + { Location = new Point(_anyAllCombo.Right + 5, label.Top), Text = "¹е", TextAlign = ContentAlignment.MiddleLeft, Size = new Size(FormTools.LabelWidth, FormTools.ControlHeight) }; base.Controls.Add(label, _anyAllCombo, label2); - GroupBox groupBox = new GroupBox { + GroupBox groupBox = new GroupBox + { Location = FormTools.NewLocation(0, rowIndex++) }; int num = FormTools.TabPageControlHeight - groupBox.Top - 40; @@ -128,30 +143,43 @@ public SmartGroupPropertiesTabPage(TabbedSettingsDialog dialog, SmartGroupSettin base.Controls.Add(groupBox); } - protected override void UpdateControls() { + protected override void UpdateControls() + { base.UpdateControls(); _anyAllCombo.SelectedValue = _ruleGroup.Operator; if (_ruleGroup.Rules.Count > 0) + { _ruleGroup.Rules.ForEach(AddRuleControl); + } else + { AddRuleControl(null); - + } LayoutRuleControls(); } - protected override bool IsValid() { + protected override bool IsValid() + { bool flag = true; - foreach (SmartRuleControl control in _rulePanel.Controls) { + foreach (SmartRuleControl control in _rulePanel.Controls) + { string text = null; - try { - if (control.Value is string text2) { + try + { + if (control.Value is string text2) + { if (string.IsNullOrEmpty(text2)) + { text = "һʽ"; + } else + { Regex.Match(string.Empty, text2); + } } } - catch (Exception ex) { + catch (Exception ex) + { text = ex.Message; } flag &= !base.Dialog.SetError(control.ValueControl, text); @@ -159,63 +187,79 @@ protected override bool IsValid() { return flag ? base.IsValid() : false; } - protected override void UpdateSettings() { + protected override void UpdateSettings() + { base.UpdateSettings(); List source = _rulePanel.Controls.Cast().ToList(); IEnumerable rules = from r in source - orderby r.Index - select r into c - select new Rule(new RuleProperty(c.Property), c.Operator, c.Value); + orderby r.Index + select r into c + select new Rule(new RuleProperty(c.Property), c.Operator, c.Value); _ruleGroup.Set(_anyAllCombo.SelectedValue, rules); } protected override void ParentGroupChangedHandler(object sender, EventArgs e) { } - private void InsertRuleControl(SmartRuleControl afterRule) { + private void InsertRuleControl(SmartRuleControl afterRule) + { int num = afterRule.Index + 1; - foreach (SmartRuleControl control in _rulePanel.Controls) { + foreach (SmartRuleControl control in _rulePanel.Controls) + { if (control.Index >= num) + { control.Index++; + } } SmartRuleControl value = CreateRuleControl(null, num); _rulePanel.Controls.Add(value); LayoutRuleControls(); } - private void AddRuleControl(Rule rule) { + private void AddRuleControl(Rule rule) + { SmartRuleControl value = CreateRuleControl(rule, _rulePanel.Controls.Count); _rulePanel.Controls.Add(value); } - private SmartRuleControl CreateRuleControl(Rule rule, int index) { - SmartRuleControl newRule = new SmartRuleControl(rule, ref _nextRuleTabIndex) { + private SmartRuleControl CreateRuleControl(Rule rule, int index) + { + SmartRuleControl newRule = new SmartRuleControl(rule, ref _nextRuleTabIndex) + { Index = index }; - newRule.AddButton.Click += delegate { + newRule.AddButton.Click += delegate + { InsertRuleControl(newRule); }; - newRule.DeleteButton.Click += delegate { + newRule.DeleteButton.Click += delegate + { DeleteRuleControl(newRule); }; return newRule; } - private void DeleteRuleControl(SmartRuleControl rule) { + private void DeleteRuleControl(SmartRuleControl rule) + { int index = rule.Index; _rulePanel.Controls.Remove(rule); - foreach (SmartRuleControl control in _rulePanel.Controls) { + foreach (SmartRuleControl control in _rulePanel.Controls) + { if (control.Index > index) + { control.Index--; + } } LayoutRuleControls(); } - private void LayoutRuleControls() { + private void LayoutRuleControls() + { int count = _rulePanel.Controls.Count; int num = 0; _rulePanel.SuspendLayout(); int value = _rulePanel.VerticalScroll.Value; - foreach (SmartRuleControl control in _rulePanel.Controls) { + foreach (SmartRuleControl control in _rulePanel.Controls) + { control.DeleteButton.Enabled = count > 1; control.Location = new Point(0, control.Index * 25 - value); num = Math.Max(num, control.Top); diff --git a/RdcMan/SmartGroupSettings.cs b/RdcMan/SmartGroupSettings.cs index 5a1f546..5dc4346 100644 --- a/RdcMan/SmartGroupSettings.cs +++ b/RdcMan/SmartGroupSettings.cs @@ -2,25 +2,30 @@ using System.Windows.Forms; using System.Xml; -namespace RdcMan { - public class SmartGroupSettings : GroupSettings { - //internal new const string TabName = ""; +namespace RdcMan +{ + public class SmartGroupSettings : GroupSettings + { + //internal new const string TabName = "Smart Group Settings"; private static Dictionary _settingProperties; protected override Dictionary SettingProperties => _settingProperties; - static SmartGroupSettings() { + static SmartGroupSettings() + { typeof(SmartGroupSettings).GetSettingProperties(out _settingProperties); } public SmartGroupSettings() : base("") { } - public override TabPage CreateTabPage(TabbedSettingsDialog dialog) { + public override TabPage CreateTabPage(TabbedSettingsDialog dialog) + { return new SmartGroupPropertiesTabPage(dialog, this); } - protected override void WriteSettings(XmlTextWriter tw, RdcTreeNode node) { + protected override void WriteSettings(XmlTextWriter tw, RdcTreeNode node) + { HashSet hashSet = new HashSet(); if (string.IsNullOrEmpty(base.Comment.Value)) hashSet.Add(base.Comment); diff --git a/RdcMan/SmartServerRef.cs b/RdcMan/SmartServerRef.cs index d0bb413..12c7f4f 100644 --- a/RdcMan/SmartServerRef.cs +++ b/RdcMan/SmartServerRef.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - internal class SmartServerRef : ServerRef { +namespace RdcMan +{ + internal class SmartServerRef : ServerRef + { public SmartServerRef(Server server) : base(server) { } public override bool ConfirmRemove(bool askUser) { diff --git a/RdcMan/SortExtensions.cs b/RdcMan/SortExtensions.cs index 7e2ef3b..387ec66 100644 --- a/RdcMan/SortExtensions.cs +++ b/RdcMan/SortExtensions.cs @@ -2,63 +2,82 @@ using System.Linq; using System.Windows.Forms; -namespace RdcMan { - internal static class SortExtensions { - private class ServerTreeSortComparer : IComparer { +namespace RdcMan +{ + internal static class SortExtensions + { + private class ServerTreeSortComparer : IComparer + { private SortOrder _sortOrder; - public ServerTreeSortComparer(SortOrder sortOrder) { + public ServerTreeSortComparer(SortOrder sortOrder) + { _sortOrder = sortOrder; } - public int Compare(TreeNode treeNode1, TreeNode treeNode2) { - if (_sortOrder == SortOrder.ByStatus) { + public int Compare(TreeNode treeNode1, TreeNode treeNode2) + { + if (_sortOrder == SortOrder.ByStatus) + { ImageConstants imageConstants = ServerTree.TranslateImage((ImageConstants)treeNode1.ImageIndex, toSelected: false); ImageConstants imageConstants2 = ServerTree.TranslateImage((ImageConstants)treeNode2.ImageIndex, toSelected: false); int num = imageConstants2 - imageConstants; if (num != 0) + { return num; + } } return Helpers.NaturalCompare(treeNode1.Text, treeNode2.Text); } } - public static void SortBuiltinGroups(this ServerTree tree) { - if (!tree.SuppressSorting) { + public static void SortBuiltinGroups(this ServerTree tree) + { + if (!tree.SuppressSorting) + { List list = tree.Nodes.OfType().Cast().ToList(); tree.Nodes.SortAndRebuildNodeList(list, SortOrder.ByName); } } - public static void SortAllNodes(this ServerTree tree) { - using (Helpers.Timer("sorting all nodes")) { - tree.Operation(OperationBehavior.RestoreSelected, delegate { + public static void SortAllNodes(this ServerTree tree) + { + using (Helpers.Timer("sorting all nodes")) + { + tree.Operation(OperationBehavior.RestoreSelected, delegate + { tree.SortHelper(tree.Nodes, recurse: true); tree.SortBuiltinGroups(); }); } } - public static void SortRoot(this ServerTree tree) { - tree.Operation(OperationBehavior.RestoreSelected | OperationBehavior.SuspendUpdate, delegate { + public static void SortRoot(this ServerTree tree) + { + tree.Operation(OperationBehavior.RestoreSelected | OperationBehavior.SuspendUpdate, delegate + { tree.SortHelper(tree.Nodes, recurse: false); tree.SortBuiltinGroups(); }); } - public static bool SortGroup(this ServerTree tree, GroupBase group) { + public static bool SortGroup(this ServerTree tree, GroupBase group) + { return tree.SortGroup(group, recurse: false); } - public static bool SortGroup(this ServerTree tree, GroupBase group, bool recurse) { + public static bool SortGroup(this ServerTree tree, GroupBase group, bool recurse) + { bool result = false; if (group.AllowSort) + { result = tree.SortHelper(group.Nodes, recurse); - + } return result; } - public static bool SortNode(this ServerTree tree, RdcTreeNode node) { + public static bool SortNode(this ServerTree tree, RdcTreeNode node) + { if (node.Parent is GroupBase group) return tree.SortGroup(group); @@ -68,31 +87,37 @@ public static bool SortNode(this ServerTree tree, RdcTreeNode node) { return false; } - private static bool SortHelper(this ServerTree tree, TreeNodeCollection nodes, bool recurse) { + private static bool SortHelper(this ServerTree tree, TreeNodeCollection nodes, bool recurse) + { if (tree.SuppressSorting) return false; bool anyChanged = false; - tree.Operation(OperationBehavior.RestoreSelected | OperationBehavior.SuspendUpdate, delegate { + tree.Operation(OperationBehavior.RestoreSelected | OperationBehavior.SuspendUpdate, delegate + { anyChanged = tree.SortNodes(nodes, recurse); }); return anyChanged; } - private static bool SortNodes(this ServerTree tree, TreeNodeCollection nodes, bool recurse) { + private static bool SortNodes(this ServerTree tree, TreeNodeCollection nodes, bool recurse) + { List list = new List(nodes.Count); List list2 = new List(nodes.Count); - foreach (TreeNode node in nodes) { + foreach (TreeNode node in nodes) + { if (node is ServerBase) list2.Add(node); else list.Add(node); } bool flag = false; - if (recurse) { + if (recurse) + { foreach (GroupBase item in from g in list.OfType() - where g.AllowSort - select g) { + where g.AllowSort + select g) + { flag |= tree.SortNodes(item.Nodes, recurse: true); } } @@ -100,15 +125,18 @@ where g.AllowSort return flag | nodes.SortAndRebuildNodeList(list2, Program.Preferences.ServerSortOrder); } - private static bool SortAndRebuildNodeList(this TreeNodeCollection nodes, List list, SortOrder sortOrder) { + private static bool SortAndRebuildNodeList(this TreeNodeCollection nodes, List list, SortOrder sortOrder) + { if (list.Count == 0 || sortOrder == SortOrder.None) return false; list.Sort(new ServerTreeSortComparer(sortOrder)); TreeNode treeNode = nodes[0]; bool result = false; - foreach (TreeNode item in list) { - if (item == treeNode) { + foreach (TreeNode item in list) + { + if (item == treeNode) + { treeNode = treeNode.NextNode; continue; } diff --git a/RdcMan/SortGroupsCheckedMenuItem.cs b/RdcMan/SortGroupsCheckedMenuItem.cs index 4818458..c8526f6 100644 --- a/RdcMan/SortGroupsCheckedMenuItem.cs +++ b/RdcMan/SortGroupsCheckedMenuItem.cs @@ -1,10 +1,15 @@ -namespace RdcMan { - internal class SortGroupsCheckedMenuItem : EnumMenuItem { - protected override SortOrder Value { - get { +namespace RdcMan +{ + internal class SortGroupsCheckedMenuItem : EnumMenuItem + { + protected override SortOrder Value + { + get + { return Program.Preferences.GroupSortOrder; } - set { + set + { Program.Preferences.GroupSortOrder = value; ServerTree.Instance.SortAllNodes(); ServerTree.Instance.OnGroupChanged(ServerTree.Instance.RootNode, ChangeType.PropertyChanged); diff --git a/RdcMan/SortOrder.cs b/RdcMan/SortOrder.cs index 4b97123..e09e86b 100644 --- a/RdcMan/SortOrder.cs +++ b/RdcMan/SortOrder.cs @@ -1,5 +1,7 @@ -namespace RdcMan { - public enum SortOrder { +namespace RdcMan +{ + public enum SortOrder + { ByStatus, ByName, None diff --git a/RdcMan/SortServersCheckedMenuItem.cs b/RdcMan/SortServersCheckedMenuItem.cs index 8f243f5..1801d51 100644 --- a/RdcMan/SortServersCheckedMenuItem.cs +++ b/RdcMan/SortServersCheckedMenuItem.cs @@ -1,10 +1,15 @@ -namespace RdcMan { - internal class SortServersCheckedMenuItem : EnumMenuItem { - protected override SortOrder Value { - get { +namespace RdcMan +{ + internal class SortServersCheckedMenuItem : EnumMenuItem + { + protected override SortOrder Value + { + get + { return Program.Preferences.ServerSortOrder; } - set { + set + { Program.Preferences.ServerSortOrder = value; ServerTree.Instance.SortAllNodes(); ServerTree.Instance.OnGroupChanged(ServerTree.Instance.RootNode, ChangeType.PropertyChanged); diff --git a/RdcMan/StringSetting.cs b/RdcMan/StringSetting.cs index b704512..84a4361 100644 --- a/RdcMan/StringSetting.cs +++ b/RdcMan/StringSetting.cs @@ -1,18 +1,29 @@ using System.Xml; -namespace RdcMan { - public class StringSetting : Setting { - public StringSetting(object o) : base(o) { +namespace RdcMan +{ + public class StringSetting : Setting + { + public StringSetting(object o) + : base(o) + { if (base.Value == null) + { base.Value = string.Empty; + } } - public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) { + public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) + { xmlNode = xmlNode.FirstChild; if (xmlNode == null) + { base.Value = string.Empty; + } else + { base.Value = xmlNode.InnerText; + } } } } diff --git a/RdcMan/StringUtilities.cs b/RdcMan/StringUtilities.cs index 88ee5eb..2c7da7c 100644 --- a/RdcMan/StringUtilities.cs +++ b/RdcMan/StringUtilities.cs @@ -2,8 +2,10 @@ using System.Collections.Generic; using System.Globalization; -namespace RdcMan { - public static class StringUtilities { +namespace RdcMan +{ + public static class StringUtilities + { private const char SetOpenChar = '{'; private const char SetSeparatorChar = ','; @@ -16,103 +18,139 @@ public static class StringUtilities { private const char RangeCloseChar = ']'; - public static string CultureFormat(this string format, params object[] args) { + public static string CultureFormat(this string format, params object[] args) + { return string.Format(CultureInfo.CurrentUICulture, format, args); } - public static string InvariantFormat(this string format, params object[] args) { + public static string InvariantFormat(this string format, params object[] args) + { return string.Format(CultureInfo.InvariantCulture, format, args); } - public static IEnumerable ExpandPattern(string pattern) { + public static IEnumerable ExpandPattern(string pattern) + { bool flag = false; - for (int i = 0; i < pattern.Length; i++) { - switch (pattern[i]) { - case SetOpenChar: { - int num2 = pattern.IndexOf(SetCloseChar, i); - if (num2 == -1) - throw new ArgumentException($"δպϣȱʧ {SetCloseChar}{pattern.Substring(i)}"); - - string prefix = pattern.Substring(0, i); - string suffix = pattern.Substring(num2 + 1); - IEnumerable enumerable2 = ExpandSet(pattern.Substring(i + 1, num2 - i - 1)); - foreach (string setValue in enumerable2) { - foreach (string item in ExpandPattern(suffix)) { - yield return prefix + setValue + item; - } + for (int i = 0; i < pattern.Length; i++) + { + switch (pattern[i]) + { + case SetOpenChar: + { + int num2 = pattern.IndexOf(SetCloseChar, i); + if (num2 == -1) + { + throw new ArgumentException($"δպϣȱʧ {SetCloseChar}{pattern.Substring(i)}"); + } + string prefix = pattern.Substring(0, i); + string suffix = pattern.Substring(num2 + 1); + IEnumerable enumerable2 = ExpandSet(pattern.Substring(i + 1, num2 - i - 1)); + foreach (string setValue in enumerable2) + { + foreach (string item in ExpandPattern(suffix)) + { + yield return prefix + setValue + item; } - flag = true; - break; } - case RangeOpenChar: { - int num = pattern.IndexOf(RangeCloseChar, i); - if (num == -1) - throw new ArgumentException($"Χδպϣȱʧ {RangeCloseChar}{pattern.Substring(i)}"); - - string suffix = pattern.Substring(0, i); - string prefix = pattern.Substring(num + 1); - IEnumerable enumerable = ExpandRange(pattern.Substring(i + 1, num - i - 1)); - foreach (string setValue in enumerable) { - foreach (string item2 in ExpandPattern(prefix)) { - yield return suffix + setValue + item2; - } + flag = true; + break; + } + case RangeOpenChar: + { + int num = pattern.IndexOf(RangeCloseChar, i); + if (num == -1) + { + throw new ArgumentException($"Χδպϣȱʧ {RangeCloseChar}{pattern.Substring(i)}"); + } + string suffix = pattern.Substring(0, i); + string prefix = pattern.Substring(num + 1); + IEnumerable enumerable = ExpandRange(pattern.Substring(i + 1, num - i - 1)); + foreach (string setValue in enumerable) + { + foreach (string item2 in ExpandPattern(prefix)) + { + yield return suffix + setValue + item2; } - flag = true; - break; } - default: - continue; + flag = true; + break; + } + default: + continue; } break; } if (!flag) + { yield return pattern; + } } - private static IEnumerable ExpandSet(string set) { + private static IEnumerable ExpandSet(string set) + { return set.Split(SetSeparatorChar); } - private static IEnumerable ExpandRange(string range) { + private static IEnumerable ExpandRange(string range) + { string[] array = range.Split(RangeSeparatorChar); if (array.Length != 2) + { throw new ArgumentException($"Χֵ͸ֵ {RangeSeparatorChar} ָ{range}"); - + } string text = array[0]; string text2 = array[1]; if (text.Length == 0 || text2.Length == 0) + { throw new ArgumentException($"Χȱֵ {range}"); - - if (char.IsLetter(text, 0)) { + } + if (char.IsLetter(text, 0)) + { if (!char.IsLetter(text2, 0)) + { throw new ArgumentException($"Χͬ͵ģĸΧַΧ {range}"); + } if (text.Length != 1 || text2.Length != 1) + { throw new ArgumentException($"ĸΧǵַ{range}"); + } if (char.IsLower(text[0]) != char.IsLower(text2[0])) + { throw new ArgumentException($"ĸΧͬ {range}"); + } if (text.CompareTo(text2) > 0) + { throw new ArgumentException($"ΧͲܴڸߣ{range}"); - + } int num = text[0]; int highValue2 = text2[0]; - for (int value2 = num; value2 <= highValue2; value2++) { + for (int value2 = num; value2 <= highValue2; value2++) + { yield return $"{(char)value2}"; } } - else { + else + { if (!char.IsDigit(text, 0)) + { throw new ArgumentException($"ʽķΧĸΧַΧ{range}"); + } if (!int.TryParse(text, out var result) || !int.TryParse(text2, out var highValue2)) + { throw new ArgumentException($"ΧͬʵģĸΧַΧ{range}"); + } if (result > highValue2) + { throw new ArgumentException($"ΧͲܴڸߣ{range}"); - + } int length = text.Length; string format = ""; - for (int i = 0; i < length; i++) { + for (int i = 0; i < length; i++) + { format += "0"; } - for (int value2 = result; value2 <= highValue2; value2++) { + for (int value2 = result; value2 <= highValue2; value2++) + { yield return value2.ToString(format); } } diff --git a/RdcMan/TabbedSettingsDialog.cs b/RdcMan/TabbedSettingsDialog.cs index 4be48b7..5dcd128 100644 --- a/RdcMan/TabbedSettingsDialog.cs +++ b/RdcMan/TabbedSettingsDialog.cs @@ -4,8 +4,10 @@ using System.Linq; using System.Windows.Forms; -namespace RdcMan { - public class TabbedSettingsDialog : RdcDialog { +namespace RdcMan +{ + public class TabbedSettingsDialog : RdcDialog + { private TabPage _initiallyActiveTab; private readonly TabControl _tabControl; @@ -13,8 +15,10 @@ public class TabbedSettingsDialog : RdcDialog { public IEnumerable TabPages => _tabControl.TabPages.Cast(); public TabbedSettingsDialog(string dialogTitle, string acceptButtonText, Form parentForm) - : base(dialogTitle, acceptButtonText, parentForm) { - _tabControl = new TabControl { + : base(dialogTitle, acceptButtonText, parentForm) + { + _tabControl = new TabControl + { Location = new Point(8, 8), SelectedIndex = 0, Size = new Size(FormTools.TabControlWidth, FormTools.TabControlHeight), @@ -24,53 +28,73 @@ public TabbedSettingsDialog(string dialogTitle, string acceptButtonText, Form pa base.Controls.Add(_tabControl); } - public void AddTabPage(TabPage page) { + public void AddTabPage(TabPage page) + { _tabControl.TabPages.Add(page); } - public void SetActiveTab(string name) { + public void SetActiveTab(string name) + { _initiallyActiveTab = TabPages.Where((TabPage p) => p.Text == name).FirstOrDefault(); } - public void UpdateSettings() { - foreach (ISettingsTabPage item in TabPages.OfType()) { + public void UpdateSettings() + { + foreach (ISettingsTabPage item in TabPages.OfType()) + { item.UpdateSettings(); } } - public void EnableTabs(EnableTabsEventArgs args) { - foreach (string name in args.TabNames) { + public void EnableTabs(EnableTabsEventArgs args) + { + foreach (string name in args.TabNames) + { TabPage tabPage = TabPages.Where((TabPage p) => p.Text.Equals(name)).First(); ISettingsTabPage settingsTabPage = tabPage as ISettingsTabPage; settingsTabPage.InheritanceControl.Enable(args.Enabled, args.Reason); } } - protected override void ShownCallback(object sender, EventArgs args) { - foreach (TabPage tabPage in TabPages) { + protected override void ShownCallback(object sender, EventArgs args) + { + foreach (TabPage tabPage in TabPages) + { tabPage.Enabled = _acceptButton.Enabled; - if (tabPage is ISettingsTabPage settingsTabPage) { + if (tabPage is ISettingsTabPage settingsTabPage) + { settingsTabPage.UpdateControls(); - if (settingsTabPage.FocusControl != null) { + if (settingsTabPage.FocusControl != null) + { _tabControl.SelectedTab = tabPage; settingsTabPage.FocusControl.Focus(); } } } if (_initiallyActiveTab != null) + { _tabControl.SelectedTab = _initiallyActiveTab; + } } - protected override void AcceptIfValid(object sender, EventArgs e) { + protected override void AcceptIfValid(object sender, EventArgs e) + { TabPage tabPage = null; - foreach (TabPage tabPage2 in TabPages) { + foreach (TabPage tabPage2 in TabPages) + { if (tabPage2 is ISettingsTabPage settingsTabPage && !settingsTabPage.Validate() && (tabPage == null || tabPage2 == _tabControl.SelectedTab)) + { tabPage = tabPage2; + } } if (tabPage == null) + { base.AcceptIfValid(sender, e); + } else + { _tabControl.SelectedTab = tabPage; + } } } } diff --git a/RdcMan/TemporaryServer.cs b/RdcMan/TemporaryServer.cs index 032ad69..523f792 100644 --- a/RdcMan/TemporaryServer.cs +++ b/RdcMan/TemporaryServer.cs @@ -1,14 +1,20 @@ using System.Windows.Forms; -namespace RdcMan { - public class TemporaryServer : Server { - protected TemporaryServer() { } +namespace RdcMan +{ + public class TemporaryServer : Server + { + protected TemporaryServer() + { + } - public static TemporaryServer CreateForQuickConnect() { + public static TemporaryServer CreateForQuickConnect() + { return new TemporaryServer(); } - public static TemporaryServer Create(ConnectToDialog dlg) { + public static TemporaryServer Create(ConnectToDialog dlg) + { TemporaryServer server = dlg.Server; dlg.UpdateSettings(); server.Properties.ServerName.Value = dlg.QuickConnectTabPage.ServerNameTextBox.Text; @@ -20,12 +26,15 @@ public static TemporaryServer Create(ConnectToDialog dlg) { return server; } - public override bool CanDropOnTarget(RdcTreeNode targetNode) { - if (FileGroup == null) { + public override bool CanDropOnTarget(RdcTreeNode targetNode) + { + if (FileGroup == null) + { GroupBase groupBase = (targetNode as GroupBase) ?? (targetNode.Parent as GroupBase); if (groupBase.DropBehavior() != DragDropEffects.Link) + { return groupBase.CanDropServers(); - + } return false; } return base.CanDropOnTarget(targetNode); diff --git a/RdcMan/ThrottledAction.cs b/RdcMan/ThrottledAction.cs index 1f42891..f550acf 100644 --- a/RdcMan/ThrottledAction.cs +++ b/RdcMan/ThrottledAction.cs @@ -2,8 +2,10 @@ using System.Collections.Generic; using System.Threading; -namespace RdcMan { - internal class ThrottledAction : IDisposable { +namespace RdcMan +{ + internal class ThrottledAction : IDisposable + { private const int Max = 3; private int _numActive; @@ -12,17 +14,18 @@ internal class ThrottledAction : IDisposable { private Semaphore _actionSemaphore; - private readonly List _servers; + private List _servers; private Action _preAction; - private readonly Action _action; + private Action _action; private int _delayInMilliseconds; - private readonly Action _postAction; + private Action _postAction; - public ThrottledAction(List servers, Action preAction, Action action, int delayInMilliseconds, Action postAction) { + public ThrottledAction(List servers, Action preAction, Action action, int delayInMilliseconds, Action postAction) + { _servers = servers; _preAction = preAction; _action = action; @@ -30,50 +33,64 @@ public ThrottledAction(List servers, Action preAction, Action 0) { + private void WaitForCompletion() + { + while (Thread.VolatileRead(ref _numActive) > 0) + { Thread.Sleep(_delayInMilliseconds); } } - protected virtual void Dispose(bool disposing) { - if (!_disposed) { - if (disposing && _actionSemaphore != null) { + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing && _actionSemaphore != null) + { _actionSemaphore.Close(); _actionSemaphore = null; } diff --git a/RdcMan/ThrottledOperation.cs b/RdcMan/ThrottledOperation.cs index cd80359..d724b42 100644 --- a/RdcMan/ThrottledOperation.cs +++ b/RdcMan/ThrottledOperation.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; -namespace RdcMan { - internal class ThrottledOperation : IDisposable { +namespace RdcMan +{ + internal class ThrottledOperation : IDisposable + { private HashSet _serversInScope; private object _serversInScopeLock = new object(); @@ -13,36 +15,46 @@ internal class ThrottledOperation : IDisposable { private bool _disposed; - public ThrottledOperation(List servers, IEnumerable completionStates, Action preAction, Action action, int delayInMilliseconds, Action postAction) { + public ThrottledOperation(List servers, IEnumerable completionStates, Action preAction, Action action, int delayInMilliseconds, Action postAction) + { ThrottledOperation throttledOperation = this; _serversInScope = new HashSet(); _completionStates = new HashSet(completionStates); - _throttledAction = new ThrottledAction(servers, delegate { + _throttledAction = new ThrottledAction(servers, delegate + { preAction(); Server.ConnectionStateChanged += throttledOperation.ConnectionStateChangeConnectHandler; - }, delegate (ServerBase server) { - lock (throttledOperation._serversInScopeLock) { + }, delegate(ServerBase server) + { + lock (throttledOperation._serversInScopeLock) + { throttledOperation._serversInScope.Add(server.ServerNode); } action(server); - }, delayInMilliseconds, delegate { + }, delayInMilliseconds, delegate + { Server.ConnectionStateChanged -= throttledOperation.ConnectionStateChangeConnectHandler; postAction(); }); } - ~ThrottledOperation() { + ~ThrottledOperation() + { Dispose(disposing: false); } - public void Dispose() { + public void Dispose() + { Dispose(disposing: true); GC.SuppressFinalize(this); } - protected virtual void Dispose(bool disposing) { - if (!_disposed) { - if (disposing && _throttledAction != null) { + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing && _throttledAction != null) + { _throttledAction.Dispose(); _throttledAction = null; } @@ -50,18 +62,24 @@ protected virtual void Dispose(bool disposing) { } } - public void Execute() { + public void Execute() + { _throttledAction.Execute(); } - private void ConnectionStateChangeConnectHandler(ConnectionStateChangedEventArgs args) { - if (_completionStates.Contains(args.State)) { + private void ConnectionStateChangeConnectHandler(ConnectionStateChangedEventArgs args) + { + if (_completionStates.Contains(args.State)) + { bool flag; - lock (_serversInScopeLock) { + lock (_serversInScopeLock) + { flag = _serversInScope.Remove(args.Server); } if (flag) + { _throttledAction.CompleteAction(); + } } } } diff --git a/RdcMan/ThumbnailLayout.cs b/RdcMan/ThumbnailLayout.cs index 6ee660c..cf6ccaa 100644 --- a/RdcMan/ThumbnailLayout.cs +++ b/RdcMan/ThumbnailLayout.cs @@ -3,10 +3,14 @@ using System.Drawing; using System.Windows.Forms; -namespace RdcMan { - internal class ThumbnailLayout : IDisposable, IEquatable { - private class LayoutComparer : IComparer { - public int Compare(ServerLabel label1, ServerLabel label2) { +namespace RdcMan +{ + internal class ThumbnailLayout : IDisposable, IEquatable + { + private class LayoutComparer : IComparer + { + public int Compare(ServerLabel label1, ServerLabel label2) + { Server server = label1.Server; Server server2 = label2.Server; server.InheritSettings(); @@ -15,15 +19,19 @@ public int Compare(ServerLabel label1, ServerLabel label2) { int value2 = server2.DisplaySettings.ThumbnailScale.Value; int num = value2 - value; if (num != 0) + { return num; - + } List path = label1.AssociatedNode.GetPath(); List path2 = label2.AssociatedNode.GetPath(); int num2 = Math.Min(path.Count, path2.Count); - for (int i = 0; i < num2; i++) { + for (int i = 0; i < num2; i++) + { num = path[i].Index - path2[i].Index; if (num != 0) + { return num; + } } return num; } @@ -49,8 +57,10 @@ public int Compare(ServerLabel label1, ServerLabel label2) { public int FocusedServerIndex { get; set; } - public int[] TabIndexToServerIndex { - get { + public int[] TabIndexToServerIndex + { + get + { EnsureTabIndex(); return _tabIndexToServerIndex; } @@ -62,29 +72,37 @@ public int[] TabIndexToServerIndex { public GroupBase Group { get; private set; } - public bool IsServerPositionComputed(int index) { + public bool IsServerPositionComputed(int index) + { return _isServerPositionComputed[index]; } - public ThumbnailLayout(GroupBase group) { + public ThumbnailLayout(GroupBase group) + { Group = group; } - ~ThumbnailLayout() { + ~ThumbnailLayout() + { Dispose(disposing: false); } - public void Dispose() { + public void Dispose() + { Dispose(disposing: true); GC.SuppressFinalize(this); } - protected virtual void Dispose(bool disposing) { + protected virtual void Dispose(bool disposing) + { if (_disposed) + { return; - - if (disposing) { - LabelArray.ForEach(delegate (ServerLabel l) { + } + if (disposing) + { + LabelArray.ForEach(delegate(ServerLabel l) + { l.Dispose(); }); LabelArray = null; @@ -92,19 +110,24 @@ protected virtual void Dispose(bool disposing) { _disposed = true; } - public override string ToString() { + public override string ToString() + { return "{0} ({1} )".InvariantFormat(Group.Text, NodeCount); } - public void Compute(int numAcross) { - using (Helpers.Timer("computing thumbnail layout")) { + public void Compute(int numAcross) + { + using (Helpers.Timer("computing thumbnail layout")) + { List list = CreateThumbnailList(); LabelArray = list.ToArray(); } if (NodeCount == 0) + { return; - - using (Helpers.Timer("sorting {0} thumbnails", NodeCount)) { + } + using (Helpers.Timer("sorting {0} thumbnails", NodeCount)) + { Array.Sort(LabelArray, new LayoutComparer()); } SetThumbnailIndex(); @@ -115,9 +138,11 @@ public void Compute(int numAcross) { List list3 = null; ServerLabel[] labelArray = LabelArray; int value; - foreach (ServerLabel serverLabel in labelArray) { + foreach (ServerLabel serverLabel in labelArray) + { value = serverLabel.Server.DisplaySettings.ThumbnailScale.Value; - if (list3 != null && num == value) { + if (list3 != null && num == value) + { list3.Add(serverLabel); continue; } @@ -132,43 +157,58 @@ public void Compute(int numAcross) { _thumbnailAbsoluteBounds = new Rectangle[_maxNodeIndex]; ServerTileX = new int[_maxNodeIndex]; ServerTileY = new int[_maxNodeIndex]; - using (Helpers.Timer("laying out {0} thumbnails", NodeCount)) { + using (Helpers.Timer("laying out {0} thumbnails", NodeCount)) + { int num2 = 0; int num3 = 0; - while (list2.Count > 0) { + while (list2.Count > 0) + { bool flag = false; int num4 = -1; - for (int j = 0; j < list2.Count; j++) { + for (int j = 0; j < list2.Count; j++) + { list3 = list2[j]; ServerLabel serverLabel2 = list3[0]; value = serverLabel2.Server.DisplaySettings.ThumbnailScale.Value; if (num4 != -1 && value > num4) + { break; - + } bool flag2 = false; - if (num2 == 0 || num2 + value <= numAcross) { + if (num2 == 0 || num2 + value <= numAcross) + { int num5 = Math.Min(value, numAcross); bool flag3 = true; - for (int k = 0; k < num5; k++) { - for (int l = 0; l < value; l++) { - if (ServerLayoutToIndex[num3 + l, num2 + k] != 0) { + for (int k = 0; k < num5; k++) + { + for (int l = 0; l < value; l++) + { + if (ServerLayoutToIndex[num3 + l, num2 + k] != 0) + { num4 = k; flag3 = false; break; } } if (!flag3) + { break; + } } if (flag3) + { flag2 = true; + } } if (!flag2) + { continue; - + } int thumbnailIndex = serverLabel2.ThumbnailIndex; - for (int m = 0; m < value; m++) { - for (int n = 0; n < value; n++) { + for (int m = 0; m < value; m++) + { + for (int n = 0; n < value; n++) + { ServerLayoutToIndex[num3 + n, num2 + m] = thumbnailIndex; } } @@ -178,16 +218,19 @@ public void Compute(int numAcross) { flag = true; list3.Remove(serverLabel2); if (list3.Count == 0) + { list2.Remove(list3); - + } num2 += value; - if (num2 >= numAcross) { + if (num2 >= numAcross) + { num2 = 0; num3++; } break; } - if (!flag && ++num2 >= numAcross) { + if (!flag && ++num2 >= numAcross) + { num2 = 0; num3++; } @@ -195,40 +238,50 @@ public void Compute(int numAcross) { } } - public void SetThumbnailIndex() { + public void SetThumbnailIndex() + { int num = 0; ServerLabel[] labelArray = LabelArray; - foreach (ServerLabel serverLabel in labelArray) { + foreach (ServerLabel serverLabel in labelArray) + { num = (serverLabel.ThumbnailIndex = num + 1); } } - public void SetThumbnailAbsoluteBounds(int serverIndex, int x, int y, int width, int height) { + public void SetThumbnailAbsoluteBounds(int serverIndex, int x, int y, int width, int height) + { _thumbnailAbsoluteBounds[serverIndex] = new Rectangle(x, y, width, height); _isServerPositionComputed[serverIndex] = true; } - public Rectangle GetThumbnailAbsoluteBounds(int serverIndex) { + public Rectangle GetThumbnailAbsoluteBounds(int serverIndex) + { return _thumbnailAbsoluteBounds[serverIndex]; } - public void EnsureTabIndex() { - if (_tabIndexToServerIndex != null) { + public void EnsureTabIndex() + { + if (_tabIndexToServerIndex != null) + { return; } int upperBound = ServerLayoutToIndex.GetUpperBound(1); int lowestTileY = LowestTileY; int num = 1; _tabIndexToServerIndex = new int[_maxNodeIndex]; - for (int i = 0; i <= lowestTileY; i++) { + for (int i = 0; i <= lowestTileY; i++) + { ServerLabel serverLabel; - for (int j = 0; j <= upperBound; j += serverLabel.Server.DisplaySettings.ThumbnailScale.Value) { + for (int j = 0; j <= upperBound; j += serverLabel.Server.DisplaySettings.ThumbnailScale.Value) + { int num2 = ServerLayoutToIndex[i, j]; if (num2 == 0) + { break; - + } serverLabel = LabelArray[num2 - 1]; - if (ServerTileY[num2] == i) { + if (ServerTileY[num2] == i) + { _tabIndexToServerIndex[num] = serverLabel.ThumbnailIndex; serverLabel.TabIndex = num++; } @@ -236,19 +289,26 @@ public void EnsureTabIndex() { } } - private List CreateThumbnailList() { + private List CreateThumbnailList() + { List labelList = new List(); HashSet set = new HashSet(); bool useActualNode = Group is VirtualGroup; - Group.VisitNodes(delegate (RdcTreeNode node) { + Group.VisitNodes(delegate(RdcTreeNode node) + { if (node is GroupBase groupBase) + { groupBase.InheritSettings(); - else { + } + else + { ServerBase serverBase = node as ServerBase; Server serverNode = serverBase.ServerNode; - if (!set.Contains(serverNode) && serverNode.Parent is GroupBase groupBase2) { + if (!set.Contains(serverNode) && serverNode.Parent is GroupBase groupBase2) + { groupBase2.InheritSettings(); - if (groupBase2.DisplaySettings.ShowDisconnectedThumbnails.Value || serverNode.IsConnected) { + if (groupBase2.DisplaySettings.ShowDisconnectedThumbnails.Value || serverNode.IsConnected) + { ServerLabel item = new ServerLabel(useActualNode ? serverBase : serverNode); labelList.Add(item); set.Add(serverNode); @@ -259,13 +319,18 @@ private List CreateThumbnailList() { return labelList; } - public bool Equals(ThumbnailLayout other) { + public bool Equals(ThumbnailLayout other) + { if (Group != other.Group || NodeCount != other.NodeCount) + { return false; - - for (int i = 0; i < NodeCount; i++) { + } + for (int i = 0; i < NodeCount; i++) + { if (LabelArray[i].AssociatedNode != other.LabelArray[i].AssociatedNode || ServerTileX[i] != other.ServerTileX[i] || ServerTileY[i] != other.ServerTileY[i]) + { return false; + } } return true; } diff --git a/RdcMan/ValueComboBox.cs b/RdcMan/ValueComboBox.cs index dc369b1..602bbff 100644 --- a/RdcMan/ValueComboBox.cs +++ b/RdcMan/ValueComboBox.cs @@ -2,113 +2,153 @@ using System.Collections.Generic; using System.Windows.Forms; -namespace RdcMan { - public class ValueComboBox : ComboBox, ISettingControl { - private class ComboBoxItem { +namespace RdcMan +{ + public class ValueComboBox : ComboBox, ISettingControl + { + private class ComboBoxItem + { public string Name; public T Value; - public override string ToString() { + public override string ToString() + { return Name; } } public Setting Setting; - public new TValue SelectedValue { - get { + public new TValue SelectedValue + { + get + { if (base.SelectedItem == null) + { return default(TValue); - + } return (base.SelectedItem as ComboBoxItem).Value; } - set { + set + { int num = FindItem(value); if (num != -1) + { SelectedIndex = num; + } } } public int ItemCount => base.Items.Count; - public new ObjectCollection Items { - set { + public new ObjectCollection Items + { + set + { throw new InvalidOperationException(); } } - public new string Text { - get { + public new string Text + { + get + { throw new InvalidOperationException(); } } public ValueComboBox(Setting setting, IEnumerable values, Func toString) - : this(values, toString) { + : this(values, toString) + { Setting = setting; } - public ValueComboBox(IEnumerable values, Func toString) { + public ValueComboBox(IEnumerable values, Func toString) + { base.DropDownStyle = ComboBoxStyle.DropDownList; if (values != null) + { AddItems(values, toString); + } } - public void AddItems(IEnumerable values, Func toString) { - values.ForEach(delegate (TValue v) { + public void AddItems(IEnumerable values, Func toString) + { + values.ForEach(delegate(TValue v) + { AddItem(toString(v), v); }); } - public void AddItem(string name, TValue value) { - base.Items.Add(new ComboBoxItem { + public void AddItem(string name, TValue value) + { + base.Items.Add(new ComboBoxItem + { Name = name, Value = value }); } - public void ClearItems() { + public void ClearItems() + { base.Items.Clear(); } - public void ReplaceItem(string name, TValue newValue) { + public void ReplaceItem(string name, TValue newValue) + { int num = FindItem(name); - if (num != -1) { + if (num != -1) + { ComboBoxItem comboBoxItem = base.Items[num] as ComboBoxItem; comboBoxItem.Value = newValue; } } - public int FindItem(TValue value) { - for (int i = 0; i < base.Items.Count; i++) { + public int FindItem(TValue value) + { + for (int i = 0; i < base.Items.Count; i++) + { ComboBoxItem comboBoxItem = base.Items[i] as ComboBoxItem; if (object.Equals(comboBoxItem.Value, value)) + { return i; + } } return -1; } - public int FindItem(string name) { - for (int i = 0; i < base.Items.Count; i++) { + public int FindItem(string name) + { + for (int i = 0; i < base.Items.Count; i++) + { ComboBoxItem comboBoxItem = base.Items[i] as ComboBoxItem; if (comboBoxItem.Name.Equals(name, StringComparison.OrdinalIgnoreCase)) + { return i; + } } return -1; } - void ISettingControl.UpdateControl() { + void ISettingControl.UpdateControl() + { if (Setting != null) + { SelectedValue = Setting.Value; + } } - void ISettingControl.UpdateSetting() { + void ISettingControl.UpdateSetting() + { if (Setting != null) + { Setting.Value = SelectedValue; + } } - string ISettingControl.Validate() { + string ISettingControl.Validate() + { return null; } } diff --git a/RdcMan/VirtualGroup.cs b/RdcMan/VirtualGroup.cs index ab3ef1d..35c44f2 100644 --- a/RdcMan/VirtualGroup.cs +++ b/RdcMan/VirtualGroup.cs @@ -1,25 +1,32 @@ -namespace RdcMan { - internal abstract class VirtualGroup : GroupBase { +namespace RdcMan +{ + internal abstract class VirtualGroup : GroupBase + { protected IServerRefFactory ServerRefFactory => this as IServerRefFactory; - protected VirtualGroup() { + protected VirtualGroup() + { ChangeImageIndex(ImageConstants.Group); } - protected override void InitSettings() { + protected override void InitSettings() + { base.Properties = new GroupSettings(); base.InitSettings(); } - public sealed override bool CanAddServers() { + public sealed override bool CanAddServers() + { return false; } - public sealed override bool CanAddGroups() { + public sealed override bool CanAddGroups() + { return false; } - public sealed override bool CanDropGroups() { + public sealed override bool CanDropGroups() + { return false; } } diff --git a/RdcMan/XmlSetting.cs b/RdcMan/XmlSetting.cs index e73b65b..f3e1b33 100644 --- a/RdcMan/XmlSetting.cs +++ b/RdcMan/XmlSetting.cs @@ -1,14 +1,18 @@ using System.Xml; -namespace RdcMan { - public class XmlSetting : Setting { +namespace RdcMan +{ + public class XmlSetting : Setting + { public XmlSetting(object o) : base(o) { } - public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) { + public override void ReadXml(XmlNode xmlNode, RdcTreeNode node) + { base.Value = xmlNode; } - public override void WriteXml(XmlTextWriter tw, RdcTreeNode node) { + public override void WriteXml(XmlTextWriter tw, RdcTreeNode node) + { base.Value.WriteTo(tw); } } diff --git a/Resources/app.ico b/Resources/app.ico index 8c480aa..db79f59 100644 Binary files a/Resources/app.ico and b/Resources/app.ico differ diff --git a/Resources/connected.ico b/Resources/connected.ico index a298379..5f5b9a6 100644 Binary files a/Resources/connected.ico and b/Resources/connected.ico differ diff --git a/Resources/connectedselected.ico b/Resources/connectedselected.ico index b589b3c..c1e3ddb 100644 Binary files a/Resources/connectedselected.ico and b/Resources/connectedselected.ico differ diff --git a/Resources/connecting.ico b/Resources/connecting.ico index 22124eb..e42f094 100644 Binary files a/Resources/connecting.ico and b/Resources/connecting.ico differ diff --git a/Resources/connectingselected.ico b/Resources/connectingselected.ico index 97058a3..f111568 100644 Binary files a/Resources/connectingselected.ico and b/Resources/connectingselected.ico differ diff --git a/Resources/default.ico b/Resources/default.ico new file mode 100644 index 0000000..e82028b Binary files /dev/null and b/Resources/default.ico differ diff --git a/Resources/disconnected.ico b/Resources/disconnected.ico index 23745fb..5aaa4c4 100644 Binary files a/Resources/disconnected.ico and b/Resources/disconnected.ico differ diff --git a/Resources/group.ico b/Resources/group.ico index 6f4261d..98d360f 100644 Binary files a/Resources/group.ico and b/Resources/group.ico differ diff --git a/Resources/smartgroup.ico b/Resources/smartgroup.ico index c452c68..c568230 100644 Binary files a/Resources/smartgroup.ico and b/Resources/smartgroup.ico differ diff --git a/Win32/WinTrust.cs b/Win32/WinTrust.cs index e17bd3a..12d4e1c 100644 --- a/Win32/WinTrust.cs +++ b/Win32/WinTrust.cs @@ -12,7 +12,7 @@ public sealed class WinTrust { public static bool VerifyEmbeddedSignature(string fileName) { WinTrustData pWVTData = new WinTrustData(fileName); - WinVerifyTrustResult winVerifyTrustResult = WinVerifyTrust(pgActionID: new Guid(WINTRUST_ACTION_GENERIC_VERIFY_V2), hwnd: INVALID_HANDLE_VALUE, pWVTData: pWVTData); + WinVerifyTrustResult winVerifyTrustResult = WinVerifyTrust(pgActionID: new Guid("{00AAC56B-CD44-11d0-8CC2-00C04FC295EE}"), hwnd: INVALID_HANDLE_VALUE, pWVTData: pWVTData); return winVerifyTrustResult == WinVerifyTrustResult.Success; } diff --git a/Win32/WinTrustData.cs b/Win32/WinTrustData.cs index 7694a32..74e5264 100644 --- a/Win32/WinTrustData.cs +++ b/Win32/WinTrustData.cs @@ -31,7 +31,8 @@ public class WinTrustData { public WinTrustData(string _fileName) { if (Environment.OSVersion.Version.Major > 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor > 1) - || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor == 1 && !string.IsNullOrEmpty(Environment.OSVersion.ServicePack))) { + || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor == 1 && !string.IsNullOrEmpty(Environment.OSVersion.ServicePack)) + ) { ProvFlags |= WinTrustDataProvFlags.DisableMD2andMD4; } WinTrustFileInfo structure = new WinTrustFileInfo(_fileName); diff --git a/app.config b/app.config index 99a6018..821f87a 100644 --- a/app.config +++ b/app.config @@ -1,24 +1,24 @@ - + -
+
- + - - - - - - - + + + + + + + - - - + + + \ No newline at end of file