From 0b7ee51caa6f07a27bb9bcae3222ba010a6fba3f Mon Sep 17 00:00:00 2001 From: kpreisser Date: Sat, 30 Sep 2017 18:04:51 +0200 Subject: [PATCH] Fix code style. --- .../Core/Actions/CompoundAction.cs | 28 +- .../Core/Actions/LoopAction.cs | 10 +- .../Core/Environment/IScreenshotContent.cs | 8 +- .../Core/Environment/WindowParameters.cs | 4 +- TTMouseclickSimulator/Core/Simulator.cs | 18 +- .../DoodleInteraction/DoodlePanelAction.cs | 4 +- .../Fishing/AbstractFishingRodAction.cs | 20 +- .../Actions/Fishing/AutomaticFishingAction.cs | 12 +- .../Actions/Fishing/QuitFishingAction.cs | 2 +- .../Actions/Fishing/SellFishAction.cs | 2 +- .../Actions/Fishing/StraightFishingAction.cs | 2 +- .../Actions/Gardening/PlantFlowerAction.cs | 8 +- .../Actions/Keyboard/PressKeyAction.cs | 8 +- .../Actions/Keyboard/WriteTextAction.cs | 14 +- .../ToontownRewritten/Actions/PauseAction.cs | 4 +- .../Actions/Speedchat/SpeedchatAction.cs | 12 +- TTMouseclickSimulator/MainWindow.xaml.cs | 148 +++++------ .../Project/SimulatorProject.cs | 2 +- .../Project/XmlProjectDeserializer.cs | 18 +- TTMouseclickSimulator/Utils/TaskDialog.cs | 248 +++++++++--------- 20 files changed, 286 insertions(+), 286 deletions(-) diff --git a/TTMouseclickSimulator/Core/Actions/CompoundAction.cs b/TTMouseclickSimulator/Core/Actions/CompoundAction.cs index 6ef8e08..d1cb322 100644 --- a/TTMouseclickSimulator/Core/Actions/CompoundAction.cs +++ b/TTMouseclickSimulator/Core/Actions/CompoundAction.cs @@ -24,7 +24,7 @@ public class CompoundAction : AbstractActionContainer private readonly Random rng = new Random(); - public override sealed IList SubActions => actionList; + public override sealed IList SubActions => this.actionList; /// @@ -74,21 +74,21 @@ public override sealed async Task RunAsync(IInteractionProvider provider) int[] randomOrder = null; Func getNextActionIndex; - if (type == CompoundActionType.Sequential) + if (this.type == CompoundActionType.Sequential) getNextActionIndex = () => - (!loop && currentIdx + 1 == actionList.Count) ? -1 - : currentIdx = (currentIdx + 1) % actionList.Count; - else if (type == CompoundActionType.RandomIndex) - getNextActionIndex = () => rng.Next(actionList.Count); + (!this.loop && currentIdx + 1 == this.actionList.Count) ? -1 + : currentIdx = (currentIdx + 1) % this.actionList.Count; + else if (this.type == CompoundActionType.RandomIndex) + getNextActionIndex = () => this.rng.Next(this.actionList.Count); else { - randomOrder = new int[actionList.Count]; + randomOrder = new int[this.actionList.Count]; getNextActionIndex = () => { - if (!loop && currentIdx + 1 == actionList.Count) + if (!this.loop && currentIdx + 1 == this.actionList.Count) return -1; - currentIdx = (currentIdx + 1) % actionList.Count; + currentIdx = (currentIdx + 1) % this.actionList.Count; if (currentIdx == 0) { // Generate a new order array. @@ -96,7 +96,7 @@ public override sealed async Task RunAsync(IInteractionProvider provider) randomOrder[i] = i; for (int i = 0; i < randomOrder.Length; i++) { - int rIdx = rng.Next(randomOrder.Length - i); + int rIdx = this.rng.Next(randomOrder.Length - i); int tmp = randomOrder[i]; randomOrder[i] = randomOrder[i + rIdx]; randomOrder[i + rIdx] = tmp; @@ -125,7 +125,7 @@ public override sealed async Task RunAsync(IInteractionProvider provider) OnSubActionStartedOrStopped(nextIdx); try { - IAction action = actionList[nextIdx]; + var action = this.actionList[nextIdx]; await action.RunAsync(provider); } finally @@ -134,7 +134,7 @@ public override sealed async Task RunAsync(IInteractionProvider provider) } // After running an action, wait. - int waitInterval = rng.Next(minimumPauseDuration, maximumPauseDuration); + int waitInterval = this.rng.Next(this.minimumPauseDuration, this.maximumPauseDuration); OnActionInformationUpdated($"Pausing {waitInterval} ms"); await provider.WaitAsync(waitInterval); @@ -150,8 +150,8 @@ public override sealed async Task RunAsync(IInteractionProvider provider) } - public override string ToString() => $"Compound – Type: {type}, " - + $"MinPause: {minimumPauseDuration}, MaxPause: {maximumPauseDuration}, Loop: {loop}"; + public override string ToString() => $"Compound – Type: {this.type}, " + + $"MinPause: {this.minimumPauseDuration}, MaxPause: {this.maximumPauseDuration}, Loop: {this.loop}"; public enum CompoundActionType : int diff --git a/TTMouseclickSimulator/Core/Actions/LoopAction.cs b/TTMouseclickSimulator/Core/Actions/LoopAction.cs index 4b2095b..5b734ab 100644 --- a/TTMouseclickSimulator/Core/Actions/LoopAction.cs +++ b/TTMouseclickSimulator/Core/Actions/LoopAction.cs @@ -28,22 +28,22 @@ public LoopAction(IAction action, int? count = null) this.count = count; } - public override IList SubActions => new List() { action }; + public override IList SubActions => new List() { this.action }; public override sealed async Task RunAsync(IInteractionProvider provider) { OnSubActionStartedOrStopped(0); try { - for (int i = 0; !count.HasValue || i < count.Value; i++) + for (int i = 0; !this.count.HasValue || i < this.count.Value; i++) { for (;;) { try { provider.EnsureNotCanceled(); - OnActionInformationUpdated($"Iteration {i + 1}/{count?.ToString() ?? "∞"}"); - await action.RunAsync(provider); + OnActionInformationUpdated($"Iteration {i + 1}/{this.count?.ToString() ?? "∞"}"); + await this.action.RunAsync(provider); } catch (Exception ex) when (!(ex is SimulatorCanceledException)) { @@ -61,6 +61,6 @@ public override sealed async Task RunAsync(IInteractionProvider provider) } - public override string ToString() => $"Loop – Count: {count?.ToString() ?? "∞"}"; + public override string ToString() => $"Loop – Count: {this.count?.ToString() ?? "∞"}"; } } diff --git a/TTMouseclickSimulator/Core/Environment/IScreenshotContent.cs b/TTMouseclickSimulator/Core/Environment/IScreenshotContent.cs index 1ef8f61..ad5b6fb 100644 --- a/TTMouseclickSimulator/Core/Environment/IScreenshotContent.cs +++ b/TTMouseclickSimulator/Core/Environment/IScreenshotContent.cs @@ -29,16 +29,16 @@ public byte GetValueFromIndex(int index) { switch (index) { case 0: - return r; + return this.r; case 1: - return g; + return this.g; case 2: - return b; + return this.b; default: throw new ArgumentOutOfRangeException(nameof(index)); } } - public System.Windows.Media.Color ToColor() => System.Windows.Media.Color.FromArgb(255, r, g, b); + public System.Windows.Media.Color ToColor() => System.Windows.Media.Color.FromArgb(255, this.r, this.g, this.b); } } diff --git a/TTMouseclickSimulator/Core/Environment/WindowParameters.cs b/TTMouseclickSimulator/Core/Environment/WindowParameters.cs index 253cb53..63c95de 100644 --- a/TTMouseclickSimulator/Core/Environment/WindowParameters.cs +++ b/TTMouseclickSimulator/Core/Environment/WindowParameters.cs @@ -17,7 +17,7 @@ public struct WindowPosition public Size Size { get; set; } - public Coordinates RelativeToAbsoluteCoordinates(Coordinates c) => Coordinates.Add(c); + public Coordinates RelativeToAbsoluteCoordinates(Coordinates c) => this.Coordinates.Add(c); } public struct Coordinates @@ -31,7 +31,7 @@ public Coordinates(int x, int y) this.Y = y; } - public Coordinates Add(Coordinates c) => new Coordinates(X + c.X, Y + c.Y); + public Coordinates Add(Coordinates c) => new Coordinates(this.X + c.X, this.Y + c.Y); } public struct Size diff --git a/TTMouseclickSimulator/Core/Simulator.cs b/TTMouseclickSimulator/Core/Simulator.cs index bd240f5..b1c3972 100644 --- a/TTMouseclickSimulator/Core/Simulator.cs +++ b/TTMouseclickSimulator/Core/Simulator.cs @@ -38,7 +38,7 @@ public Simulator(IntPtr windowHandle, IAction mainAction, AbstractWindowsEnviron this.mainAction = mainAction; this.environmentInterface = environmentInterface; - provider = new StandardInteractionProvider(this, windowHandle, environmentInterface, out cancelCallback); + this.provider = new StandardInteractionProvider(this, windowHandle, environmentInterface, out this.cancelCallback); } /// @@ -47,31 +47,31 @@ public Simulator(IntPtr windowHandle, IAction mainAction, AbstractWindowsEnviron /// public async Task RunAsync() { - if (canceled) + if (this.canceled) throw new InvalidOperationException("The simulator has already been canceled."); try { - using (provider) + using (this.provider) { OnSimulatorStarted(); // InitializeAsync() does not need to be in the try block because it has its own. - await provider.InitializeAsync(); + await this.provider.InitializeAsync(); for (;;) { try { // Run the action. - await mainAction.RunAsync(provider); + await this.mainAction.RunAsync(this.provider); // Normally the main action would be a CompoundAction that never returns, but // it is possible that the action will return normally. } catch (Exception ex) when (!(ex is SimulatorCanceledException)) { - await provider.CheckRetryForExceptionAsync(ExceptionDispatchInfo.Capture(ex)); + await this.provider.CheckRetryForExceptionAsync(ExceptionDispatchInfo.Capture(ex)); continue; } break; @@ -81,7 +81,7 @@ public async Task RunAsync() } finally { - canceled = true; + this.canceled = true; OnSimulatorStopped(); } } @@ -93,8 +93,8 @@ public async Task RunAsync() /// public void Cancel() { - canceled = true; - cancelCallback(); + this.canceled = true; + this.cancelCallback(); } diff --git a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/DoodleInteraction/DoodlePanelAction.cs b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/DoodleInteraction/DoodlePanelAction.cs index 5ba82da..812192b 100644 --- a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/DoodleInteraction/DoodlePanelAction.cs +++ b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/DoodleInteraction/DoodlePanelAction.cs @@ -20,12 +20,12 @@ public DoodlePanelAction(DoodlePanelButton button) public override async Task RunAsync(IInteractionProvider provider) { - Coordinates c = new Coordinates(1397, 206 + (int)button * 49); + var c = new Coordinates(1397, 206 + (int)this.button * 49); await MouseHelpers.DoSimpleMouseClickAsync(provider, c, VerticalScaleAlignment.Right); } - public override string ToString() => $"Doodle Panel – Button: {button}"; + public override string ToString() => $"Doodle Panel – Button: {this.button}"; public enum DoodlePanelButton : int diff --git a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/AbstractFishingRodAction.cs b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/AbstractFishingRodAction.cs index 3fa535f..198fb7c 100644 --- a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/AbstractFishingRodAction.cs +++ b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/AbstractFishingRodAction.cs @@ -58,18 +58,18 @@ public override sealed async Task RunAsync(IInteractionProvider provider) // Then, wait until we find a window displaying the caught fish // or the specified number of seconds has passed. OnActionInformationUpdated("Waiting for the fish result dialog…"); - Stopwatch sw = new Stopwatch(); + var sw = new Stopwatch(); sw.Start(); bool found = false; - while (!found && sw.ElapsedMilliseconds <= WaitingForFishResultDialogTime) + while (!found && sw.ElapsedMilliseconds <= this.WaitingForFishResultDialogTime) { await provider.WaitAsync(500); // Get a current screenshot. var screenshot = provider.GetCurrentWindowScreenshot(); - foreach (Coordinates c in fishResultDialogCoordinates) + foreach (var c in fishResultDialogCoordinates) { var cc = screenshot.WindowPosition.ScaleCoordinates( c, MouseHelpers.ReferenceWindowSize); @@ -93,7 +93,7 @@ public override sealed async Task RunAsync(IInteractionProvider provider) /// protected async Task StartCastFishingRodAsync(IInteractionProvider provider) { - Coordinates coords = new Coordinates(800, 846); + var coords = new Coordinates(800, 846); var pos = provider.GetCurrentWindowPosition(); coords = pos.ScaleCoordinates(coords, MouseHelpers.ReferenceWindowSize); @@ -168,11 +168,11 @@ public byte GetValueFromIndex(int index) switch (index) { case 0: - return ToleranceR; + return this.ToleranceR; case 1: - return ToleranceG; + return this.ToleranceG; case 2: - return ToleranceB; + return this.ToleranceB; default: throw new ArgumentOutOfRangeException(nameof(index)); } @@ -180,9 +180,9 @@ public byte GetValueFromIndex(int index) public Tolerance(byte toleranceR, byte toleranceG, byte toleranceB) { - ToleranceR = toleranceR; - ToleranceG = toleranceG; - ToleranceB = toleranceB; + this.ToleranceR = toleranceR; + this.ToleranceG = toleranceG; + this.ToleranceB = toleranceB; } public Tolerance(byte tolerance) diff --git a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/AutomaticFishingAction.cs b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/AutomaticFishingAction.cs index 231cde3..a0d4419 100644 --- a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/AutomaticFishingAction.cs +++ b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/AutomaticFishingAction.cs @@ -13,7 +13,7 @@ public class AutomaticFishingAction : AbstractFishingRodAction public AutomaticFishingAction(int[] scan1, int[] scan2, byte[] bubbleColorRgb, byte[] toleranceRgb) { - spotData = new FishingSpotData( + this.spotData = new FishingSpotData( new Coordinates(scan1[0], scan1[1]), new Coordinates(scan2[0], scan2[1]), new ScreenshotColor(bubbleColorRgb[0], bubbleColorRgb[1], bubbleColorRgb[2]), @@ -43,15 +43,15 @@ protected override sealed async Task FinishCastFishingRodAsync(IInteractionProvi // TODO: The fish bubble detection should be changed so that it does not scan // for a specific color, but instead checks that for a point if the color is // darker than the neighbor pixels (in some distance). - for (int y = spotData.Scan1.Y; y <= spotData.Scan2.Y && !newCoords.HasValue; y += scanStep) + for (int y = this.spotData.Scan1.Y; y <= this.spotData.Scan2.Y && !newCoords.HasValue; y += scanStep) { - for (int x = spotData.Scan1.X; x <= spotData.Scan2.X; x += scanStep) + for (int x = this.spotData.Scan1.X; x <= this.spotData.Scan2.X; x += scanStep) { var c = new Coordinates(x, y); c = screenshot.WindowPosition.ScaleCoordinates(c, MouseHelpers.ReferenceWindowSize); - if (CompareColor(spotData.BubbleColor, screenshot.GetPixel(c), - spotData.Tolerance)) + if (CompareColor(this.spotData.BubbleColor, screenshot.GetPixel(c), + this.spotData.Tolerance)) { newCoords = new Coordinates(x + 20, y + 20); var scaledCoords = screenshot.WindowPosition.ScaleCoordinates( @@ -132,6 +132,6 @@ protected override sealed async Task FinishCastFishingRodAsync(IInteractionProvi public override string ToString() => $"Automatic Fishing – " - + $"Color: [{spotData.BubbleColor.r}, {spotData.BubbleColor.g}, {spotData.BubbleColor.b}]"; + + $"Color: [{this.spotData.BubbleColor.r}, {this.spotData.BubbleColor.g}, {this.spotData.BubbleColor.b}]"; } } diff --git a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/QuitFishingAction.cs b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/QuitFishingAction.cs index 17ee7b2..bf12454 100644 --- a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/QuitFishingAction.cs +++ b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/QuitFishingAction.cs @@ -8,7 +8,7 @@ public class QuitFishingAction : AbstractAction { public override sealed async Task RunAsync(IInteractionProvider provider) { - Coordinates c = new Coordinates(1503, 1086); + var c = new Coordinates(1503, 1086); await MouseHelpers.DoSimpleMouseClickAsync(provider, c); } diff --git a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/SellFishAction.cs b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/SellFishAction.cs index 64d828b..23def6e 100644 --- a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/SellFishAction.cs +++ b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/SellFishAction.cs @@ -8,7 +8,7 @@ public class SellFishAction : AbstractAction { public override sealed async Task RunAsync(IInteractionProvider provider) { - Coordinates c = new Coordinates(1159, 911); + var c = new Coordinates(1159, 911); await MouseHelpers.DoSimpleMouseClickAsync(provider, c); } diff --git a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/StraightFishingAction.cs b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/StraightFishingAction.cs index 225eeb6..6c2b350 100644 --- a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/StraightFishingAction.cs +++ b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Fishing/StraightFishingAction.cs @@ -10,7 +10,7 @@ public class StraightFishingAction : AbstractFishingRodAction protected override sealed async Task FinishCastFishingRodAsync(IInteractionProvider provider) { // Simply cast the fishing rod straight, without checking for bubbles. - Coordinates coords = new Coordinates(800, 1009); + var coords = new Coordinates(800, 1009); var pos = provider.GetCurrentWindowPosition(); coords = pos.ScaleCoordinates(coords, MouseHelpers.ReferenceWindowSize); diff --git a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Gardening/PlantFlowerAction.cs b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Gardening/PlantFlowerAction.cs index 77ad23b..52d6ac8 100644 --- a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Gardening/PlantFlowerAction.cs +++ b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Gardening/PlantFlowerAction.cs @@ -41,7 +41,7 @@ public override sealed async Task RunAsync(IInteractionProvider provider) await provider.WaitAsync(200); // Click on the jellybean fields. - foreach (int jellybean in jellybeanCombination) + foreach (int jellybean in this.jellybeanCombination) { var c = new Coordinates((int)Math.Round(560 + jellybean * 60.5), 514); await MouseHelpers.DoSimpleMouseClickAsync(provider, c, @@ -56,12 +56,12 @@ await MouseHelpers.DoSimpleMouseClickAsync(provider, c, public override string ToString() { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < jellybeanCombination.Length; i++) + var sb = new StringBuilder(); + for (int i = 0; i < this.jellybeanCombination.Length; i++) { if (i > 0) sb.Append(", "); - sb.Append(jellybeanColors[jellybeanCombination[i]]); + sb.Append(jellybeanColors[this.jellybeanCombination[i]]); } return $"Plant Flower – JellyBeans: {sb.ToString()}"; diff --git a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Keyboard/PressKeyAction.cs b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Keyboard/PressKeyAction.cs index 1ccf0cc..1202b44 100644 --- a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Keyboard/PressKeyAction.cs +++ b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Keyboard/PressKeyAction.cs @@ -22,13 +22,13 @@ public PressKeyAction(AbstractWindowsEnvironment.VirtualKeyShort key, int durati public override sealed async Task RunAsync(IInteractionProvider provider) { - provider.PressKey(key); + provider.PressKey(this.key); // Use a accurate timer for measuring the time after we need to release the key. - await provider.WaitAsync(duration, true); - provider.ReleaseKey(key); + await provider.WaitAsync(this.duration, true); + provider.ReleaseKey(this.key); } - public override string ToString() => $"Press Key – Key: {key}, Duration: {duration}"; + public override string ToString() => $"Press Key – Key: {this.key}, Duration: {this.duration}"; } } diff --git a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Keyboard/WriteTextAction.cs b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Keyboard/WriteTextAction.cs index f9b8c80..70fd2eb 100644 --- a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Keyboard/WriteTextAction.cs +++ b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Keyboard/WriteTextAction.cs @@ -33,14 +33,14 @@ public WriteTextAction(string text, int? pauseDuration = null) public override sealed async Task RunAsync(IInteractionProvider provider) { // write the text and presses enter. - if (!pauseDuration.HasValue) - provider.WriteText(text); + if (!this.pauseDuration.HasValue) + provider.WriteText(this.text); else { - for (int i = 0; i < text.Length; i++) + for (int i = 0; i < this.text.Length; i++) { - provider.WriteText(text[i].ToString()); - await provider.WaitAsync(pauseDuration.Value); + provider.WriteText(this.text[i].ToString()); + await provider.WaitAsync(this.pauseDuration.Value); } } @@ -52,7 +52,7 @@ public override sealed async Task RunAsync(IInteractionProvider provider) } - public override string ToString() => $"Write Text – Text: \"{text}\"" - + (pauseDuration.HasValue ? "" : $", Pause Duration: {pauseDuration}"); + public override string ToString() => $"Write Text – Text: \"{this.text}\"" + + (this.pauseDuration.HasValue ? "" : $", Pause Duration: {this.pauseDuration}"); } } diff --git a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/PauseAction.cs b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/PauseAction.cs index 30dc350..e8386c1 100644 --- a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/PauseAction.cs +++ b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/PauseAction.cs @@ -17,9 +17,9 @@ public PauseAction(int duration) } public override sealed async Task RunAsync(IInteractionProvider provider) => - await provider.WaitAsync(duration); + await provider.WaitAsync(this.duration); - public override string ToString() => $"Pause – Duration: {duration}"; + public override string ToString() => $"Pause – Duration: {this.duration}"; } } diff --git a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Speedchat/SpeedchatAction.cs b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Speedchat/SpeedchatAction.cs index 10dfc07..2a05054 100644 --- a/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Speedchat/SpeedchatAction.cs +++ b/TTMouseclickSimulator/Core/ToontownRewritten/Actions/Speedchat/SpeedchatAction.cs @@ -32,15 +32,15 @@ public SpeedchatAction(params int[] menuItems) public override sealed async Task RunAsync(IInteractionProvider provider) { // Click on the Speedchat Icon. - Coordinates c = new Coordinates(122, 40); + var c = new Coordinates(122, 40); await MouseHelpers.DoSimpleMouseClickAsync(provider, c, VerticalScaleAlignment.Left, 100); int currentYNumber = 0; - for (int i = 0; i < menuItems.Length; i++) + for (int i = 0; i < this.menuItems.Length; i++) { await provider.WaitAsync(300); - currentYNumber += menuItems[i]; + currentYNumber += this.menuItems[i]; c = new Coordinates(xWidths[i], (40 + currentYNumber * 38)); await MouseHelpers.DoSimpleMouseClickAsync(provider, c, VerticalScaleAlignment.Left, 100); } @@ -49,12 +49,12 @@ public override sealed async Task RunAsync(IInteractionProvider provider) public override string ToString() { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < menuItems.Length; i++) + var sb = new StringBuilder(); + for (int i = 0; i < this.menuItems.Length; i++) { if (i > 0) sb.Append(", "); - sb.Append(menuItems[i]); + sb.Append(this.menuItems[i]); } return $"Speedchat – Items: [{sb.ToString()}]"; } diff --git a/TTMouseclickSimulator/MainWindow.xaml.cs b/TTMouseclickSimulator/MainWindow.xaml.cs index b3a5673..14e2694 100644 --- a/TTMouseclickSimulator/MainWindow.xaml.cs +++ b/TTMouseclickSimulator/MainWindow.xaml.cs @@ -52,19 +52,19 @@ public MainWindow() { InitializeComponent(); - lblAppName.Content = AppName; - Title = AppName; + this.lblAppName.Content = AppName; + this.Title = AppName; - openFileDialog = new Microsoft.Win32.OpenFileDialog(); - openFileDialog.DefaultExt = ProjectFileExtension; - openFileDialog.Filter = "XML Simulator Project|*" + ProjectFileExtension; + this.openFileDialog = new Microsoft.Win32.OpenFileDialog(); + this.openFileDialog.DefaultExt = ProjectFileExtension; + this.openFileDialog.Filter = "XML Simulator Project|*" + ProjectFileExtension; // Set the initial directory to the executable path or the "SampleProjects" folder if it exists. string exeDirectory = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); string sampleProjectsPath = System.IO.Path.Combine(exeDirectory, SampleProjectsFolderName); if (Directory.Exists(sampleProjectsPath)) - openFileDialog.InitialDirectory = sampleProjectsPath; + this.openFileDialog.InitialDirectory = sampleProjectsPath; else - openFileDialog.InitialDirectory = exeDirectory; + this.openFileDialog.InitialDirectory = exeDirectory; RefreshProjectControls(); } @@ -78,30 +78,30 @@ private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs { // If the simulator is currently running, don't close the window but stop the // simulator and wait until it is finished. - if (simulator != null) + if (this.simulator != null) { e.Cancel = true; Hide(); - closeWindowAfterStop = true; - simulator.Cancel(); + this.closeWindowAfterStop = true; + this.simulator.Cancel(); } } private async Task RunSimulatorAsync() { - btnStart.IsEnabled = false; - btnStop.IsEnabled = true; - btnLoad.IsEnabled = false; - if (quickActionButtons != null) - foreach (var bt in quickActionButtons) + this.btnStart.IsEnabled = false; + this.btnStop.IsEnabled = true; + this.btnLoad.IsEnabled = false; + if (this.quickActionButtons != null) + foreach (var bt in this.quickActionButtons) bt.IsEnabled = false; // Run the simulator in another task so it is not executed in the GUI thread. // However, we then await that new task so we are notified when it is finished. - Exception runException = null; - simulatorStartAction?.Invoke(); + var runException = null as Exception; + this.simulatorStartAction?.Invoke(); await Task.Run(async () => { try @@ -111,9 +111,9 @@ await Task.Run(async () => var process = environment.FindProcess(); var mainWindowHandle = environment.FindMainWindowHandleOfProcess(process); - Simulator sim = simulator = new Simulator(mainWindowHandle, currentQuickAction != null ? currentQuickAction.Action : - project.Configuration.MainAction, environment); - sim.AsyncRetryHandler = async (ex) => !closeWindowAfterStop && await HandleSimulatorRetryAsync(sim, ex); + var sim = this.simulator = new Simulator(mainWindowHandle, this.currentQuickAction != null ? this.currentQuickAction.Action : + this.project.Configuration.MainAction, environment); + sim.AsyncRetryHandler = async (ex) => !this.closeWindowAfterStop && await HandleSimulatorRetryAsync(sim, ex); await sim.RunAsync(); } @@ -122,12 +122,12 @@ await Task.Run(async () => runException = ex; } }); - simulatorStopAction?.Invoke(); + this.simulatorStopAction?.Invoke(); // Don't show a messagebox if we need to close the window. - if (!closeWindowAfterStop && runException != null && !(runException is SimulatorCanceledException)) + if (!this.closeWindowAfterStop && runException != null && !(runException is SimulatorCanceledException)) { - TaskDialog dialog = new TaskDialog() + var dialog = new TaskDialog() { Title = AppName, MainInstruction = "Simulator stopped!", @@ -147,11 +147,11 @@ private async Task HandleSimulatorRetryAsync(Simulator sim, ExceptionDispa { // Show a TaskDialog. bool result = false; - await Dispatcher.InvokeAsync(new Action(() => + await this.Dispatcher.InvokeAsync(new Action(() => { - if (!closeWindowAfterStop) + if (!this.closeWindowAfterStop) { - TaskDialog dialog = new TaskDialog() + var dialog = new TaskDialog() { Title = AppName, MainInstruction = "Simulator interrupted!", @@ -183,7 +183,7 @@ await Dispatcher.InvokeAsync(new Action(() => private static string GetExceptionDetailsText(Exception ex) { StringBuilder detailsSb = null; - Exception innerEx = ex.InnerException; + var innerEx = ex.InnerException; while (innerEx != null) { if (detailsSb == null) @@ -201,21 +201,21 @@ private static string GetExceptionDetailsText(Exception ex) private void HandleSimulatorCanceled() { - simulator = null; - btnStart.IsEnabled = true; - btnStop.IsEnabled = false; - btnLoad.IsEnabled = true; - if (quickActionButtons != null) - foreach (var bt in quickActionButtons) + this.simulator = null; + this.btnStart.IsEnabled = true; + this.btnStop.IsEnabled = false; + this.btnLoad.IsEnabled = true; + if (this.quickActionButtons != null) + foreach (var bt in this.quickActionButtons) bt.IsEnabled = true; - if (currentQuickAction != null) + if (this.currentQuickAction != null) { - currentQuickAction = null; + this.currentQuickAction = null; RefreshProjectControls(); } - if (closeWindowAfterStop) + if (this.closeWindowAfterStop) Close(); } @@ -223,27 +223,27 @@ private void HandleSimulatorCanceled() private void btnStop_Click(object sender, RoutedEventArgs e) { - simulator.Cancel(); - btnStop.IsEnabled = false; + this.simulator.Cancel(); + this.btnStop.IsEnabled = false; } private void btnLoad_Click(object sender, RoutedEventArgs e) { - if (openFileDialog.ShowDialog(this) == true) + if (this.openFileDialog.ShowDialog(this) == true) { // Try to load the given project. try { - using (FileStream fs = new FileStream(openFileDialog.FileName, FileMode.Open, + using (var fs = new FileStream(this.openFileDialog.FileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { - XmlProjectDeserializer deser = new XmlProjectDeserializer(); - project = deser.Deserialize(fs); + var deser = new XmlProjectDeserializer(); + this.project = deser.Deserialize(fs); } } catch (Exception ex) { - TaskDialog dialog = new TaskDialog() + var dialog = new TaskDialog() { Title = AppName, MainInstruction = "Could not load the selected project.", @@ -261,34 +261,34 @@ private void btnLoad_Click(object sender, RoutedEventArgs e) } - if (quickActionButtons != null) + if (this.quickActionButtons != null) { - foreach (var b in quickActionButtons) - gridProjectControls.Children.Remove(b); - quickActionButtons = null; + foreach (var b in this.quickActionButtons) + this.gridProjectControls.Children.Remove(b); + this.quickActionButtons = null; } RefreshProjectControls(); // For each quick action, create a button. - quickActionButtons = new Button[project.Configuration.QuickActions.Count]; - for (int idx = 0; idx < project.Configuration.QuickActions.Count; idx++) + this.quickActionButtons = new Button[this.project.Configuration.QuickActions.Count]; + for (int idx = 0; idx < this.project.Configuration.QuickActions.Count; idx++) { int i = idx; - var quickAction = project.Configuration.QuickActions[i]; + var quickAction = this.project.Configuration.QuickActions[i]; - Button b = quickActionButtons[i] = new Button(); + var b = this.quickActionButtons[i] = new Button(); b.Height = 21; b.HorizontalAlignment = HorizontalAlignment.Left; b.VerticalAlignment = VerticalAlignment.Top; b.Margin = new Thickness(0, 2 + 23 * i, 0, 0); b.Content = " " + quickAction.Name + " "; - gridProjectControls.Children.Add(b); + this.gridProjectControls.Children.Add(b); Grid.SetRow(b, 1); b.Click += async (_s, _e) => { - currentQuickAction = quickAction; + this.currentQuickAction = quickAction; RefreshProjectControls(); await RunSimulatorAsync(); @@ -299,29 +299,29 @@ private void btnLoad_Click(object sender, RoutedEventArgs e) private void RefreshProjectControls() { - lblActionTitle.Content = currentQuickAction != null ? currentQuickAction.Name - : project?.Configuration.MainAction != null ? actionTitleMainAction : ""; - if (project == null) + this.lblActionTitle.Content = this.currentQuickAction != null ? this.currentQuickAction.Name + : this.project?.Configuration.MainAction != null ? actionTitleMainAction : ""; + if (this.project == null) { - lblCurrentProject.Content = "(none)"; - txtDescription.Text = string.Empty; - btnStart.IsEnabled = false; + this.lblCurrentProject.Content = "(none)"; + this.txtDescription.Text = string.Empty; + this.btnStart.IsEnabled = false; } else { - lblCurrentProject.Content = project.Title; - txtDescription.Text = project.Description; - btnStart.IsEnabled = project.Configuration.MainAction != null; + this.lblCurrentProject.Content = this.project.Title; + this.txtDescription.Text = this.project.Description; + this.btnStart.IsEnabled = this.project.Configuration.MainAction != null; // Create labels for each action. - actionListGrid.Children.Clear(); - IAction mainAct = currentQuickAction != null ? currentQuickAction.Action - : project.Configuration.MainAction; + this.actionListGrid.Children.Clear(); + var mainAct = this.currentQuickAction != null ? this.currentQuickAction.Action + : this.project.Configuration.MainAction; if (mainAct != null) { int posCounter = 0; - CreateActionLabels(mainAct, actionListGrid, 0, ref posCounter, - out simulatorStartAction, out simulatorStopAction); + CreateActionLabels(mainAct, this.actionListGrid, 0, ref posCounter, + out this.simulatorStartAction, out this.simulatorStopAction); } } } @@ -329,7 +329,7 @@ private void RefreshProjectControls() private void CreateActionLabels(IAction action, Grid grid, int recursiveCount, ref int posCounter, out Action handleStart, out Action handleStop) { - Label l = new Label(); + var l = new Label(); l.Margin = new Thickness(recursiveCount * 10, 18 * posCounter, 0, 0); grid.Children.Add(l); @@ -346,17 +346,17 @@ private void CreateActionLabels(IAction action, Grid grid, int recursiveCount, l.Content = str; }; - action.ActionInformationUpdated += s => Dispatcher.Invoke(new Action(() => l.Content = str + " – " + s)); + action.ActionInformationUpdated += s => this.Dispatcher.Invoke(new Action(() => l.Content = str + " – " + s)); posCounter++; if (action is IActionContainer) { - IActionContainer cont = (IActionContainer)action; - IList subActions = cont.SubActions; - Action[] handleStartActions = new Action[subActions.Count]; - Action[] handleStopActions = new Action[subActions.Count]; + var cont = (IActionContainer)action; + var subActions = cont.SubActions; + var handleStartActions = new Action[subActions.Count]; + var handleStopActions = new Action[subActions.Count]; for (int i = 0; i < subActions.Count; i++) { CreateActionLabels(subActions[i], grid, recursiveCount + 1, ref posCounter, @@ -364,7 +364,7 @@ private void CreateActionLabels(IAction action, Grid grid, int recursiveCount, } int? currentActiveAction = null; - cont.SubActionStartedOrStopped += (idx) => Dispatcher.Invoke(new Action(() => + cont.SubActionStartedOrStopped += (idx) => this.Dispatcher.Invoke(new Action(() => { if (idx.HasValue) { diff --git a/TTMouseclickSimulator/Project/SimulatorProject.cs b/TTMouseclickSimulator/Project/SimulatorProject.cs index e38d63e..4b20036 100644 --- a/TTMouseclickSimulator/Project/SimulatorProject.cs +++ b/TTMouseclickSimulator/Project/SimulatorProject.cs @@ -12,6 +12,6 @@ public class SimulatorProject public SimulatorConfiguration Configuration { get; set; } - public override string ToString() => Title; + public override string ToString() => this.Title; } } diff --git a/TTMouseclickSimulator/Project/XmlProjectDeserializer.cs b/TTMouseclickSimulator/Project/XmlProjectDeserializer.cs index 9c92b9c..d93dcf2 100644 --- a/TTMouseclickSimulator/Project/XmlProjectDeserializer.cs +++ b/TTMouseclickSimulator/Project/XmlProjectDeserializer.cs @@ -92,7 +92,7 @@ private SimulatorConfiguration ParseConfiguration(XElement configEl) var mainActionEl = configEl.Element(ns + "MainAction"); if (mainActionEl != null) { - IList actionList = ParseActionList(mainActionEl); + var actionList = ParseActionList(mainActionEl); if (actionList.Count != 1) { throw new InvalidDataException(" must contain exactly one Action element."); @@ -108,7 +108,7 @@ private SimulatorConfiguration ParseConfiguration(XElement configEl) i++; var quickActionName = el.Attribute("title")?.Value ?? $"Quick Action [{i.ToString()}]"; - IList quickActionList = ParseActionList(el); + var quickActionList = ParseActionList(el); if (quickActionList.Count != 1) { throw new InvalidDataException(" must contain exactly one Action element."); @@ -128,7 +128,7 @@ private SimulatorConfiguration ParseConfiguration(XElement configEl) private IList ParseActionList(XElement parent) { - List actionList = new List(); + var actionList = new List(); foreach (var child in parent.Elements()) { if (child.Name.Namespace == ns) @@ -157,7 +157,7 @@ private IList ParseActionList(XElement parent) var param = parameters[i]; // Check if the element specifies the parameter. If not, use the default // value if available. - XAttribute attr = child.Attribute(param.Name); + var attr = child.Attribute(param.Name); if (typeof(IList).IsAssignableFrom(param.ParameterType)) { paramSubactionListIdx = i; @@ -204,9 +204,9 @@ private IList ParseActionList(XElement parent) else if (param.ParameterType.IsAssignableFrom(typeof(int[])) || param.ParameterType.IsAssignableFrom(typeof(byte[]))) { - string[] valueElements = attrval.Split(new string[] { "," }, + var valueElements = attrval.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); - Array values = Array.CreateInstance(param.ParameterType.GetElementType(), + var values = Array.CreateInstance(param.ParameterType.GetElementType(), valueElements.Length); for (int j = 0; j < valueElements.Length; j++) @@ -227,7 +227,7 @@ private IList ParseActionList(XElement parent) else if (typeof(Enum).IsAssignableFrom(param.ParameterType)) { // Find the enum entry with the specified name. - Array values = Enum.GetValues(param.ParameterType); + var values = Enum.GetValues(param.ParameterType); bool found = false; foreach (Enum val in values) { @@ -256,7 +256,7 @@ private IList ParseActionList(XElement parent) } // Parse child actions. - IList childActions = ParseActionList(child); + var childActions = ParseActionList(child); if (paramSubactionListIdx != -1) { parameterValues[paramSubactionListIdx] = childActions; @@ -276,7 +276,7 @@ private IList ParseActionList(XElement parent) // Now instanciate the IAction. - IAction instance = (IAction)constr.Invoke(parameterValues); + var instance = (IAction)constr.Invoke(parameterValues); actionList.Add(instance); } } diff --git a/TTMouseclickSimulator/Utils/TaskDialog.cs b/TTMouseclickSimulator/Utils/TaskDialog.cs index 40d55d1..ba0b6de 100644 --- a/TTMouseclickSimulator/Utils/TaskDialog.cs +++ b/TTMouseclickSimulator/Utils/TaskDialog.cs @@ -52,7 +52,7 @@ public class TaskDialog : IWin32Window, WinFormsIWin32Window /// /// The window handle of the dialog, or if the dialog is not active. /// - public IntPtr Handle => hwndDialog; + public IntPtr Handle => this.hwndDialog; public string Title { get; set; } @@ -114,17 +114,17 @@ public class TaskDialog : IWin32Window, WinFormsIWin32Window /// If is null, this field contains the /// of the common buttons that was pressed. /// - public TaskDialogResult ResultCommonButtonID => resultCommonButtonID; + public TaskDialogResult ResultCommonButtonID => this.resultCommonButtonID; /// /// If not null, contains the custom button that was pressed. Otherwise, /// contains the common button that was pressed. /// - public ICustomButton ResultCustomButton => resultCustomButton; + public ICustomButton ResultCustomButton => this.resultCustomButton; - public IRadioButton ResultRadioButton => resultRadioButton; + public IRadioButton ResultRadioButton => this.resultRadioButton; - public bool ResultVerificationFlagChecked => resultVerificationFlagChecked; + public bool ResultVerificationFlagChecked => this.resultVerificationFlagChecked; /// @@ -144,9 +144,9 @@ public class TaskDialog : IWin32Window, WinFormsIWin32Window public TaskDialog() { // Create a delegate for the callback. - callbackProcDelegate = new TaskDialogCallbackProcDelegate(TaskDialogCallbackProc); + this.callbackProcDelegate = new TaskDialogCallbackProcDelegate(TaskDialogCallbackProc); // Get a function pointer for the delegate. - ptrCallbackProcDelegate = Marshal.GetFunctionPointerForDelegate(callbackProcDelegate); + this.ptrCallbackProcDelegate = Marshal.GetFunctionPointerForDelegate(this.callbackProcDelegate); // Set default values Reset(); @@ -163,16 +163,16 @@ public TaskDialog() /// public void Reset() { - Flags = TaskDialogFlags.PositionRelativeToWindow; - Title = MainInstruction = Content = Footer = VerificationText = - ExpandedInformation = ExpandedControlText = CollapsedControlText = null; - MainIcon = MainUpdateIcon = FooterIcon = default(TaskDialogIcon); - CommonButtons = default(TaskDialogButtons); - CustomButtons = null; - RadioButtons = null; - DefaultCommonButton = default(TaskDialogResult); - DefaultCustomButton = null; - DefaultRadioButton = null; + this.Flags = TaskDialogFlags.PositionRelativeToWindow; + this.Title = this.MainInstruction = this.Content = this.Footer = this.VerificationText = + this.ExpandedInformation = this.ExpandedControlText = this.CollapsedControlText = null; + this.MainIcon = this.MainUpdateIcon = this.FooterIcon = default(TaskDialogIcon); + this.CommonButtons = default(TaskDialogButtons); + this.CustomButtons = null; + this.RadioButtons = null; + this.DefaultCommonButton = default(TaskDialogResult); + this.DefaultCustomButton = null; + this.DefaultRadioButton = null; } @@ -184,39 +184,39 @@ private void CheckButtonConfig() // has been created for Navigate(), which need to do the check, then releasing the old buttons, then // assigning the new buttons. - if (DefaultCustomButton != null && ((DefaultCustomButton as CustomButton)?.Creator != this)) + if (this.DefaultCustomButton != null && ((this.DefaultCustomButton as CustomButton)?.Creator != this)) throw new InvalidOperationException("Custom buttons must be created with this TaskDialog instance."); - if (DefaultRadioButton != null && ((DefaultRadioButton as RadioButton)?.Creator != this)) + if (this.DefaultRadioButton != null && ((this.DefaultRadioButton as RadioButton)?.Creator != this)) throw new InvalidOperationException("Radio buttons must be created with this TaskDialog instance."); - if (DefaultCustomButton != null && !(CustomButtons?.Contains(DefaultCustomButton) == true)) - throw new InvalidOperationException($"The default custom button must be part of the {nameof(CustomButtons)} array."); - if (DefaultRadioButton != null && !(RadioButtons?.Contains(DefaultRadioButton) == true)) - throw new InvalidOperationException($"The default radio button must be part of the {nameof(CustomButtons)} array."); - if ((Flags & TaskDialogFlags.UseCommandLinks) == TaskDialogFlags.UseCommandLinks && CustomButtons == null) - throw new InvalidOperationException($"When specifying the {nameof(TaskDialogFlags.UseCommandLinks)} flag, the {nameof(CustomButtons)} array must not be null."); + if (this.DefaultCustomButton != null && !(this.CustomButtons?.Contains(this.DefaultCustomButton) == true)) + throw new InvalidOperationException($"The default custom button must be part of the {nameof(this.CustomButtons)} array."); + if (this.DefaultRadioButton != null && !(this.RadioButtons?.Contains(this.DefaultRadioButton) == true)) + throw new InvalidOperationException($"The default radio button must be part of the {nameof(this.CustomButtons)} array."); + if ((this.Flags & TaskDialogFlags.UseCommandLinks) == TaskDialogFlags.UseCommandLinks && this.CustomButtons == null) + throw new InvalidOperationException($"When specifying the {nameof(TaskDialogFlags.UseCommandLinks)} flag, the {nameof(this.CustomButtons)} array must not be null."); - for (int i = 0; i < CustomButtons?.Length; i++) + for (int i = 0; i < this.CustomButtons?.Length; i++) { - var bt = CustomButtons[i] as CustomButton; + var bt = this.CustomButtons[i] as CustomButton; if (bt?.Creator != this) throw new InvalidOperationException("Custom buttons must be created with this TaskDialog instance."); // Check for duplicates. for (int j = 0; j < i; j++) { - if (CustomButtons[j] == bt) + if (this.CustomButtons[j] == bt) throw new InvalidOperationException("Duplicate custom button found."); } } - for (int i = 0; i < RadioButtons?.Length; i++) + for (int i = 0; i < this.RadioButtons?.Length; i++) { - var rbt = RadioButtons[i] as RadioButton; + var rbt = this.RadioButtons[i] as RadioButton; if (rbt?.Creator != this) throw new InvalidOperationException("Radio buttons must be created with this TaskDialog instance."); // Check for duplicates. for (int j = 0; j < i; j++) { - if (RadioButtons[j] == rbt) + if (this.RadioButtons[j] == rbt) throw new InvalidOperationException("Duplicate radio button found."); } } @@ -231,10 +231,10 @@ private void PrepareButtonConfig(out IDictionary currentCusto int currentCustomButtonID = CustomButtonStartID; - if (CustomButtons?.Length > 0) + if (this.CustomButtons?.Length > 0) { currentCustomButtons = new SortedDictionary(); - foreach (var button in CustomButtons) + foreach (var button in this.CustomButtons) { var bt = (CustomButton)button; int buttonId = currentCustomButtonID++; @@ -242,10 +242,10 @@ private void PrepareButtonConfig(out IDictionary currentCusto currentCustomButtons.Add(buttonId, bt); } } - if (RadioButtons?.Length > 0) + if (this.RadioButtons?.Length > 0) { currentRadioButtons = new SortedDictionary(); - foreach (var button in RadioButtons) + foreach (var button in this.RadioButtons) { var bt = (RadioButton)button; int buttonId = currentCustomButtonID++; @@ -274,34 +274,34 @@ private void CreateConfig(out TaskDialogConfig config) config = new TaskDialogConfig() { cbSize = Marshal.SizeOf(), - hwndParent = currentOwnerHwnd.Value, - pszWindowTitle = Title, - pszMainInstruction = MainInstruction, - pszContent = Content, - pszFooter = Footer, - dwCommonButtons = CommonButtons, - hMainIcon = (IntPtr)MainIcon, - dwFlags = Flags, - hFooterIcon = (IntPtr)FooterIcon, - pszVerificationText = VerificationText, - pszExpandedInformation = ExpandedInformation, - pszExpandedControlText = ExpandedControlText, - pszCollapsedControlText = CollapsedControlText, - nDefaultButton = (DefaultCustomButton as CustomButton)?.ButtonID ?? (int)DefaultCommonButton, - nDefaultRadioButton = (DefaultRadioButton as RadioButton)?.ButtonID ?? 0, - pfCallback = ptrCallbackProcDelegate + hwndParent = this.currentOwnerHwnd.Value, + pszWindowTitle = this.Title, + pszMainInstruction = this.MainInstruction, + pszContent = this.Content, + pszFooter = this.Footer, + dwCommonButtons = this.CommonButtons, + hMainIcon = (IntPtr)this.MainIcon, + dwFlags = this.Flags, + hFooterIcon = (IntPtr)this.FooterIcon, + pszVerificationText = this.VerificationText, + pszExpandedInformation = this.ExpandedInformation, + pszExpandedControlText = this.ExpandedControlText, + pszCollapsedControlText = this.CollapsedControlText, + nDefaultButton = (this.DefaultCustomButton as CustomButton)?.ButtonID ?? (int)this.DefaultCommonButton, + nDefaultRadioButton = (this.DefaultRadioButton as RadioButton)?.ButtonID ?? 0, + pfCallback = this.ptrCallbackProcDelegate }; - if (currentCustomButtons?.Count > 0) + if (this.currentCustomButtons?.Count > 0) { - TaskDialogButtonStruct[] structs = currentCustomButtons.Values.Select(e => + var structs = this.currentCustomButtons.Values.Select(e => new TaskDialogButtonStruct(e.ButtonID.Value, e.Text)).ToArray(); config.pButtons = AllocateAndMarshalButtons(structs); config.cButtons = structs.Length; } - if (currentRadioButtons?.Count > 0) + if (this.currentRadioButtons?.Count > 0) { - TaskDialogButtonStruct[] structs = currentRadioButtons.Values.Select(e => + var structs = this.currentRadioButtons.Values.Select(e => new TaskDialogButtonStruct(e.ButtonID.Value, e.Text)).ToArray(); config.pRadioButtons = AllocateAndMarshalButtons(structs); config.cRadioButtons = structs.Length; @@ -327,10 +327,10 @@ private static void DisposeConfig(ref TaskDialogConfig config) private static IntPtr AllocateAndMarshalButtons(TaskDialogButtonStruct[] structs) { // Allocate memory for the array. - IntPtr initialPtr = Marshal.AllocHGlobal( + var initialPtr = Marshal.AllocHGlobal( Marshal.SizeOf() * structs.Length); - IntPtr currentPtr = initialPtr; + var currentPtr = initialPtr; foreach (var button in structs) { // Marshal the struct element. This will allocate memory for the strings. @@ -343,7 +343,7 @@ private static IntPtr AllocateAndMarshalButtons(TaskDialogButtonStruct[] structs private static void FreeButtons(IntPtr pointer, int length) { - IntPtr currentPtr = pointer; + var currentPtr = pointer; // We need to destroy each structure. Otherwise we will leak memory from the // allocated strings (TaskDialogButton.ButtonText) which have been allocated // using Marshal.StructureToPtr(). @@ -359,9 +359,9 @@ private static void FreeButtons(IntPtr pointer, int length) private void ApplyButtonInitialization() { // Apply current properties of buttons after the dialog has been created. - if (currentCustomButtons != null) + if (this.currentCustomButtons != null) { - foreach (var btn in currentCustomButtons.Values) + foreach (var btn in this.currentCustomButtons.Values) { if (!btn.Enabled) btn.Enabled = false; @@ -369,9 +369,9 @@ private void ApplyButtonInitialization() btn.ButtonElevationRequiredState = true; } } - if (currentRadioButtons != null) + if (this.currentRadioButtons != null) { - foreach (var btn in currentRadioButtons.Values) + foreach (var btn in this.currentRadioButtons.Values) { if (!btn.Enabled) btn.Enabled = false; @@ -379,9 +379,9 @@ private void ApplyButtonInitialization() } // Check if we need to update the icon. - if (MainUpdateIcon != default(TaskDialogIcon) && MainIcon != MainUpdateIcon) + if (this.MainUpdateIcon != default(TaskDialogIcon) && this.MainIcon != this.MainUpdateIcon) { - CheckUpdateIcon(TaskDialogUpdateElements.MainIcon, TaskDialogUpdateElements.MainIcon, TaskDialogIconElement.Main, (IntPtr)MainUpdateIcon); + CheckUpdateIcon(TaskDialogUpdateElements.MainIcon, TaskDialogUpdateElements.MainIcon, TaskDialogIconElement.Main, (IntPtr)this.MainUpdateIcon); } } @@ -390,7 +390,7 @@ private int TaskDialogCallbackProc(IntPtr hWnd, TaskDialogNotifications notifica { try { - hwndDialog = hWnd; + this.hwndDialog = hWnd; switch (notification) { case TaskDialogNotifications.Created: @@ -400,7 +400,7 @@ private int TaskDialogCallbackProc(IntPtr hWnd, TaskDialogNotifications notifica case TaskDialogNotifications.Destroyed: OnClosing(EventArgs.Empty); // Clear the dialog handle. - hwndDialog = IntPtr.Zero; + this.hwndDialog = IntPtr.Zero; break; case TaskDialogNotifications.Navigated: ApplyButtonInitialization(); @@ -414,15 +414,15 @@ private int TaskDialogCallbackProc(IntPtr hWnd, TaskDialogNotifications notifica // Check if the button is part of the custom buttons. int buttonID = wparam.ToInt32(); CustomButton bt; - if (currentCustomButtons != null && currentCustomButtons.TryGetValue(buttonID, out bt)) + if (this.currentCustomButtons != null && this.currentCustomButtons.TryGetValue(buttonID, out bt)) return bt.ButtonClicked?.Invoke(bt, EventArgs.Empty) ?? true ? HResultOk : HResultFalse; else - return CommonButtonClicked?.Invoke(this, new CommonButtonClickedEventArgs((TaskDialogResult)buttonID)) ?? true ? HResultOk : HResultFalse; + return this.CommonButtonClicked?.Invoke(this, new CommonButtonClickedEventArgs((TaskDialogResult)buttonID)) ?? true ? HResultOk : HResultFalse; case TaskDialogNotifications.RadioButtonClicked: int rbuttonID = wparam.ToInt32(); RadioButton rbt; // Note: It should not happen that we don't find the radio button id. - if (currentRadioButtons != null && currentRadioButtons.TryGetValue(rbuttonID, out rbt)) + if (this.currentRadioButtons != null && this.currentRadioButtons.TryGetValue(rbuttonID, out rbt)) rbt.OnRadioButtonClicked(EventArgs.Empty); break; case TaskDialogNotifications.ExpandButtonClicked: @@ -451,11 +451,11 @@ private int TaskDialogCallbackProc(IntPtr hWnd, TaskDialogNotifications notifica private void SendTaskDialogMessage(TaskDialogMessages message, int wparam, IntPtr lparam) { - if (hwndDialog == IntPtr.Zero) + if (this.hwndDialog == IntPtr.Zero) throw new InvalidOperationException("Can only update the state of a task dialog while it is active."); SendMessage( - hwndDialog, + this.hwndDialog, (int)message, (IntPtr)wparam, lparam); @@ -527,13 +527,13 @@ private void SendTaskDialogMessage(TaskDialogMessages message, int wparam, IntPt public void Show(IntPtr hwndOwner) { // Recursive Show() is not possible because we would use the same callback delegate.. - if (currentOwnerHwnd.HasValue) + if (this.currentOwnerHwnd.HasValue) throw new InvalidOperationException("Cannot recursively show the same task dialog instance."); CheckButtonConfig(); - PrepareButtonConfig(out currentCustomButtons, out currentRadioButtons); + PrepareButtonConfig(out this.currentCustomButtons, out this.currentRadioButtons); - currentOwnerHwnd = hwndOwner; + this.currentOwnerHwnd = hwndOwner; TaskDialogConfig config; CreateConfig(out config); try @@ -543,7 +543,7 @@ public void Show(IntPtr hwndOwner) try { ret = TaskDialogIndirect(ref config, out resultButtonID, out resultRadioButtonID, - out resultVerificationFlagChecked); + out this.resultVerificationFlagChecked); } // Only catch exceptions if the hWnd of the task dialog is not set, otherwise the exception // must have occured in the callback. @@ -559,19 +559,19 @@ public void Show(IntPtr hwndOwner) // If do MessageBox.Show() wrapped in a try/catch on a button click, and before calling .Show() // create and start a timer which stops and throws an exception on its Tick event, // the application will crash with an AccessViolationException as soon as you close the MessageBox. - catch (Exception ex) when (hwndDialog == IntPtr.Zero && + catch (Exception ex) when (this.hwndDialog == IntPtr.Zero && (ex is DllNotFoundException || ex is EntryPointNotFoundException)) { // Show a regular messagebox instead. This should only happen if we debug and for some // reason the VS host process doesn't use our manifest. - StringBuilder msgContent = new StringBuilder(); - if (MainInstruction != null) - msgContent.Append(MainInstruction + "\n\n"); - if (Content != null) - msgContent.Append(Content + "\n\n"); - if (ExpandedInformation != null) - msgContent.Append(ExpandedInformation + "\n\n"); - MessageBox.Show(msgContent.ToString(), Title, MessageBoxButton.OK); + var msgContent = new StringBuilder(); + if (this.MainInstruction != null) + msgContent.Append(this.MainInstruction + "\n\n"); + if (this.Content != null) + msgContent.Append(this.Content + "\n\n"); + if (this.ExpandedInformation != null) + msgContent.Append(this.ExpandedInformation + "\n\n"); + MessageBox.Show(msgContent.ToString(), this.Title, MessageBoxButton.OK); resultButtonID = (int)TaskDialogResult.Ok; resultRadioButtonID = 0; @@ -587,31 +587,31 @@ public void Show(IntPtr hwndOwner) // Set the result fields CustomButton myResultCustomButton = null; - if (currentCustomButtons?.TryGetValue(resultButtonID, out myResultCustomButton) == true) + if (this.currentCustomButtons?.TryGetValue(resultButtonID, out myResultCustomButton) == true) { - resultCustomButton = myResultCustomButton; - resultCommonButtonID = 0; + this.resultCustomButton = myResultCustomButton; + this.resultCommonButtonID = 0; } else { - resultCommonButtonID = (TaskDialogResult)resultButtonID; - resultCustomButton = null; + this.resultCommonButtonID = (TaskDialogResult)resultButtonID; + this.resultCustomButton = null; } // Note that even if we have radio buttons, it could be that the user didn't select one. - if (!(currentRadioButtons?.TryGetValue(resultRadioButtonID, out resultRadioButton) == true)) - resultRadioButton = null; + if (!(this.currentRadioButtons?.TryGetValue(resultRadioButtonID, out this.resultRadioButton) == true)) + this.resultRadioButton = null; } finally { // Clear the handles and free the memory. - currentOwnerHwnd = null; + this.currentOwnerHwnd = null; DisposeConfig(ref config); - ClearButtonConfig(currentCustomButtons, currentRadioButtons); - currentCustomButtons = null; - currentRadioButtons = null; + ClearButtonConfig(this.currentCustomButtons, this.currentRadioButtons); + this.currentCustomButtons = null; + this.currentRadioButtons = null; // We need to ensure the callback delegate is not garbage-collected as long as TaskDialogIndirect // doesn't return, by calling GC.KeepAlive(). @@ -621,7 +621,7 @@ public void Show(IntPtr hwndOwner) // object's lifetime to as small a window as possible, to the point // where a 'this' pointer isn't considered live in an instance method // unless you read a value from the instance. - GC.KeepAlive(callbackProcDelegate); + GC.KeepAlive(this.callbackProcDelegate); } } @@ -649,14 +649,14 @@ public void Navigate() CheckButtonConfig(); // OK, create the new button config. - ClearButtonConfig(currentCustomButtons, currentRadioButtons); - PrepareButtonConfig(out currentCustomButtons, out currentRadioButtons); + ClearButtonConfig(this.currentCustomButtons, this.currentRadioButtons); + PrepareButtonConfig(out this.currentCustomButtons, out this.currentRadioButtons); // Create a new config and marshal it. TaskDialogConfig config; CreateConfig(out config); - IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf()); + var ptr = Marshal.AllocHGlobal(Marshal.SizeOf()); Marshal.StructureToPtr(config, ptr, false); try { @@ -747,12 +747,12 @@ private void ClickRadioButton(int radioButtonID) => /// public void UpdateElements(TaskDialogUpdateElements updateFlags) { - CheckUpdateElementText(updateFlags, TaskDialogUpdateElements.Content, TaskDialogElements.Content, Content); - CheckUpdateElementText(updateFlags, TaskDialogUpdateElements.ExpandedInformation, TaskDialogElements.ExpandedInformation, ExpandedInformation); - CheckUpdateElementText(updateFlags, TaskDialogUpdateElements.Footer, TaskDialogElements.Footer, Footer); - CheckUpdateElementText(updateFlags, TaskDialogUpdateElements.MainInstruction, TaskDialogElements.MainInstruction, MainInstruction); - CheckUpdateIcon(updateFlags, TaskDialogUpdateElements.MainIcon, TaskDialogIconElement.Main, (IntPtr)MainIcon); - CheckUpdateIcon(updateFlags, TaskDialogUpdateElements.FooterIcon, TaskDialogIconElement.Footer, (IntPtr)FooterIcon); + CheckUpdateElementText(updateFlags, TaskDialogUpdateElements.Content, TaskDialogElements.Content, this.Content); + CheckUpdateElementText(updateFlags, TaskDialogUpdateElements.ExpandedInformation, TaskDialogElements.ExpandedInformation, this.ExpandedInformation); + CheckUpdateElementText(updateFlags, TaskDialogUpdateElements.Footer, TaskDialogElements.Footer, this.Footer); + CheckUpdateElementText(updateFlags, TaskDialogUpdateElements.MainInstruction, TaskDialogElements.MainInstruction, this.MainInstruction); + CheckUpdateIcon(updateFlags, TaskDialogUpdateElements.MainIcon, TaskDialogIconElement.Main, (IntPtr)this.MainIcon); + CheckUpdateIcon(updateFlags, TaskDialogUpdateElements.FooterIcon, TaskDialogIconElement.Footer, (IntPtr)this.FooterIcon); } private void CheckUpdateElementText(TaskDialogUpdateElements updateFlags, TaskDialogUpdateElements flagToCheck, @@ -760,7 +760,7 @@ private void CheckUpdateElementText(TaskDialogUpdateElements updateFlags, TaskDi { if ((updateFlags & flagToCheck) == flagToCheck) { - IntPtr strPtr = Marshal.StringToHGlobalUni(text); + var strPtr = Marshal.StringToHGlobalUni(text); try { // Note: SetElementText will resize the dialog while UpdateElementText will not (which would @@ -811,7 +811,7 @@ public static TaskDialogResult Show(TaskDialog owner, string content, string ins public static TaskDialogResult Show(IntPtr hwndOwner, string content, string instruction = null, string caption = null, TaskDialogButtons buttons = TaskDialogButtons.OK, TaskDialogIcon icon = 0) { - TaskDialog dialog = new TaskDialog() + var dialog = new TaskDialog() { Content = content, MainInstruction = instruction, @@ -925,8 +925,8 @@ private struct TaskDialogButtonStruct public TaskDialogButtonStruct(int buttonID, string buttonText) { - ButtonID = buttonID; - ButtonText = buttonText; + this.ButtonID = buttonID; + this.ButtonText = buttonText; } } @@ -1077,7 +1077,7 @@ public class HyperlinkClickedEventArgs : EventArgs public HyperlinkClickedEventArgs(string hyperlink) { - Hyperlink = hyperlink; + this.Hyperlink = hyperlink; } } @@ -1090,7 +1090,7 @@ public class CommonButtonClickedEventArgs : EventArgs public CommonButtonClickedEventArgs(TaskDialogResult buttonID) { - ButtonID = buttonID; + this.ButtonID = buttonID; } } @@ -1100,7 +1100,7 @@ public class BooleanStatusEventArgs : EventArgs public BooleanStatusEventArgs(bool status) { - Status = status; + this.Status = status; } } @@ -1113,8 +1113,8 @@ private abstract class ButtonBase : IButtonBase public ButtonBase(TaskDialog creator, string text) { - Creator = creator; - Text = text; + this.Creator = creator; + this.Text = text; } protected void VerifyState() @@ -1127,7 +1127,7 @@ protected void VerifyState() protected bool TryVerifyState() { - return ButtonID.HasValue; + return this.ButtonID.HasValue; } public abstract void Click(); @@ -1139,12 +1139,12 @@ public bool Enabled { get { - return enabled; + return this.enabled; } set { SetEnabled(value); - enabled = value; + this.enabled = value; } } } @@ -1164,29 +1164,29 @@ public bool ButtonElevationRequiredState { get { - return buttonElevationRequiredState; + return this.buttonElevationRequiredState; } set { // The Task dialog will set this property on th Created/Navigated event. if (TryVerifyState()) - Creator.SetButtonElevationRequiredState(ButtonID.Value, value); - buttonElevationRequiredState = value; + this.Creator.SetButtonElevationRequiredState(this.ButtonID.Value, value); + this.buttonElevationRequiredState = value; } } public override void Click() { VerifyState(); - Creator.ClickButton(ButtonID.Value); + this.Creator.ClickButton(this.ButtonID.Value); } protected override void SetEnabled(bool enabled) { // The Task dialog will set this property on th Created/Navigated event. if (TryVerifyState()) - Creator.SetButtonEnabled(ButtonID.Value, enabled); + this.Creator.SetButtonEnabled(this.ButtonID.Value, enabled); } } @@ -1202,14 +1202,14 @@ public RadioButton(TaskDialog creator, string text) public override void Click() { VerifyState(); - Creator.ClickRadioButton(ButtonID.Value); + this.Creator.ClickRadioButton(this.ButtonID.Value); } protected override void SetEnabled(bool enabled) { // The Task dialog will set this property on th Created/Navigated event. if (TryVerifyState()) - Creator.SetRadioButtonEnabled(ButtonID.Value, enabled); + this.Creator.SetRadioButtonEnabled(this.ButtonID.Value, enabled); } public void OnRadioButtonClicked(EventArgs e) => RadioButtonClicked?.Invoke(this, e);