diff --git a/CLITest/Program.cs b/CLITest/Program.cs index 456a92f..4dc782e 100644 --- a/CLITest/Program.cs +++ b/CLITest/Program.cs @@ -5,71 +5,77 @@ using CC_Functions.Commandline.TUI; namespace CLITest { - class Program + internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.White; Console.Clear(); - Screen screen = new Screen(40, 20); + CenteredScreen cScreen = new CenteredScreen(40, 20, ConsoleColor.Green); + Panel screen = cScreen.ContentPanel; Button btn1 = new Button("Test") { - Point = new Point(2, 0) + Point = new Point(2, 0), + BackColor = ConsoleColor.DarkGreen }; screen.Controls.Add(btn1); - btn1.Click += (screen1, eventArgs) => - { - DiffDraw.FullDraw(true); - }; + btn1.Click += (screen1, eventArgs) => { DiffDraw.FullDraw(true); }; Label lab1 = new Label("Meem") { - Point = new Point(2, 1) + Point = new Point(2, 1), + BackColor = ConsoleColor.Green }; screen.Controls.Add(lab1); screen.Controls.Add(new Label("Saas\nSoos") { - Point = new Point(2, 2) + Point = new Point(2, 2), + BackColor = ConsoleColor.Green }); - Button btn2 = new Button("X"); + Button btn2 = new Button("X") + { + BackColor = ConsoleColor.Red, + ForeColor = ConsoleColor.White + }; screen.Controls.Add(btn2); - + CheckBox box = new CheckBox("Are u gae?") { - Point = new Point(2, 3) + Point = new Point(2, 3), + BackColor = ConsoleColor.DarkGreen }; screen.Controls.Add(box); - box.CheckedChanged += (screen1, eventArgs) => - { - lab1.Content = box.Checked ? "Sas" : "Meem"; - }; + box.CheckedChanged += (screen1, eventArgs) => { lab1.Content = box.Checked ? "Sas" : "Meem"; }; TextBox tbox = new TextBox("Hello\nWorld1\n\nHow are u?") { Size = new Size(20, 10), - Point = new Point(0, 6) + Point = new Point(0, 6), + BackColor = ConsoleColor.DarkYellow }; screen.Controls.Add(tbox); Slider slider = new Slider { Point = new Point(2, 4), - Size = new Size(8, 2), + Size = new Size(16, 2), MaxValue = 75, StepSize = 14, MinValue = -3, - Value = 7 + Value = 7, + BackColor = ConsoleColor.Magenta }; screen.Controls.Add(slider); - + bool visible = true; btn2.Click += (screen1, eventArgs) => visible = false; - screen.Close += (screen1, eventArgs) => visible = false; - screen.Render(); + cScreen.Close += (screen1, eventArgs) => visible = false; + cScreen.TabChanged += (screen1, eventArgs) => btn1.Content = $"Test {cScreen.TabPoint}"; + cScreen.Render(); while (visible) { Thread.Sleep(50); - screen.ReadInput(); + cScreen.ReadInput(); } Console.ResetColor(); Console.Clear(); diff --git a/Commandline/TUI/Button.cs b/Commandline/TUI/Button.cs index 6285536..2603a9b 100644 --- a/Commandline/TUI/Button.cs +++ b/Commandline/TUI/Button.cs @@ -1,41 +1,67 @@ +using System.Collections.Generic; using System.Drawing; +using System.Linq; using CC_Functions.Misc; namespace CC_Functions.Commandline.TUI { /// - /// A basic button type + /// A basic button type /// public class Button : Control { /// - /// The text inside this button + /// The text inside this button /// public string Content; + /// - /// Creates a new button + /// Creates a new button /// /// The text inside this button public Button(string content) { Content = content; char[,] tmp = Content.ToNdArray2D(); - Size = new Size(tmp.GetLength(0), tmp.GetLength(1)); - } - - /// - public override Pixel[,] Render() - { - char[,] inp = Content.ToNdArray2D(); - inp = inp.Resize(Size.Width, Size.Height); - Pixel[,] output = new Pixel[Size.Width, Size.Height]; - for (int x = 0; x < Size.Width; x++) - for (int y = 0; y < Size.Height; y++) - output[x, y] = new Pixel(Selected ? ForeColor : BackColor, Selected ? BackColor : ForeColor, inp[x, y]); - return output; + Size = new Size(tmp.GetLength(1), tmp.GetLength(0)); } /// public override bool Selectable { get; } = true; + + /// + public override Pixel[,] Render() + { + char[,] inp = Indent(SplitLines(Content, Size.Width), Size.Width).ToNdArray2D(); + inp = inp.Resize(Size.Height, Size.Width); + Pixel[,] output = new Pixel[Size.Height, Size.Width]; + for (int x = 0; x < Size.Height; x++) + for (int y = 0; y < Size.Width; y++) + output[x, y] = new Pixel(Selected ? ForeColor : BackColor, Selected ? BackColor : ForeColor, inp[x, y]); + return output; + } + + private string Indent(string source, int maxLen) + { + string[] tmp = source.Split('\n'); + for (int i = 0; i < tmp.Length; i++) tmp[i] = new string(SpecialChars.Empty, (maxLen - tmp[i].Length) / 2) + tmp[i]; + return string.Join('\n', tmp); + } + + private string SplitLines(string source, int maxLen) + { + List parts = new List(source.Split()); + while (parts.Any(s => s.Length > maxLen)) + { + parts = parts.SelectMany(s => + { + if (s.Length > maxLen) + return s.Insert(maxLen, "\n").Split('\n'); + else + return new[] {s}; + }).ToList(); + } + return string.Join('\n', parts); + } } } \ No newline at end of file diff --git a/Commandline/TUI/CenteredScreen.cs b/Commandline/TUI/CenteredScreen.cs new file mode 100644 index 0000000..928689b --- /dev/null +++ b/Commandline/TUI/CenteredScreen.cs @@ -0,0 +1,73 @@ +using System; +using System.Drawing; +using CC_Functions.Misc; + +namespace CC_Functions.Commandline.TUI +{ + /// + /// Provides a screen that stays in the middle of the console. Use ContentPanel to attach controls + /// + public class CenteredScreen : Screen + { + private bool _resizing; + + /// + /// The actual size of this control. The "Size" property is assigned automatically + /// + public Size ActualSize; + + /// + /// The panel used for storing and rendering the actual controls + /// + public Panel ContentPanel; + + /// + /// The title to display at the top of the console + /// + public string Title = "CC-Functions.CommandLine app"; + + private readonly Label _titleLabel; + + /// + /// Creates a screen that stays in the middle of the console. Use ContentPanel to attach controls + /// + /// The width of the content panel + /// The height of the content panel + /// The content panels background (Should be different from Console.BackgroundColor) + /// Whether to use color when drawing + public CenteredScreen(int width, int height, ConsoleColor contentBack, bool color = true) : base(width, height, color) + { + ContentPanel = new Panel {BackColor = contentBack}; + ActualSize = new Size(width, height); + _titleLabel = new Label(Title); + Controls.Add(ContentPanel); + Controls.Add(_titleLabel); + WindowResize += (screen, args) => CalculatePosition(); + ((Control) this).Resize += (caller, args) => CalculatePosition(); + CalculatePosition(true); + } + + /// + /// Calculates the Size variable, Title and ContentPanel position/size + /// + /// Whether this is the initial calculation + public void CalculatePosition(bool initial = false) + { + if (!_resizing) + { + _resizing = true; + Size = new Size(Console.WindowWidth, Console.WindowHeight - 1); + _titleLabel.Content = Title + Environment.NewLine + new string(SpecialChars.OneLineSimple.LeftRight, Console.WindowWidth); + ContentPanel.Size = ActualSize; + ContentPanel.Point = new Point((Console.WindowWidth - ActualSize.Width) / 2, + (Console.WindowHeight - ActualSize.Height) / 2); + if (!initial) + { + Console.Clear(); + DiffDraw.FullDraw(Color); + } + _resizing = false; + } + } + } +} \ No newline at end of file diff --git a/Commandline/TUI/CheckBox.cs b/Commandline/TUI/CheckBox.cs index cddda3a..dd1fcef 100644 --- a/Commandline/TUI/CheckBox.cs +++ b/Commandline/TUI/CheckBox.cs @@ -5,20 +5,29 @@ using CC_Functions.Misc; namespace CC_Functions.Commandline.TUI { /// - /// Provides a control for users to select a boolean + /// Provides a control for users to select a boolean /// public class CheckBox : Control { /// - /// The text inside this checkbox + /// Called when the state of this checkbox is changed + /// + /// The current screen instance + /// Args + public delegate void OnCheckedChanged(Screen screen, EventArgs e); + + /// + /// Whether the box is checked + /// + public bool Checked; + + /// + /// The text inside this checkbox /// public string Content; + /// - /// Whether the box is checked - /// - public bool Checked = false; - /// - /// Creates a new checkbox + /// Creates a new checkbox /// /// The text inside this CheckBox public CheckBox(string content) @@ -43,6 +52,9 @@ namespace CC_Functions.Commandline.TUI }; } + /// + public override bool Selectable { get; } = true; + /// public override Pixel[,] Render() { @@ -63,17 +75,8 @@ namespace CC_Functions.Commandline.TUI return output; } - /// - public override bool Selectable { get; } = true; - /// - /// Called when the state of this checkbox is changed - /// - /// The current screen instance - /// Args - public delegate void OnCheckedChanged(Screen screen, EventArgs e); - /// - /// Called when the state of this checkbox is changed + /// Called when the state of this checkbox is changed /// public event OnClick CheckedChanged; } diff --git a/Commandline/TUI/Control.cs b/Commandline/TUI/Control.cs index 88c7939..c4040d0 100644 --- a/Commandline/TUI/Control.cs +++ b/Commandline/TUI/Control.cs @@ -4,29 +4,45 @@ using System.Drawing; namespace CC_Functions.Commandline.TUI { /// - /// Abstract class inherited by all controls + /// Abstract class inherited by all controls /// public abstract class Control { /// - /// Called when the controls Size property is changed + /// Called when [enter] is pressed while the control is selected + /// + /// An instance of the calling screen + /// Args + public delegate void OnClick(Screen screen, EventArgs e); + + /// + /// Called when the control is selected and unknown input is given + /// + /// An instance of the calling screen + /// Args + public delegate void OnInput(Screen screen, InputEventArgs e); + + /// + /// Called when the controls Size property is changed /// /// The calling control /// Args public delegate void OnResize(Control caller, EventArgs e); - /// - /// Called when the controls Size property is changed - /// - public event OnResize Resize; - private Point _point; + private Size _size; + /// - /// Renders the control + /// Whether the control can be interacted with /// - /// The rendered pixels - public abstract Pixel[,] Render(); + public bool Enabled = true; + /// - /// The size of the control + /// Whether the control should be rendered + /// + public bool Visible = true; + + /// + /// The size of the control /// public Size Size { @@ -40,61 +56,64 @@ namespace CC_Functions.Commandline.TUI } get => _size; } + /// - /// The position of this control + /// The position of this control /// - public Point Point - { - get => _point; - set => _point = value; - } + public Point Point { get; set; } + /// - /// The foreground color for this control + /// The foreground color for this control /// public ConsoleColor ForeColor { get; set; } = Console.ForegroundColor; + /// - /// The background color for this control + /// The background color for this control /// public ConsoleColor BackColor { get; set; } = Console.BackgroundColor; + /// - /// Whether the control can be selected + /// Whether the control can be selected /// public abstract bool Selectable { get; } /// - /// Called when [enter] is pressed while the control is selected - /// - /// An instance of the calling screen - /// Args - public delegate void OnClick(Screen screen, EventArgs e); - /// - /// Called when [enter] is pressed while the control is selected - /// - public event OnClick Click; - /// - /// Called when the control is selected and unknown input is given - /// - /// An instance of the calling screen - /// Args - public delegate void OnInput(Screen screen, InputEventArgs e); - /// - /// Called when the control is selected and unknown input is given - /// - public event OnInput Input; - /// - /// Whether the object is selected. Used internally and for drawing + /// Whether the object is selected. Used internally and for drawing /// public bool Selected { get; internal set; } = false; + /// - /// Invokes click events + /// Called when the controls Size property is changed + /// + public event OnResize Resize; + + /// + /// Renders the control + /// + /// The rendered pixels + public abstract Pixel[,] Render(); + + /// + /// Called when [enter] is pressed while the control is selected + /// + public event OnClick Click; + + /// + /// Called when the control is selected and unknown input is given + /// + public event OnInput Input; + + /// + /// Invokes click events /// /// The calling screen internal void InvokeClick(Screen screen) { Click?.Invoke(screen, new EventArgs()); } + /// - /// Invokes input events + /// Invokes input events /// /// The calling screen /// The input data @@ -102,13 +121,5 @@ namespace CC_Functions.Commandline.TUI { Input?.Invoke(screen, new InputEventArgs(info)); } - /// - /// Whether the control should be rendered - /// - public bool Visible = true; - /// - /// Whether the control can be interacted with - /// - public bool Enabled = true; } } \ No newline at end of file diff --git a/Commandline/TUI/DiffDraw.cs b/Commandline/TUI/DiffDraw.cs index a500de3..a37e21a 100644 --- a/Commandline/TUI/DiffDraw.cs +++ b/Commandline/TUI/DiffDraw.cs @@ -5,22 +5,25 @@ using CC_Functions.Misc; namespace CC_Functions.Commandline.TUI { /// - /// Provides differential drawing of a char[,] Do not use in combination with System.Console + /// Provides differential drawing of a char[,] Do not use in combination with System.Console /// public static class DiffDraw { + private static Pixel[,] _last = new Pixel[0, 0]; private static Pixel[,] Screen { get; set; } = new Pixel[0, 0]; - private static Pixel[,] _last = new Pixel[0,0]; + /// - /// The regions width + /// The regions width /// public static int Width => Screen.GetLength(1); + /// - /// The regions height + /// The regions height /// public static int Height => Screen.GetLength(0); + /// - /// Draws to the console + /// Draws to the console /// /// Whether to use color public static void Draw(bool color) @@ -39,8 +42,10 @@ namespace CC_Functions.Commandline.TUI if (tmp1 == _last[y, x]) continue; if (color) { - Console.ForegroundColor = tmp1.ForeColor; - Console.BackgroundColor = tmp1.BackColor; + if (Console.ForegroundColor != tmp1.ForeColor) + Console.ForegroundColor = tmp1.ForeColor; + if (Console.BackgroundColor != tmp1.BackColor) + Console.BackgroundColor = tmp1.BackColor; } Console.CursorLeft = x; Console.Write(tmp1); @@ -52,8 +57,9 @@ namespace CC_Functions.Commandline.TUI Console.BackgroundColor = bcol; _last = Screen; } + /// - /// Redraws the entire screen (should be done from time to time to prevent corruption) + /// Redraws the entire screen (should be done from time to time to prevent corruption) /// /// Whether to use color public static void FullDraw(bool color) @@ -72,8 +78,10 @@ namespace CC_Functions.Commandline.TUI Pixel tmp1 = Screen[y, x]; if (color) { - Console.ForegroundColor = tmp1.ForeColor; - Console.BackgroundColor = tmp1.BackColor; + if (Console.ForegroundColor != tmp1.ForeColor) + Console.ForegroundColor = tmp1.ForeColor; + if (Console.BackgroundColor != tmp1.BackColor) + Console.BackgroundColor = tmp1.BackColor; } Console.CursorLeft = x; Console.Write(tmp1); @@ -85,64 +93,74 @@ namespace CC_Functions.Commandline.TUI Console.BackgroundColor = bcol; _last = Screen; } + /// - /// Gets the char at a location + /// Gets the char at a location /// /// The location /// The char public static char Get(Point p) => Get(p.X, p.Y); + /// - /// Gets the char at a location + /// Gets the char at a location /// /// The locations X coordinate /// The locations Y coordinate /// The char public static char Get(int x, int y) => Screen[y, x].Content; + /// - /// Gets the foreground color at a location + /// Gets the foreground color at a location /// /// The location /// The color public static ConsoleColor GetForeColor(Point p) => GetForeColor(p.X, p.Y); + /// - /// Gets the foreground color at a location + /// Gets the foreground color at a location /// /// The locations X coordinate /// The locations Y coordinate /// The color public static ConsoleColor GetForeColor(int x, int y) => Screen[y, x].ForeColor; + /// - /// Gets the background color at a location + /// Gets the background color at a location /// /// The location /// The color public static ConsoleColor GetBackColor(Point p) => GetBackColor(p.X, p.Y); + /// - /// Gets the background color at a location + /// Gets the background color at a location /// /// The locations X coordinate /// The locations Y coordinate /// The color public static ConsoleColor GetBackColor(int x, int y) => Screen[y, x].BackColor; + /// - /// Sets a pixel at a point + /// Sets a pixel at a point /// /// The point to place at /// The pixel to place public static void Set(Point p, Pixel c) => Set(p.X, p.Y, c); + /// - /// Sets a pixel at a location + /// Sets a pixel at a location /// /// The locations X coordinate /// The locations Y coordinate /// The pixel to place public static void Set(int x, int y, Pixel c) => Screen[y, x] = c; + /// - /// Clears the screen + /// Clears the screen /// public static void Clear() => Clear(Width, Height); + /// - /// Resizes and clears the screen + /// Resizes and clears the screen /// /// The new width /// The new height @@ -151,8 +169,9 @@ namespace CC_Functions.Commandline.TUI Screen = new Pixel[height, width]; _last = _last.Resize(height, width); } + /// - /// Replaces the screen state + /// Replaces the screen state /// /// The new state public static void Clear(Pixel[,] content) diff --git a/Commandline/TUI/InputEventArgs.cs b/Commandline/TUI/InputEventArgs.cs index 431d31f..150970e 100644 --- a/Commandline/TUI/InputEventArgs.cs +++ b/Commandline/TUI/InputEventArgs.cs @@ -3,19 +3,19 @@ using System; namespace CC_Functions.Commandline.TUI { /// - /// Arguments containing input data + /// Arguments containing input data /// public class InputEventArgs : EventArgs { - private readonly ConsoleKeyInfo _info; /// - /// The inputs data - /// - public ConsoleKeyInfo Info => _info; - /// - /// Generates new arguments + /// Generates new arguments /// /// The input data - public InputEventArgs(ConsoleKeyInfo info) => _info = info; + public InputEventArgs(ConsoleKeyInfo info) => Info = info; + + /// + /// The inputs data + /// + public ConsoleKeyInfo Info { get; } } } \ No newline at end of file diff --git a/Commandline/TUI/Label.cs b/Commandline/TUI/Label.cs index c0e1069..d6e65ad 100644 --- a/Commandline/TUI/Label.cs +++ b/Commandline/TUI/Label.cs @@ -4,19 +4,24 @@ using CC_Functions.Misc; namespace CC_Functions.Commandline.TUI { /// - /// A basic text control + /// A basic text control /// public class Label : Control { /// - /// The text inside this label + /// The text inside this label /// public string Content; + /// - /// Creates a new label + /// Creates a new label /// /// The text inside this label public Label(string content) => Content = content; + + /// + public override bool Selectable { get; } = false; + /// public override Pixel[,] Render() { @@ -30,7 +35,5 @@ namespace CC_Functions.Commandline.TUI Size = new Size(w, h); return output; } - /// - public override bool Selectable { get; } = false; } } \ No newline at end of file diff --git a/Commandline/TUI/Panel.cs b/Commandline/TUI/Panel.cs index 6ed8218..e298fc5 100644 --- a/Commandline/TUI/Panel.cs +++ b/Commandline/TUI/Panel.cs @@ -5,37 +5,47 @@ using CC_Functions.Misc; namespace CC_Functions.Commandline.TUI { /// - /// A panel containing other components. MUST be inherited for all other controls that contain others + /// A panel containing other components. MUST be inherited for all other controls that contain others /// public class Panel : Control { /// - /// The controls inside this panel + /// Enable to draw a simple border around this control + /// + public bool Border = true; + /// + /// The controls inside this panel /// public List Controls = new List(); + /// + public override bool Selectable { get; } = false; + /// - /// Renders the control and all contained controls + /// Renders the control and all contained controls /// /// The rendered pixels public override Pixel[,] Render() { Pixel[,] tmp = new Pixel[Size.Height, Size.Width]; tmp.Populate(new Pixel(BackColor, ForeColor, SpecialChars.Empty)); - foreach (Control control in Controls) + if (Border) { + for (int i = 0; i < Size.Width; i++) tmp[Size.Height - 1, i] = new Pixel(BackColor, ForeColor, SpecialChars.OneLineSimple.LeftRight); + for (int i = 0; i < Size.Height; i++) tmp[i, Size.Width - 1] = new Pixel(BackColor, ForeColor, SpecialChars.OneLineSimple.UpDown); + tmp[Size.Height - 1, Size.Width - 1] = new Pixel(BackColor, ForeColor, '┘'); + } + foreach (Control control in Controls) if (control.Visible) { Pixel[,] render = control.Render(); render.CopyTo(tmp, control.Point); } - } return tmp; } - /// - public override bool Selectable { get; } = false; + /// - /// Recursively enumerates all controls + /// Recursively enumerates all controls /// /// A list of all controls public Control[] EnumerateRecursive() @@ -50,4 +60,4 @@ namespace CC_Functions.Commandline.TUI return output.ToArray(); } } -} +} \ No newline at end of file diff --git a/Commandline/TUI/Pixel.cs b/Commandline/TUI/Pixel.cs index 2ebaedf..1087192 100644 --- a/Commandline/TUI/Pixel.cs +++ b/Commandline/TUI/Pixel.cs @@ -4,10 +4,106 @@ using System.Collections.Generic; namespace CC_Functions.Commandline.TUI { /// - /// Represents a pixel + /// Represents a pixel /// public class Pixel { + /// + /// This pixels background color + /// + public ConsoleColor BackColor; + + /// + /// This pixels content character + /// + public char Content; + + /// + /// This pixels foregound color + /// + public ConsoleColor ForeColor; + + /// + /// Generates a new pixel + /// + /// The background color + /// The foreground color + /// The new content + public Pixel(ConsoleColor backColor, ConsoleColor foreColor, char content) + { + BackColor = backColor; + ForeColor = foreColor; + Content = content; + } + + /// + /// Generates a new pixel + /// + /// The content for this pixel + public Pixel(char content) : this(Console.BackgroundColor, Console.ForegroundColor, content) + { + } + + /// + /// Generates a new pixel + /// + public Pixel() : this(' ') + { + } + + /// + /// Use this in functions that require equality comparers + /// + public static IEqualityComparer ColorContentComparer { get; } = new ColorContentEqualityComparer(); + + /// + /// Whether this is equal to another pixel + /// + /// The other pixel to compare + /// Whether they are equal + protected bool Equals(Pixel other) => ColorContentComparer.Equals(this, other); + + /// + /// Whether this is equal to another object + /// + /// The other object to compare + /// + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) return false; + if (ReferenceEquals(this, obj)) return true; + if (obj.GetType() != GetType()) return false; + return Equals((Pixel) obj); + } + + /// + /// Generates an integer for comparing this object + /// + /// The generated hash + public override int GetHashCode() => HashCode.Combine((int) BackColor, (int) ForeColor, Content); + + /// + /// Whether two pixels are equal + /// + /// First pixel to compare + /// Second pixel to compare + /// Whether they are equal + public static bool operator ==(Pixel a, Pixel b) => a.Equals(b); + + /// + /// Whether to pixels are not equal + /// + /// First pixel to compare + /// Second pixel to compare + /// Whether they are not equal + public static bool operator !=(Pixel a, Pixel b) => !a.Equals(b); + + /// + /// Returns the content of this pixel + /// + /// The content of this pixel + public override string ToString() => Content.ToString(); + private sealed class ColorContentEqualityComparer : IEqualityComparer { public bool Equals(Pixel x, Pixel y) @@ -21,89 +117,5 @@ namespace CC_Functions.Commandline.TUI public int GetHashCode(Pixel obj) => obj.GetHashCode(); } - /// - /// Use this in functions that require equality comparers - /// - public static IEqualityComparer ColorContentComparer { get; } = new ColorContentEqualityComparer(); - /// - /// Whether this is equal to another pixel - /// - /// The other pixel to compare - /// Whether they are equal - protected bool Equals(Pixel other) => ColorContentComparer.Equals(this, other); - /// - /// Whether this is equal to another object - /// - /// The other object to compare - /// - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) return false; - if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != GetType()) return false; - return Equals((Pixel) obj); - } - - /// - /// Generates an integer for comparing this object - /// - /// The generated hash - public override int GetHashCode() => HashCode.Combine((int) BackColor, (int) ForeColor, Content); - /// - /// This pixels background color - /// - public ConsoleColor BackColor; - /// - /// This pixels foregound color - /// - public ConsoleColor ForeColor; - /// - /// This pixels content character - /// - public char Content; - /// - /// Generates a new pixel - /// - /// The background color - /// The foreground color - /// The new content - public Pixel(ConsoleColor backColor, ConsoleColor foreColor, char content) - { - BackColor = backColor; - ForeColor = foreColor; - Content = content; - } - /// - /// Generates a new pixel - /// - /// The content for this pixel - public Pixel(char content) : this(Console.BackgroundColor, Console.ForegroundColor, content) - { - } - /// - /// Generates a new pixel - /// - public Pixel() : this(' ') - { - } - /// - /// Whether two pixels are equal - /// - /// First pixel to compare - /// Second pixel to compare - /// Whether they are equal - public static bool operator ==(Pixel a, Pixel b) => a.Equals(b); - /// - /// Whether to pixels are not equal - /// - /// First pixel to compare - /// Second pixel to compare - /// Whether they are not equal - public static bool operator !=(Pixel a, Pixel b) => !a.Equals(b); - /// - /// Returns the content of this pixel - /// - /// The content of this pixel - public override string ToString() => Content.ToString(); } } \ No newline at end of file diff --git a/Commandline/TUI/Screen.cs b/Commandline/TUI/Screen.cs index 642cae0..5cfacd9 100644 --- a/Commandline/TUI/Screen.cs +++ b/Commandline/TUI/Screen.cs @@ -5,22 +5,46 @@ using System.Linq; namespace CC_Functions.Commandline.TUI { /// - /// Provides a front-end renderer for panels, draws using DiffDraw + /// Provides a front-end renderer for panels, draws using DiffDraw /// public class Screen : Panel { /// - /// Whether to output in color. Recommended for most terminals, might cause slowdowns in others + /// Called if Escape is pressed, use this for flow control + /// + /// This instance of the screen class + /// Args + public delegate void OnClose(Screen screen, EventArgs e); + + /// + /// Called when the selected control is changed + /// + /// This instance of the screen class + /// Args + public delegate void OnTabChanged(Screen screen, EventArgs args); + + /// + /// Called by ReadInput if a change in the window size is detected. Use this for positioning + /// + /// This instance of the screen class + /// Args + public delegate void OnWindowResize(Screen screen, EventArgs e); + + /// + /// Whether to output in color. Recommended for most terminals, might cause slowdowns in others /// public readonly bool Color; - /// - /// The current index of the tab-selected control in an array of selectable controls - /// - public int TabPoint = 0; - private int _wndWidth = Console.WindowWidth; + private int _wndHeight = Console.WindowHeight; + private int _wndWidth = Console.WindowWidth; + /// - /// Creates a screen object. Multiple can be instantiated but drawing one overrides others. Use panels for that + /// The current index of the tab-selected control in an array of selectable controls + /// + public int TabPoint; + + /// + /// Creates a screen object. Multiple can be instantiated but drawing one overrides others. Use panels for that /// /// The screens with /// The screens height @@ -28,12 +52,13 @@ namespace CC_Functions.Commandline.TUI public Screen(int width, int height, bool color = true) { Color = color; + Border = false; Resize(width, height); Tab(); } /// - /// Resizes the screen. Make sure that this does not exceed the console size + /// Resizes the screen. Make sure that this does not exceed the console size /// /// /// @@ -42,9 +67,9 @@ namespace CC_Functions.Commandline.TUI Size = new Size(width, height); DiffDraw.Clear(width, height); } - + /// - /// Renders the screen, draws it to the console and outputs the new state + /// Renders the screen, draws it to the console and outputs the new state /// /// The new state of the screen public new Pixel[,] Render() @@ -56,9 +81,12 @@ namespace CC_Functions.Commandline.TUI } /// - /// Reads input from Console and calls according functions + /// Reads input from Console and calls according functions /// - /// Set to false to prevent redrawing if the screen should be updated. You can Render manually in that case + /// + /// Set to false to prevent redrawing if the screen should be updated. You can Render manually in + /// that case + /// public void ReadInput(bool canRedraw = true) { bool render = false; @@ -101,8 +129,9 @@ namespace CC_Functions.Commandline.TUI if (canRedraw && render) Render(); } + /// - /// Increases the TabPoint or reverts back to 0 if at the end of selectables + /// Increases the TabPoint or reverts back to 0 if at the end of selectables /// /// Set to false to decrease instead public void Tab(bool positive = true) @@ -111,8 +140,9 @@ namespace CC_Functions.Commandline.TUI Control[] selectable = controls.Where(s => s.Selectable).ToArray(); Tab(selectable, positive); } + /// - /// Increases the TabPoint or reverts back to 0 if at the end of selectables + /// Increases the TabPoint or reverts back to 0 if at the end of selectables /// /// The array of selectable controls to select from. You should most likely not use this /// Set to false to decrease instead @@ -132,28 +162,24 @@ namespace CC_Functions.Commandline.TUI } foreach (Control control in selectable) control.Selected = false; selectable[TabPoint].Selected = true; + TabChanged?.Invoke(this, new EventArgs()); Render(); } } + /// - /// Called if Escape is pressed, use this for flow control - /// - /// This instance of the screen class - /// Args - public delegate void OnClose(Screen screen, EventArgs e); - /// - /// Called if Escape is pressed, use this for flow control + /// Called if Escape is pressed, use this for flow control /// public event OnClose Close; + /// - /// Called by ReadInput if a change in the window size is detected. Use this for positioning - /// - /// This instance of the screen class - /// Args - public delegate void OnWindowResize(Screen screen, EventArgs e); - /// - /// Called by ReadInput if a change in the window size is detected. Use this for positioning + /// Called by ReadInput if a change in the window size is detected. Use this for positioning /// public event OnWindowResize WindowResize; + + /// + /// Called when the selected control is changed + /// + public event OnTabChanged TabChanged; } } \ No newline at end of file diff --git a/Commandline/TUI/Slider.cs b/Commandline/TUI/Slider.cs index fbdabfe..b03a3ae 100644 --- a/Commandline/TUI/Slider.cs +++ b/Commandline/TUI/Slider.cs @@ -4,12 +4,21 @@ using CC_Functions.Misc; namespace CC_Functions.Commandline.TUI { /// - /// Provides a control to select a number from a range of numbers + /// Provides a control to select a number from a range of numbers /// public class Slider : Control { + private int _maxValue = 10; + private int _minValue; + private int _value = 5; + /// - /// Generates a new slider + /// The size of steps in this slider + /// + public int StepSize = 1; + + /// + /// Generates a new slider /// public Slider() { @@ -32,8 +41,9 @@ namespace CC_Functions.Commandline.TUI } }; } + /// - /// The maximum value for this slider + /// The maximum value for this slider /// /// Thrown if too low/high public int MaxValue @@ -44,11 +54,13 @@ namespace CC_Functions.Commandline.TUI if (value > MinValue && value >= Value) _maxValue = value; else - throw new ArgumentOutOfRangeException("MaxValue must be larger than MinValue and equal to or larger than Value"); + throw new ArgumentOutOfRangeException( + "MaxValue must be larger than MinValue and equal to or larger than Value"); } } + /// - /// The minimal value for this slider + /// The minimal value for this slider /// /// Thrown if too low/high public int MinValue @@ -59,11 +71,13 @@ namespace CC_Functions.Commandline.TUI if (value < MaxValue && value <= Value) _minValue = value; else - throw new ArgumentOutOfRangeException("MaxValue must be larger than MinValue and equal to or smaller than Value"); + throw new ArgumentOutOfRangeException( + "MaxValue must be larger than MinValue and equal to or smaller than Value"); } } + /// - /// The current value of this slider + /// The current value of this slider /// /// Thrown if too low/high public int Value @@ -77,13 +91,10 @@ namespace CC_Functions.Commandline.TUI throw new ArgumentOutOfRangeException("Value must be between MinValue and MaxValue"); } } - /// - /// The size of steps in this slider - /// - public int StepSize = 1; - private int _value = 5; - private int _maxValue = 10; - private int _minValue = 0; + + /// + public override bool Selectable { get; } = true; + /// public override Pixel[,] Render() { @@ -91,16 +102,17 @@ namespace CC_Functions.Commandline.TUI int litValLen = Math.Max(MaxValue.ToString().Length, MinValue.ToString().Length); int prevpts = Math.Max((Value - MinValue) * Size.Width / delta - litValLen - 2, 0); int postpts = Math.Max(Size.Width - prevpts - litValLen - 2, 0); - char[,] rend = $"{new string('=', prevpts)}[{Value.ToString($"D{litValLen}")}]{new string('=', postpts)}".ToNdArray2D(); + char[,] rend = $"{new string('=', prevpts)}[{Value.ToString($"D{(Value < 0 ? litValLen - 1 : litValLen)}")}]{new string('=', postpts)}" + .ToNdArray2D(); int f1 = rend.GetLength(0); int f2 = rend.GetLength(1); Pixel[,] output = new Pixel[f1, f2]; output.Populate(new Pixel()); for (int i = 0; i < f1; i++) - for (int j = 0; j < f2; j++) output[i, j] = new Pixel(Selected ? ForeColor : BackColor, Selected ? BackColor : ForeColor, rend[i, j]); + for (int j = 0; j < f2; j++) + output[i, j] = new Pixel(Selected ? ForeColor : BackColor, Selected ? BackColor : ForeColor, + rend[i, j]); return output; } - /// - public override bool Selectable { get; } = true; } } \ No newline at end of file diff --git a/Commandline/TUI/TextBox.cs b/Commandline/TUI/TextBox.cs index 0f62bc3..50544cb 100644 --- a/Commandline/TUI/TextBox.cs +++ b/Commandline/TUI/TextBox.cs @@ -7,38 +7,42 @@ using CC_Functions.Misc; namespace CC_Functions.Commandline.TUI { /// - /// A basic non-scrolling text-editor control + /// A basic non-scrolling text-editor control /// public class TextBox : Control { /// - /// The text inside this textbox + /// The text inside this textbox /// public string Content; - private string[] Lines - { - get => Content.Split('\n'); - set => Content = string.Join('\n', value); - } + /// - /// The "Cursors" position in this text box + /// The "Cursors" position in this text box /// public Point Cursor = new Point(0, 0); + /// - /// Creates a new text box + /// Creates a new text box /// /// The text inside this text box public TextBox(string content) { Content = content; - Input += (screen, args) => - { - ProcessInput(args.Info.Key, args.Info); - }; + Input += (screen, args) => { ProcessInput(args.Info.Key, args.Info); }; Click += (screen, args) => ProcessInput(ConsoleKey.Enter, new ConsoleKeyInfo()); } + + private string[] Lines + { + get => Content.Split('\n'); + set => Content = string.Join('\n', value); + } + + /// + public override bool Selectable { get; } = true; + /// - /// Function to process input + /// Function to process input /// /// The pressed key /// Input metadata @@ -123,7 +127,7 @@ namespace CC_Functions.Commandline.TUI tmp.RemoveAt(Cursor.Y); lines = tmp.ToArray(); Cursor.Y--; - Cursor.X = tmplen - 1; + Cursor.X = tmplen; } } Lines = lines; @@ -132,7 +136,7 @@ namespace CC_Functions.Commandline.TUI if (lines.Length < Size.Height) { tmp = lines.ToList(); - lines[Cursor.Y] = lines[Cursor.Y].Insert(Cursor.X, "\n"); + lines[Cursor.Y] = lines[Cursor.Y].Insert(Math.Max(Cursor.X, 0), "\n"); Cursor.Y++; Cursor.X = 0; Lines = lines; @@ -142,6 +146,7 @@ namespace CC_Functions.Commandline.TUI if (lines[Cursor.Y].Length < Size.Width) { lines[Cursor.Y] = lines[Cursor.Y].Insert(Cursor.X, info.KeyChar.ToString()); + Cursor.X++; Lines = lines; } break; @@ -152,7 +157,7 @@ namespace CC_Functions.Commandline.TUI public override Pixel[,] Render() { char[,] inp1 = Content.ToNdArray2D(); - inp1 = inp1.Resize(Size.Height, Size.Width - 2); + inp1 = inp1.Resize(Size.Height, Size.Width - 2, SpecialChars.Empty); char[,] inp = new char[Size.Width, Size.Height]; inp.Populate(SpecialChars.Empty); for (int i = 0; i < Size.Height; i++) @@ -160,18 +165,17 @@ namespace CC_Functions.Commandline.TUI inp[0, i] = '['; inp[Size.Width - 1, i] = ']'; } - for (int i = 0; i < Size.Width; i++) inp[i, Size.Height - 1] = '.'; + if (Lines.Length < Size.Width) + for (int i = 0; i < Size.Width; i++) inp[i, Size.Height - 1] = '.'; inp1.Rotate().CopyTo(inp, new Point(0, 1)); if (Selected) - inp[Cursor.X + 1, Cursor.Y] = '▒'; + inp[Math.Max(Cursor.X + 1, 1), Cursor.Y] = '▒'; Pixel[,] output = new Pixel[Size.Height, Size.Width]; + output.Populate(new Pixel(Selected ? ForeColor : BackColor, Selected ? BackColor : ForeColor, SpecialChars.Empty)); for (int x = 0; x < Size.Width; x++) for (int y = 0; y < Size.Height; y++) output[y, x] = new Pixel(Selected ? ForeColor : BackColor, Selected ? BackColor : ForeColor, inp[x, y]); return output; } - - /// - public override bool Selectable { get; } = true; } } \ No newline at end of file diff --git a/Commandline/TableParser.cs b/Commandline/TableParser.cs index 09359c2..38fdf7d 100644 --- a/Commandline/TableParser.cs +++ b/Commandline/TableParser.cs @@ -9,12 +9,13 @@ using System.Text; namespace CC_Functions.Commandline { /// - /// Provides functions for parsing enumerables to powershell-like tables + /// Provides functions for parsing enumerables to powershell-like tables /// public static class TableParser { /// - /// Parses the enumerable to a table using with the specified headers and transformed to strings with the specified selector + /// Parses the enumerable to a table using with the specified headers and transformed to strings with the specified + /// selector /// /// The values to display /// The headers for columns @@ -23,8 +24,9 @@ namespace CC_Functions.Commandline /// The generated table public static string ToStringTable(this IEnumerable values, string[] columnHeaders, params Func[] valueSelectors) => ToStringTable(values.ToArray(), columnHeaders, valueSelectors); + /// - /// Parses the array to a table using with the specified headers and transformed to strings with the specified selector + /// Parses the array to a table using with the specified headers and transformed to strings with the specified selector /// /// The values to display /// The headers for columns @@ -53,8 +55,9 @@ namespace CC_Functions.Commandline return ToStringTable(arrValues); } + /// - /// Parses the array to a table + /// Parses the array to a table /// /// The cells of the table /// The generated table @@ -104,8 +107,9 @@ namespace CC_Functions.Commandline return maxColumnsWidth; } + /// - /// Parses the enumerable to a table, transformed to strings with the specified selector + /// Parses the enumerable to a table, transformed to strings with the specified selector /// /// The values to display /// Functions to get data for the cells diff --git a/Misc/ArrayFormatter.cs b/Misc/ArrayFormatter.cs index b8127cb..931ea3e 100644 --- a/Misc/ArrayFormatter.cs +++ b/Misc/ArrayFormatter.cs @@ -5,12 +5,12 @@ using System.Linq; namespace CC_Functions.Misc { /// - /// Contains extension functions to work with 1D and 2D arrays + /// Contains extension functions to work with 1D and 2D arrays /// public static class ArrayFormatter { /// - /// Copies and resizes the array + /// Copies and resizes the array /// /// The original array. This is not modified /// The new amount of elements @@ -23,8 +23,9 @@ namespace CC_Functions.Misc Array.Resize(ref output, elements); return output; } + /// - /// Copies and resizes the array + /// Copies and resizes the array /// /// The original array. This is not modified /// The new amount of elements in dimension 0 @@ -43,8 +44,9 @@ namespace CC_Functions.Misc newArray[i, j] = original[i, j]; return newArray; } + /// - /// Converts a string to a 2d char array using newlines + /// Converts a string to a 2d char array using newlines /// /// The source string /// The element to place in empty fields of the new array @@ -64,17 +66,20 @@ namespace CC_Functions.Misc } return output; } + /// - /// Clears and fills the array with the specified value + /// Clears and fills the array with the specified value /// /// The array to populate /// The value to copy to the array, defaults to the default value (usually null) /// The type of elements in the array - public static void Populate(this T[] arr, T value = default) { + public static void Populate(this T[] arr, T value = default) + { for (int i = 0; i < arr.Length; i++) arr[i] = value; } + /// - /// Clears and fills the array with the specified value + /// Clears and fills the array with the specified value /// /// The array to populate /// The value to copy to the array, defaults to the default value (usually null) @@ -84,10 +89,12 @@ namespace CC_Functions.Misc int w = arr.GetLength(0); int h = arr.GetLength(1); for (int i = 0; i < w; i++) - for (int j = 0; j < h; j++) arr[i, j] = value; + for (int j = 0; j < h; j++) + arr[i, j] = value; } + /// - /// Copies the content of a 2D array to another with offset + /// Copies the content of a 2D array to another with offset /// /// The array to copy from /// The array to copy to @@ -101,12 +108,14 @@ namespace CC_Functions.Misc int mh = target.GetLength(0); int ow = offset.X; int oh = offset.Y; - for (int x = ow; x < Math.Min(mw, w + ow); x++) - for (int y = oh; y < Math.Min(mh, h + oh); y++) - target[y, x] = arr[y - oh, x - ow]; + if (oh >= 0 && ow >= 0 && mw >= 0 && mh >= 0 && w >= 0 && h >= 0) + for (int x = ow; x < Math.Min(mw, w + ow); x++) + for (int y = oh; y < Math.Min(mh, h + oh); y++) + target[y, x] = arr[y - oh, x - ow]; } + /// - /// Copies and rotates the 2d array (row->column, column->row) + /// Copies and rotates the 2d array (row->column, column->row) /// /// The array to copy from /// The type of elements in the array @@ -117,7 +126,8 @@ namespace CC_Functions.Misc int h = arr.GetLength(1); T[,] target = new T[h, w]; for (int x = 0; x < w; x++) - for (int y = 0; y < h; y++) target[y, x] = arr[x, y]; + for (int y = 0; y < h; y++) + target[y, x] = arr[x, y]; return target; } } diff --git a/Misc/Crypto.cs b/Misc/Crypto.cs index 937aa44..fbeb1a8 100644 --- a/Misc/Crypto.cs +++ b/Misc/Crypto.cs @@ -5,12 +5,12 @@ using System.Security.Cryptography; namespace CC_Functions.Misc { /// - /// Contains cryptographic functions + /// Contains cryptographic functions /// public static class Crypto { /// - /// Encrypts an array of bytes using SHA512. Use with Decrypt + /// Encrypts an array of bytes using SHA512. Use with Decrypt /// /// The array of bytes to encrypt /// The key for encryption, later required to decrypt @@ -49,8 +49,9 @@ namespace CC_Functions.Misc return combined; } + /// - /// Decrypts an SHA512-encrypted byte array. Use with Encrypt + /// Decrypts an SHA512-encrypted byte array. Use with Encrypt /// /// The array of bytes to decrypt /// The key the data was encrypted with diff --git a/Misc/GenericExtensions.cs b/Misc/GenericExtensions.cs index 45a2106..022eed6 100644 --- a/Misc/GenericExtensions.cs +++ b/Misc/GenericExtensions.cs @@ -9,12 +9,12 @@ using System.Net; namespace CC_Functions.Misc { /// - /// Extension methods for various types + /// Extension methods for various types /// public static class GenericExtensions { /// - /// Gets an element from the dictionary or adds the default + /// Gets an element from the dictionary or adds the default /// /// The dictionary to get from /// The key to check @@ -28,8 +28,9 @@ namespace CC_Functions.Misc dict[key] = def; return dict[key]; } + /// - /// Sets an element and returns it + /// Sets an element and returns it /// /// The dictionary to set in /// The key to set at @@ -42,8 +43,9 @@ namespace CC_Functions.Misc dict[key] = val; return dict[key]; } + /// - /// Tries to cast an object + /// Tries to cast an object /// /// The object to try to parse /// The parsed object (if successful) or the default (usually null) @@ -62,8 +64,9 @@ namespace CC_Functions.Misc return false; } } + /// - /// Runs a function that transforms an object in-line + /// Runs a function that transforms an object in-line /// /// The object to run on /// The function to run @@ -71,8 +74,9 @@ namespace CC_Functions.Misc /// The output type /// public static TOut SelectO(this TIn self, Func func) => func.Invoke(self); + /// - /// Runs a function under a condition in-line (equal to if) + /// Runs a function under a condition in-line (equal to if) /// /// The condition to check /// The function to run @@ -81,8 +85,9 @@ namespace CC_Functions.Misc if (condition) func(); } + /// - /// Parses a string to a value of an enum + /// Parses a string to a value of an enum /// /// The string to parse /// The enum type (MUST be an enum) @@ -91,53 +96,60 @@ namespace CC_Functions.Misc Enum.GetNames(typeof(TEnum)).First(s => s.ToLower() == value.ToLower())); /// - /// Parses a string to a nullable bool (defaults to null if parse fails) + /// Parses a string to a nullable bool (defaults to null if parse fails) /// /// The st string to parse /// The output nullable bool public static bool? ParseBool(string value) => - bool.TryParse(value, out bool tmp) ? (bool?)tmp : null; + bool.TryParse(value, out bool tmp) ? (bool?) tmp : null; + /// - /// AND operation for nullable bools (uses True) + /// AND operation for nullable bools (uses True) /// /// First bool to check /// Second bool to check /// The operation result public static bool And(this bool? left, bool? right) => left.True() && right.True(); + /// - /// OR operation for nullable bools (uses True) + /// OR operation for nullable bools (uses True) /// /// First bool to check /// Second bool to check /// The operation result public static bool Or(this bool? left, bool? right) => left.True() || right.True(); + /// - /// XOR operation for nullable bools (uses True) + /// XOR operation for nullable bools (uses True) /// /// First bool to check /// Second bool to check /// The operation result public static bool Xor(this bool? left, bool? right) => left.Or(right) && !left.And(right); + /// - /// Whether the nullable bool is true (null->false) + /// Whether the nullable bool is true (null->false) /// /// Value to check /// Whether it is true public static bool True(this bool? self) => self == true; + /// - /// Whether the nullable bool is false (null->false) + /// Whether the nullable bool is false (null->false) /// /// Value to check /// Whether it is false public static bool False(this bool? self) => self == false; + /// - /// Whether the nullable bool is null + /// Whether the nullable bool is null /// /// Value to check /// Whether it is null public static bool Null(this bool? self) => self == null; + /// - /// Removes an element from a dictionary by its index (not key) + /// Removes an element from a dictionary by its index (not key) /// /// The dictionary to remove from /// The index of the value @@ -145,14 +157,16 @@ namespace CC_Functions.Misc /// The value type public static void RemoveAt(this Dictionary dict, int index) => dict.Remove(dict.Keys.ToArray()[index]); + /// - /// Gets the size of a dictionary + /// Gets the size of a dictionary /// /// The dictionary to check /// The size of the dictionary public static long GetSize(this DirectoryInfo directory) => IO.GetDirectorySize(directory.FullName); + /// - /// Adds a directory to an archive recursively + /// Adds a directory to an archive recursively /// /// The archive to add to /// The directory to add @@ -177,8 +191,9 @@ namespace CC_Functions.Misc ignoredPaths); return result; } + /// - /// "Unshorten" (follow) an URL + /// "Unshorten" (follow) an URL /// /// The URL to unshorten /// The unshortened URL @@ -190,8 +205,9 @@ namespace CC_Functions.Misc WebResponse resp = req.GetResponse(); return resp.ResponseUri; } + /// - /// Pings an URL to check for availability + /// Pings an URL to check for availability /// /// The URL to check /// Whether the service is online @@ -199,7 +215,7 @@ namespace CC_Functions.Misc { try { - HttpWebRequest request = (HttpWebRequest)WebRequest.Create(self); + HttpWebRequest request = (HttpWebRequest) WebRequest.Create(self); request.Timeout = 3000; request.AllowAutoRedirect = true; using WebResponse response = request.GetResponse(); @@ -210,27 +226,31 @@ namespace CC_Functions.Misc return false; } } + /// - /// Rounds a RectangleF to a Rectangle instead of flooring + /// Rounds a RectangleF to a Rectangle instead of flooring /// /// The RectangleF to round /// The rounded Rectangle public static Rectangle Round(this RectangleF self) => Rectangle.Round(self); + /// - /// Ceilings a RectangleF to a Rectangle instead of flooring + /// Ceilings a RectangleF to a Rectangle instead of flooring /// /// The RectangleF to ceil (?) /// The ceiled (?) Rectangle public static Rectangle Ceiling(this RectangleF self) => Rectangle.Ceiling(self); + /// - /// Extension method for Crypto's Encrypt + /// Extension method for Crypto's Encrypt /// /// The data to encrypt /// The key to encrypt with /// The encrypted data public static byte[] Encrypt(this byte[] self, byte[] key) => Crypto.Encrypt(self, key); + /// - /// Extension method for Crypto's Decrypt + /// Extension method for Crypto's Decrypt /// /// The data to decrypt /// The key to decrypt with diff --git a/Misc/HID.cs b/Misc/HID.cs index 85e04ae..bfbac7d 100644 --- a/Misc/HID.cs +++ b/Misc/HID.cs @@ -8,17 +8,18 @@ using System.Text; namespace CC_Functions.Misc { /// - /// Functions for hardware identidiers + /// Functions for hardware identidiers /// public static class Hid { /// - /// Whether to force Win32-based operation + /// Whether to force Win32-based operation /// public static bool ForceWindows = false; + private static byte[] _fingerPrint; - private static readonly string HIDClasses = @"Win32_Processor:UniqueId + private static readonly string HidClasses = @"Win32_Processor:UniqueId Win32_Processor:ProcessorId Win32_Processor:Name Win32_Processor:Manufacturer @@ -33,8 +34,9 @@ Win32_BaseBoard:Manufacturer Win32_BaseBoard:Name Win32_BaseBoard:SerialNumber Win32_NetworkAdapterConfiguration:MACAddress"; + /// - /// The HID for this machine + /// The HID for this machine /// public static byte[] Value { @@ -42,9 +44,13 @@ Win32_NetworkAdapterConfiguration:MACAddress"; { if (_fingerPrint != null) return _fingerPrint; string fingerprintTmp = ""; - if (ForceWindows || new [] {PlatformID.Xbox, PlatformID.Win32S, PlatformID.Win32Windows, PlatformID.Win32NT, PlatformID.WinCE}.Contains(Environment.OSVersion.Platform)) - { - HIDClasses.Split(new[] {"\r\n"}, StringSplitOptions.None).Select(s => + if (ForceWindows || + new[] + { + PlatformID.Xbox, PlatformID.Win32S, PlatformID.Win32Windows, PlatformID.Win32NT, + PlatformID.WinCE + }.Contains(Environment.OSVersion.Platform)) + HidClasses.Split(new[] {"\r\n"}, StringSplitOptions.None).Select(s => { if (s.StartsWith("\n")) s = s.Remove(0, 1); @@ -65,7 +71,6 @@ Win32_NetworkAdapterConfiguration:MACAddress"; Console.WriteLine("Failed to read property"); } }); - } else //Linux implementation. This will not work if you are using Mono on windows or do not have "uname", "lscpu" and "id" available { Process p = new Process @@ -99,15 +104,17 @@ Win32_NetworkAdapterConfiguration:MACAddress"; return _fingerPrint; } } + /// - /// Encrypts data using Crypto's Encrypt and the HID + /// Encrypts data using Crypto's Encrypt and the HID /// /// The data to encrypt /// The encrypted data public static byte[] EncryptLocal(byte[] unencrypted) => Crypto.Encrypt(unencrypted, Value); + /// - /// Decrypts data using Crypto's Decrypt and the HID + /// Decrypts data using Crypto's Decrypt and the HID /// /// The data to decrypt /// The decrypted data diff --git a/Misc/IO.cs b/Misc/IO.cs index 3f40a02..5bf4b0f 100644 --- a/Misc/IO.cs +++ b/Misc/IO.cs @@ -4,12 +4,12 @@ using System.IO; namespace CC_Functions.Misc { /// - /// IO functions + /// IO functions /// public static class IO { /// - /// Recursively gets the size of an directory + /// Recursively gets the size of an directory /// /// The path of the directory /// The size of the directory @@ -21,8 +21,9 @@ namespace CC_Functions.Misc size += new FileInfo(t).Length; return size; } + /// - /// Check whether the paths are equivalent (ignores case) + /// Check whether the paths are equivalent (ignores case) /// /// The first path to check /// The second path to check diff --git a/Misc/SpecialChars.cs b/Misc/SpecialChars.cs index 4483dc1..cfd6390 100644 --- a/Misc/SpecialChars.cs +++ b/Misc/SpecialChars.cs @@ -1,13 +1,156 @@ namespace CC_Functions.Misc { /// - /// Characters for use in CC-Functions.CommandLine + /// Characters for use in CC-Functions.CommandLine /// public static class SpecialChars { /// - /// The space character + /// The space character /// public const char Empty = ' '; + /// + /// Wall with two lines + /// + public static class TwoLineSimple + { + // 1 connectors + /// + /// Wall with specified points + /// + public const char Up = '║'; + /// + /// Wall with specified points + /// + public const char Down = '║'; + /// + /// Wall with specified points + /// + public const char Left = '═'; + /// + /// Wall with specified points + /// + public const char Right = '═'; + + // 2 connectors + /// + /// Wall with specified points + /// + public const char UpDown = '║'; + /// + /// Wall with specified points + /// + public const char LeftRight = '═'; + /// + /// Wall with specified points + /// + public const char DownRight = '╔'; + /// + /// Wall with specified points + /// + public const char UpRight = '╚'; + /// + /// Wall with specified points + /// + public const char DownLeft = '╗'; + /// + /// Wall with specified points + /// + public const char UpLeft = '╝'; + + // 3 connectors + /// + /// Wall with specified points + /// + public const char UpDownLeft = '╣'; + /// + /// Wall with specified points + /// + public const char UpDownRight = '╠'; + /// + /// Wall with specified points + /// + public const char UpLeftRight = '╩'; + /// + /// Wall with specified points + /// + public const char DownLeftRight = '╦'; + + // 4 connectors + /// + /// Wall with specified points + /// + public const char UpDownLeftRight = '╬'; + } + /// + /// Simple line + /// + public static class OneLineSimple + { + // 1 connectors + /// + /// Line with specified points + /// + public const char Up = '╵'; + /// + /// Line with specified points + /// + public const char Down = '╷'; + /// + /// Line with specified points + /// + public const char Left = '╴'; + /// + /// Line with specified points + /// + public const char Right = '╶'; + + // 2 connectors + public const char UpDown = '│'; + /// + /// Line with specified points + /// + public const char LeftRight = '─'; + /// + /// Line with specified points + /// + public const char DownRight = '┌'; + /// + /// Line with specified points + /// + public const char UpRight = '└'; + /// + /// Line with specified points + /// + public const char DownLeft = '┐'; + /// + /// Line with specified points + /// + public const char UpLeft = '┘'; + + // 3 connectors + /// + /// Line with specified points + /// + public const char UpDownLeft = '┤'; + /// + /// Line with specified points + /// + public const char UpDownRight = '├'; + /// + /// Line with specified points + /// + public const char UpLeftRight = '┴'; + /// + /// Line with specified points + /// + public const char DownLeftRight = '┬'; + + // 4 connectors + /// + /// Line with specified points + /// + public const char UpDownLeftRight = '┼'; + } } } \ No newline at end of file diff --git a/W32.Test/MainForm.cs b/W32.Test/MainForm.cs index 8392c55..8dbd9bd 100644 --- a/W32.Test/MainForm.cs +++ b/W32.Test/MainForm.cs @@ -1,10 +1,5 @@ -using System; -using System.Drawing; -using System.Linq; -using System.Windows.Forms; -using CC_Functions.Misc; +using CC_Functions.W32.DCDrawer; using CC_Functions.W32.Forms; -using CC_Functions.W32.DCDrawer; using CC_Functions.W32.Hooks; using static CC_Functions.W32.Power; @@ -14,6 +9,8 @@ namespace CC_Functions.W32.Test { private static Wnd32 _tmpWnd32Obj; private static MainForm _mainF; + + private static Wnd32 _wndSelectMouseCurrent; private readonly KeyboardHook _kHook; private readonly MouseHook _mHook; private readonly Label[] _readerLabels; @@ -101,13 +98,13 @@ namespace CC_Functions.W32.Test FormBorderStyle = FormBorderStyle.None, WindowState = FormWindowState.Maximized }; - Label lab = new Label { AutoSize = true }; + Label lab = new Label {AutoSize = true}; frm.Controls.Add(lab); - Panel pan = new Panel { BackColor = Color.Red }; + Panel pan = new Panel {BackColor = Color.Red}; frm.Controls.Add(pan); Wnd32[] children = TmpWnd.Children; - void UpdateGUI(Point labelPosition) + void UpdateGui(Point labelPosition) { lab.Text = $"{_wndSelectMouseCurrent.Title} ({_wndSelectMouseCurrent.HWnd})"; lab.Location = new Point(labelPosition.X + 5, labelPosition.Y + 5); @@ -116,11 +113,11 @@ namespace CC_Functions.W32.Test void MouseEventHandler(object sender1, MouseEventArgs e1) { - Func checkWnd = (s) => s.Position.Contains(e1.Location); + Func checkWnd = s => s.Position.Contains(e1.Location); if (children.Any(checkWnd)) { _wndSelectMouseCurrent = children.First(checkWnd); - UpdateGUI(Cursor.Position); + UpdateGui(Cursor.Position); } } @@ -151,7 +148,7 @@ namespace CC_Functions.W32.Test tmp = children.Length; tmp--; _wndSelectMouseCurrent = children[tmp]; - UpdateGUI(_wndSelectMouseCurrent.Position.Location); + UpdateGui(_wndSelectMouseCurrent.Position.Location); break; case Keys.Down: case Keys.Right: @@ -160,7 +157,7 @@ namespace CC_Functions.W32.Test if (tmp == children.Length) tmp = 0; _wndSelectMouseCurrent = children[tmp]; - UpdateGUI(_wndSelectMouseCurrent.Position.Location); + UpdateGui(_wndSelectMouseCurrent.Position.Location); break; } } @@ -172,7 +169,7 @@ namespace CC_Functions.W32.Test pan.MouseMove += MouseEventHandler; lab.MouseMove += MouseEventHandler; frm.KeyDown += KeyEventHandler; - UpdateGUI(Cursor.Position); + UpdateGui(Cursor.Position); frm.Show(); _wndSelectMouseCurrent = frm.GetWnd32(); Cursor.Position = Cursor.Position; @@ -263,7 +260,6 @@ namespace CC_Functions.W32.Test private void Wnd_action_destroy_Click(object sender, EventArgs e) => TmpWnd.Destroy(); - private static Wnd32 _wndSelectMouseCurrent; private void Wnd_select_mouse_Click(object sender, EventArgs e) { WindowState = FormWindowState.Minimized; @@ -281,7 +277,7 @@ namespace CC_Functions.W32.Test Panel pan = new Panel {BackColor = Color.Red}; frm.Controls.Add(pan); - void UpdateGUI(Point labelPosition) + void UpdateGui(Point labelPosition) { lab.Text = $"{_wndSelectMouseCurrent.Title} ({_wndSelectMouseCurrent.HWnd})"; lab.Location = new Point(labelPosition.X + 5, labelPosition.Y + 5); @@ -291,7 +287,7 @@ namespace CC_Functions.W32.Test void MouseEventHandler(object sender1, MouseEventArgs e1) { _wndSelectMouseCurrent = Wnd32.AllFromPoint(MousePosition, true).First(s => s != frm.GetWnd32()); - UpdateGUI(Cursor.Position); + UpdateGui(Cursor.Position); } void EventHandler(object sender1, EventArgs e1) @@ -390,12 +386,12 @@ namespace CC_Functions.W32.Test } private static PointF MakePoint(float xPercent, float yPercent) => new PointF( - (Screen.PrimaryScreen.Bounds.Width * xPercent) / 100, - (Screen.PrimaryScreen.Bounds.Height * yPercent) / 100); + Screen.PrimaryScreen.Bounds.Width * xPercent / 100, + Screen.PrimaryScreen.Bounds.Height * yPercent / 100); private static SizeF MakeSizeY(float xPercent, float yPercent) => new SizeF( - (Screen.PrimaryScreen.Bounds.Height * xPercent) / 100, - (Screen.PrimaryScreen.Bounds.Height * yPercent) / 100); + Screen.PrimaryScreen.Bounds.Height * xPercent / 100, + Screen.PrimaryScreen.Bounds.Height * yPercent / 100); private void desk_set_Click(object sender, EventArgs e) { diff --git a/W32.Test/Program.cs b/W32.Test/Program.cs index cc7f833..156eea9 100644 --- a/W32.Test/Program.cs +++ b/W32.Test/Program.cs @@ -1,7 +1,4 @@ -using System; -using System.Windows.Forms; - -namespace CC_Functions.W32.Test +namespace CC_Functions.W32.Test { internal static class Program { diff --git a/W32/DCDrawer/DCBuffered.cs b/W32/DCDrawer/DCBuffered.cs index 218de19..1630eac 100644 --- a/W32/DCDrawer/DCBuffered.cs +++ b/W32/DCDrawer/DCBuffered.cs @@ -1,8 +1,4 @@ -using System; -using System.Drawing; -using System.Windows.Forms; - -namespace CC_Functions.W32.DCDrawer +namespace CC_Functions.W32.DCDrawer { public class DCBuffered : IDCDrawer { @@ -20,6 +16,8 @@ namespace CC_Functions.W32.DCDrawer Graphics = buffer.Graphics; } + public Graphics Graphics { get; } + public void Dispose() { buffer.Render(drawer.Graphics); @@ -27,7 +25,5 @@ namespace CC_Functions.W32.DCDrawer buffer.Dispose(); drawer.Dispose(); } - - public Graphics Graphics { get; } } } \ No newline at end of file diff --git a/W32/DCDrawer/DCUnbuffered.cs b/W32/DCDrawer/DCUnbuffered.cs index 2010dd0..a692aef 100644 --- a/W32/DCDrawer/DCUnbuffered.cs +++ b/W32/DCDrawer/DCUnbuffered.cs @@ -1,6 +1,4 @@ -using System; -using System.Drawing; -using CC_Functions.W32.Native; +using CC_Functions.W32.Native; namespace CC_Functions.W32.DCDrawer { diff --git a/W32/DCDrawer/IDCDrawer.cs b/W32/DCDrawer/IDCDrawer.cs index d1788df..d312da0 100644 --- a/W32/DCDrawer/IDCDrawer.cs +++ b/W32/DCDrawer/IDCDrawer.cs @@ -1,7 +1,4 @@ -using System; -using System.Drawing; - -namespace CC_Functions.W32.DCDrawer +namespace CC_Functions.W32.DCDrawer { public interface IDCDrawer : IDisposable { diff --git a/W32/DeskMan.cs b/W32/DeskMan.cs index e620420..376680d 100644 --- a/W32/DeskMan.cs +++ b/W32/DeskMan.cs @@ -1,10 +1,5 @@ -using System; -using System.Drawing; -using System.Drawing.Imaging; -using System.IO; -using CC_Functions.W32.DCDrawer; +using CC_Functions.W32.DCDrawer; using CC_Functions.W32.Native; -using Microsoft.Win32; namespace CC_Functions.W32 { @@ -16,10 +11,9 @@ namespace CC_Functions.W32 { using (Bitmap bmpTemp = new Bitmap( - $@"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\Microsoft\Windows\Themes\TranscodedWallpaper")) - { + $@"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\Microsoft\Windows\Themes\TranscodedWallpaper") + ) return (Image) bmpTemp.Clone(); - } } set { diff --git a/W32/Forms/DataGridViewNumericUpDownCell.cs b/W32/Forms/DataGridViewNumericUpDownCell.cs index a56fce9..e0a0b7f 100644 --- a/W32/Forms/DataGridViewNumericUpDownCell.cs +++ b/W32/Forms/DataGridViewNumericUpDownCell.cs @@ -1,11 +1,3 @@ -using System; -using System.ComponentModel; -using System.Diagnostics; -using System.Drawing; -using System.Globalization; -using System.Runtime.InteropServices; -using System.Windows.Forms; - namespace CC_Functions.W32.Forms { public class DataGridViewNumericUpDownCell : DataGridViewTextBoxCell @@ -399,7 +391,7 @@ namespace CC_Functions.W32.Forms negativeSignKey = (Keys) VkKeyScan(negativeSignStr[0]); if ((char.IsDigit((char) e.KeyCode) || - (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) || + e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9 || negativeSignKey == e.KeyCode || Keys.Subtract == e.KeyCode) && !e.Shift && !e.Alt && !e.Control) diff --git a/W32/Forms/DataGridViewNumericUpDownColumn.cs b/W32/Forms/DataGridViewNumericUpDownColumn.cs index 42a0a53..bb4219b 100644 --- a/W32/Forms/DataGridViewNumericUpDownColumn.cs +++ b/W32/Forms/DataGridViewNumericUpDownColumn.cs @@ -1,9 +1,3 @@ -using System; -using System.ComponentModel; -using System.Globalization; -using System.Text; -using System.Windows.Forms; - namespace CC_Functions.W32.Forms { /// diff --git a/W32/Forms/DataGridViewNumericUpDownEditingControl.cs b/W32/Forms/DataGridViewNumericUpDownEditingControl.cs index 706fa9c..1686055 100644 --- a/W32/Forms/DataGridViewNumericUpDownEditingControl.cs +++ b/W32/Forms/DataGridViewNumericUpDownEditingControl.cs @@ -1,9 +1,3 @@ -using System; -using System.Drawing; -using System.Globalization; -using System.Runtime.InteropServices; -using System.Windows.Forms; - namespace CC_Functions.W32.Forms { /// @@ -86,9 +80,7 @@ namespace CC_Functions.W32.Forms dataGridView.EditingPanel.BackColor = opaqueBackColor; } else - { BackColor = dataGridViewCellStyle.BackColor; - } ForeColor = dataGridViewCellStyle.ForeColor; TextAlign = DataGridViewNumericUpDownCell.TranslateAlignment(dataGridViewCellStyle.Alignment); @@ -108,10 +100,10 @@ namespace CC_Functions.W32.Forms if (textBox != null) // If the end of the selection is at the end of the string, // let the DataGridView treat the key message - if ((RightToLeft == RightToLeft.No && - !(textBox.SelectionLength == 0 && textBox.SelectionStart == textBox.Text.Length)) || - (RightToLeft == RightToLeft.Yes && - !(textBox.SelectionLength == 0 && textBox.SelectionStart == 0))) + if (RightToLeft == RightToLeft.No && + !(textBox.SelectionLength == 0 && textBox.SelectionStart == textBox.Text.Length) || + RightToLeft == RightToLeft.Yes && + !(textBox.SelectionLength == 0 && textBox.SelectionStart == 0)) return true; break; } @@ -123,10 +115,10 @@ namespace CC_Functions.W32.Forms // If the end of the selection is at the begining of the string // or if the entire text is selected and we did not start editing, // send this character to the dataGridView, else process the key message - if ((RightToLeft == RightToLeft.No && - !(textBox.SelectionLength == 0 && textBox.SelectionStart == 0)) || - (RightToLeft == RightToLeft.Yes && - !(textBox.SelectionLength == 0 && textBox.SelectionStart == textBox.Text.Length))) + if (RightToLeft == RightToLeft.No && + !(textBox.SelectionLength == 0 && textBox.SelectionStart == 0) || + RightToLeft == RightToLeft.Yes && + !(textBox.SelectionLength == 0 && textBox.SelectionStart == textBox.Text.Length)) return true; break; } @@ -236,9 +228,7 @@ namespace CC_Functions.W32.Forms // the negative sign is pressed. bool notifyValueChange = false; if (char.IsDigit(e.KeyChar)) - { notifyValueChange = true; - } else { NumberFormatInfo numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat; diff --git a/W32/Forms/Extensions.cs b/W32/Forms/Extensions.cs index 2249459..6829123 100644 --- a/W32/Forms/Extensions.cs +++ b/W32/Forms/Extensions.cs @@ -1,9 +1,4 @@ -using System; -using System.Linq.Expressions; -using System.Reflection; -using System.Windows.Forms; - -namespace CC_Functions.W32.Forms +namespace CC_Functions.W32.Forms { public delegate void SetPropertyDelegate(TCtl control, Expression> propexpr, TProp value) where TCtl : Control; diff --git a/W32/Forms/RotatingIndicator.cs b/W32/Forms/RotatingIndicator.cs index 764ab9d..4e3f127 100644 --- a/W32/Forms/RotatingIndicator.cs +++ b/W32/Forms/RotatingIndicator.cs @@ -1,9 +1,4 @@ -using System; -using System.ComponentModel; -using System.Drawing; -using System.Drawing.Drawing2D; -using Timer = System.Timers.Timer; -using System.Windows.Forms; +using Timer = System.Timers.Timer; namespace CC_Functions.W32.Forms { @@ -15,7 +10,7 @@ namespace CC_Functions.W32.Forms private const double IndicatorOffset = Math.PI / 16; private const int MaximumIndicators = 6; private const int SizeFactor = 20; - private const double StartAt = (2 * Math.PI) / 3; + private const double StartAt = 2 * Math.PI / 3; private const double TimerInterval = 100.0; private readonly Indicator[] indicators = new Indicator[MaximumIndicators]; private readonly Timer timer; @@ -28,7 +23,7 @@ namespace CC_Functions.W32.Forms public RotatingIndicator() { for (int i = 0; i < 6; i++) - indicators[i] = new Indicator(StartAt + (i * IndicatorOffset)); + indicators[i] = new Indicator(StartAt + i * IndicatorOffset); SetStyle( ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor, true); diff --git a/W32/Forms/SelectBox.Designer.cs b/W32/Forms/SelectBox.Designer.cs index b46e572..2fdc0f2 100644 --- a/W32/Forms/SelectBox.Designer.cs +++ b/W32/Forms/SelectBox.Designer.cs @@ -1,6 +1,4 @@ -using System.Windows.Forms; - -namespace CC_Functions.W32.Forms +namespace CC_Functions.W32.Forms { partial class SelectBox { diff --git a/W32/Forms/SelectBox.cs b/W32/Forms/SelectBox.cs index 17b1746..dea9315 100644 --- a/W32/Forms/SelectBox.cs +++ b/W32/Forms/SelectBox.cs @@ -1,8 +1,4 @@ -using System; -using System.Linq; -using System.Windows.Forms; - -namespace CC_Functions.W32.Forms +namespace CC_Functions.W32.Forms { internal partial class SelectBox : Form { diff --git a/W32/GenericExtensions.cs b/W32/GenericExtensions.cs index 7cc836c..5813aaa 100644 --- a/W32/GenericExtensions.cs +++ b/W32/GenericExtensions.cs @@ -1,8 +1,4 @@ -using System; -using System.Diagnostics; -using System.Windows.Forms; - -namespace CC_Functions.W32 +namespace CC_Functions.W32 { public static class GenericExtensions { diff --git a/W32/Hooks/KeyboardHook.cs b/W32/Hooks/KeyboardHook.cs index d729bff..e1984e8 100644 --- a/W32/Hooks/KeyboardHook.cs +++ b/W32/Hooks/KeyboardHook.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Runtime.InteropServices; -using System.Windows.Forms; -using CC_Functions.W32.Native; +using CC_Functions.W32.Native; namespace CC_Functions.W32.Hooks { @@ -38,9 +33,7 @@ namespace CC_Functions.W32.Hooks { using (Process curProcess = Process.GetCurrentProcess()) using (ProcessModule curModule = curProcess.MainModule) - { return user32.SetWindowsHookEx(WH_KEYBOARD_LL, proc, kernel32.GetModuleHandle(curModule.ModuleName), 0); - } } private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) diff --git a/W32/Hooks/KeyboardHookEventArgs.cs b/W32/Hooks/KeyboardHookEventArgs.cs index cff559f..c9305ad 100644 --- a/W32/Hooks/KeyboardHookEventArgs.cs +++ b/W32/Hooks/KeyboardHookEventArgs.cs @@ -1,7 +1,4 @@ -using System; -using System.Windows.Forms; - -namespace CC_Functions.W32.Hooks +namespace CC_Functions.W32.Hooks { public sealed class KeyboardHookEventArgs : EventArgs { diff --git a/W32/Hooks/MouseHook.cs b/W32/Hooks/MouseHook.cs index ca5c497..2b8b5ab 100644 --- a/W32/Hooks/MouseHook.cs +++ b/W32/Hooks/MouseHook.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Drawing; -using System.Runtime.InteropServices; -using CC_Functions.W32.Native; +using CC_Functions.W32.Native; namespace CC_Functions.W32.Hooks { @@ -47,9 +42,7 @@ namespace CC_Functions.W32.Hooks { using (Process curProcess = Process.GetCurrentProcess()) using (ProcessModule curModule = curProcess.MainModule) - { return user32.SetWindowsHookEx(WH_MOUSE_LL, proc, kernel32.GetModuleHandle(curModule.ModuleName), 0); - } } private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) diff --git a/W32/Hooks/MouseHookEventArgs.cs b/W32/Hooks/MouseHookEventArgs.cs index 08a0e3c..fd66614 100644 --- a/W32/Hooks/MouseHookEventArgs.cs +++ b/W32/Hooks/MouseHookEventArgs.cs @@ -1,7 +1,4 @@ -using System; -using System.Drawing; - -namespace CC_Functions.W32.Hooks +namespace CC_Functions.W32.Hooks { public class MouseHookEventArgs : EventArgs { diff --git a/W32/KeyboardReader.cs b/W32/KeyboardReader.cs index 2a4b4f8..2b180f3 100644 --- a/W32/KeyboardReader.cs +++ b/W32/KeyboardReader.cs @@ -1,5 +1,4 @@ -using System.Windows.Forms; -using CC_Functions.W32.Native; +using CC_Functions.W32.Native; namespace CC_Functions.W32 { diff --git a/W32/Mouse.cs b/W32/Mouse.cs index 8e476f4..3612a86 100644 --- a/W32/Mouse.cs +++ b/W32/Mouse.cs @@ -1,6 +1,4 @@ -using System.Drawing; -using System.Windows.Forms; -using CC_Functions.W32.Native; +using CC_Functions.W32.Native; namespace CC_Functions.W32 { diff --git a/W32/Native/RECT.cs b/W32/Native/RECT.cs index 90d6f45..23c5fac 100644 --- a/W32/Native/RECT.cs +++ b/W32/Native/RECT.cs @@ -1,6 +1,4 @@ -using System.Runtime.InteropServices; - -namespace CC_Functions.W32.Native +namespace CC_Functions.W32.Native { [StructLayout(LayoutKind.Sequential)] public struct RECT diff --git a/W32/Native/advapi32.cs b/W32/Native/advapi32.cs index 24ba804..cf29e88 100644 --- a/W32/Native/advapi32.cs +++ b/W32/Native/advapi32.cs @@ -1,7 +1,4 @@ -using System; -using System.Runtime.InteropServices; - -namespace CC_Functions.W32.Native +namespace CC_Functions.W32.Native { internal static class advapi32 { diff --git a/W32/Native/gdi32.cs b/W32/Native/gdi32.cs index 1de79a6..a34a18f 100644 --- a/W32/Native/gdi32.cs +++ b/W32/Native/gdi32.cs @@ -1,7 +1,4 @@ -using System; -using System.Runtime.InteropServices; - -namespace CC_Functions.W32.Native +namespace CC_Functions.W32.Native { internal static class gdi32 { diff --git a/W32/Native/kernel32.cs b/W32/Native/kernel32.cs index 5b078ab..5fe54c7 100644 --- a/W32/Native/kernel32.cs +++ b/W32/Native/kernel32.cs @@ -1,7 +1,4 @@ -using System; -using System.Runtime.InteropServices; - -namespace CC_Functions.W32.Native +namespace CC_Functions.W32.Native { internal static class kernel32 { diff --git a/W32/Native/ntdll.cs b/W32/Native/ntdll.cs index 1a8141e..eefb190 100644 --- a/W32/Native/ntdll.cs +++ b/W32/Native/ntdll.cs @@ -1,7 +1,4 @@ -using System; -using System.Runtime.InteropServices; - -namespace CC_Functions.W32.Native +namespace CC_Functions.W32.Native { internal static class ntdll { diff --git a/W32/Native/shell32.cs b/W32/Native/shell32.cs index 3170ac6..10df960 100644 --- a/W32/Native/shell32.cs +++ b/W32/Native/shell32.cs @@ -1,7 +1,4 @@ -using System; -using System.Runtime.InteropServices; - -namespace CC_Functions.W32.Native +namespace CC_Functions.W32.Native { internal static class shell32 { diff --git a/W32/Native/user32.cs b/W32/Native/user32.cs index 779dd28..48ab606 100644 --- a/W32/Native/user32.cs +++ b/W32/Native/user32.cs @@ -1,14 +1,11 @@ -using System; -using System.Runtime.InteropServices; -using System.Text; - -namespace CC_Functions.W32.Native +namespace CC_Functions.W32.Native { internal static class user32 { - public delegate bool EnumWindowProc(IntPtr hWnd, IntPtr lParam); public delegate bool EnumDelegate(IntPtr hWnd, int lParam); + public delegate bool EnumWindowProc(IntPtr hWnd, IntPtr lParam); + public delegate IntPtr LowLevelProc(int nCode, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] @@ -130,7 +127,7 @@ namespace CC_Functions.W32.Native [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo); - + [DllImport("user32")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr lParam); diff --git a/W32/Power.cs b/W32/Power.cs index 6643e2f..c05f136 100644 --- a/W32/Power.cs +++ b/W32/Power.cs @@ -1,5 +1,4 @@ -using System; -using CC_Functions.W32.Native; +using CC_Functions.W32.Native; using static CC_Functions.W32.Privileges; namespace CC_Functions.W32 diff --git a/W32/Privileges.cs b/W32/Privileges.cs index 300c10b..fc76f3f 100644 --- a/W32/Privileges.cs +++ b/W32/Privileges.cs @@ -1,8 +1,4 @@ -using System; -using System.ComponentModel; -using System.Globalization; -using System.Runtime.InteropServices; -using CC_Functions.W32.Native; +using CC_Functions.W32.Native; namespace CC_Functions.W32 { @@ -124,18 +120,14 @@ namespace CC_Functions.W32 new Win32Exception()); } else - { throw new InvalidOperationException("AdjustTokenPrivileges failed.", new Win32Exception()); - } } else - { throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "OpenProcessToken failed. CurrentProcess: {0}", currentProcess.ToInt32()), new Win32Exception()); - } } finally { @@ -144,12 +136,10 @@ namespace CC_Functions.W32 } } else - { throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "LookupPrivilegeValue failed. SecurityEntityValue: {0}", securityEntityValue), new Win32Exception()); - } } catch (Exception e) { diff --git a/W32/ScreenMan.cs b/W32/ScreenMan.cs index 67b4ada..9304864 100644 --- a/W32/ScreenMan.cs +++ b/W32/ScreenMan.cs @@ -1,7 +1,4 @@ -using System; -using System.Drawing; -using System.Windows.Forms; -using CC_Functions.W32.DCDrawer; +using CC_Functions.W32.DCDrawer; using CC_Functions.W32.Native; namespace CC_Functions.W32 @@ -30,10 +27,7 @@ namespace CC_Functions.W32 public static void Draw(Image img) { - using (IDCDrawer drawerBuffered = GetDrawer()) - { - drawerBuffered.Graphics.DrawImage(img, GetBounds()); - } + using (IDCDrawer drawerBuffered = GetDrawer()) drawerBuffered.Graphics.DrawImage(img, GetBounds()); } public static IDCDrawer GetDrawer(bool buffer = true) diff --git a/W32/Security.cs b/W32/Security.cs index bd5414d..c07b7e4 100644 --- a/W32/Security.cs +++ b/W32/Security.cs @@ -1,6 +1,4 @@ -using System.Security.Principal; - -namespace CC_Functions.W32 +namespace CC_Functions.W32 { public static class MiscFunctions { diff --git a/W32/Time.cs b/W32/Time.cs index b6efb67..688bc36 100644 --- a/W32/Time.cs +++ b/W32/Time.cs @@ -1,5 +1,4 @@ -using System; -using CC_Functions.W32.Native; +using CC_Functions.W32.Native; namespace CC_Functions.W32 { diff --git a/W32/Wnd32.cs b/W32/Wnd32.cs index 606c285..ed82510 100644 --- a/W32/Wnd32.cs +++ b/W32/Wnd32.cs @@ -1,13 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; -using System.Drawing; -using System.Linq; -using System.Runtime.InteropServices; -using System.Text; -using System.Windows.Forms; -using CC_Functions.W32.Native; +using CC_Functions.W32.Native; namespace CC_Functions.W32 { @@ -16,10 +7,8 @@ namespace CC_Functions.W32 /// public sealed class Wnd32 : IEquatable { - #region Exposed - - #region CreateInstance - +#region Exposed +#region CreateInstance private Wnd32(IntPtr handle) => HWnd = handle; /// @@ -61,7 +50,8 @@ namespace CC_Functions.W32 /// The point to scan /// Whether windows need to be visible /// The windows - public static Wnd32[] AllFromPoint(Point point, bool visible = false) => All.Where(s => s.Position.Contains(point) && s.Shown || !visible).ToArray(); + public static Wnd32[] AllFromPoint(Point point, bool visible = false) => + All.Where(s => s.Position.Contains(point) && s.Shown || !visible).ToArray(); /// /// Gets the window associated with the forms handle @@ -100,11 +90,9 @@ namespace CC_Functions.W32 /// The current programs console window. Do NOT use this if you are not targeting a console app or allocating a console /// public static Wnd32 ConsoleWindow => FromHandle(kernel32.GetConsoleWindow()); +#endregion CreateInstance - #endregion CreateInstance - - #region InstanceActions - +#region InstanceActions public Wnd32[] Children { get @@ -357,13 +345,10 @@ namespace CC_Functions.W32 return true; } } +#endregion InstanceActions +#endregion Exposed - #endregion InstanceActions - - #endregion Exposed - - #region Internal - +#region Internal /// /// The windows' handle /// @@ -378,7 +363,7 @@ namespace CC_Functions.W32 _windowHandles.Add(hWnd); return true; } - + private bool EnumWindow(IntPtr hWnd, IntPtr lParam) { GCHandle gcChildhandlesList = GCHandle.FromIntPtr(lParam); @@ -390,7 +375,6 @@ namespace CC_Functions.W32 return true; } - - #endregion Internal +#endregion Internal } } \ No newline at end of file