diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..88620c5 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,2 @@ +# Default ignored files +/.idea.CC-Functions/.idea/workspace.xml diff --git a/.idea/.idea.CC-Functions/.idea/encodings.xml b/.idea/.idea.CC-Functions/.idea/encodings.xml new file mode 100644 index 0000000..df87cf9 --- /dev/null +++ b/.idea/.idea.CC-Functions/.idea/encodings.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/.idea.CC-Functions/.idea/indexLayout.xml b/.idea/.idea.CC-Functions/.idea/indexLayout.xml new file mode 100644 index 0000000..27ba142 --- /dev/null +++ b/.idea/.idea.CC-Functions/.idea/indexLayout.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/.idea.CC-Functions/.idea/markdown-navigator-enh.xml b/.idea/.idea.CC-Functions/.idea/markdown-navigator-enh.xml new file mode 100644 index 0000000..fccc02e --- /dev/null +++ b/.idea/.idea.CC-Functions/.idea/markdown-navigator-enh.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/.idea.CC-Functions/.idea/markdown-navigator.xml b/.idea/.idea.CC-Functions/.idea/markdown-navigator.xml new file mode 100644 index 0000000..2b999b9 --- /dev/null +++ b/.idea/.idea.CC-Functions/.idea/markdown-navigator.xml @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/.idea.CC-Functions/.idea/projectSettingsUpdater.xml b/.idea/.idea.CC-Functions/.idea/projectSettingsUpdater.xml new file mode 100644 index 0000000..7515e76 --- /dev/null +++ b/.idea/.idea.CC-Functions/.idea/projectSettingsUpdater.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/.idea.CC-Functions/.idea/vcs.xml b/.idea/.idea.CC-Functions/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/.idea.CC-Functions/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Misc/DataGridViewNumericUpDownColumn.cs b/Misc/DataGridViewNumericUpDownColumn.cs index 28cf13c..ec337b1 100644 --- a/Misc/DataGridViewNumericUpDownColumn.cs +++ b/Misc/DataGridViewNumericUpDownColumn.cs @@ -7,81 +7,74 @@ using System.Windows.Forms; namespace GradeCalc { /// - /// Custom column type dedicated to the DataGridViewNumericUpDownCell cell type. + /// Custom column type dedicated to the DataGridViewNumericUpDownCell cell type. /// public class DataGridViewNumericUpDownColumn : DataGridViewColumn { /// - /// Constructor for the DataGridViewNumericUpDownColumn class. + /// Constructor for the DataGridViewNumericUpDownColumn class. /// public DataGridViewNumericUpDownColumn() : base(new DataGridViewNumericUpDownCell()) { } /// - /// Represents the implicit cell that gets cloned when adding rows to the grid. + /// Represents the implicit cell that gets cloned when adding rows to the grid. /// - [ - Browsable(false), - DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) - ] + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override DataGridViewCell CellTemplate { - get { - return base.CellTemplate; - } - set { - DataGridViewNumericUpDownCell dataGridViewNumericUpDownCell = value as DataGridViewNumericUpDownCell; + get => base.CellTemplate; + set + { + var dataGridViewNumericUpDownCell = value as DataGridViewNumericUpDownCell; if (value != null && dataGridViewNumericUpDownCell == null) - { - throw new InvalidCastException("Value provided for CellTemplate must be of type DataGridViewNumericUpDownElements.DataGridViewNumericUpDownCell or derive from it."); - } + throw new InvalidCastException( + "Value provided for CellTemplate must be of type DataGridViewNumericUpDownElements.DataGridViewNumericUpDownCell or derive from it."); base.CellTemplate = value; } } /// - /// Replicates the DecimalPlaces property of the DataGridViewNumericUpDownCell cell type. + /// Replicates the DecimalPlaces property of the DataGridViewNumericUpDownCell cell type. /// - [ - Category("Appearance"), - DefaultValue(DataGridViewNumericUpDownCell.DATAGRIDVIEWNUMERICUPDOWNCELL_defaultDecimalPlaces), - Description("Indicates the number of decimal places to display.") - ] + [Category("Appearance")] + [DefaultValue(DataGridViewNumericUpDownCell.DATAGRIDVIEWNUMERICUPDOWNCELL_defaultDecimalPlaces)] + [Description("Indicates the number of decimal places to display.")] public int DecimalPlaces { - get { + get + { if (NumericUpDownCellTemplate == null) - { - throw new InvalidOperationException("Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); - } + throw new InvalidOperationException( + "Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); return NumericUpDownCellTemplate.DecimalPlaces; } - set { + set + { if (NumericUpDownCellTemplate == null) - { - throw new InvalidOperationException("Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); - } + throw new InvalidOperationException( + "Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); // Update the template cell so that subsequent cloned cells use the new value. NumericUpDownCellTemplate.DecimalPlaces = value; if (DataGridView != null) { // Update all the existing DataGridViewNumericUpDownCell cells in the column accordingly. - DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; - int rowCount = dataGridViewRows.Count; - for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) + var dataGridViewRows = DataGridView.Rows; + var rowCount = dataGridViewRows.Count; + for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) { // Be careful not to unshare rows unnecessarily. // This could have severe performance repercussions. - DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewNumericUpDownCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewNumericUpDownCell; + var dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); + var dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewNumericUpDownCell; if (dataGridViewCell != null) - { // Call the internal SetDecimalPlaces method instead of the property to avoid invalidation // of each cell. The whole column is invalidated later in a single operation for better performance. dataGridViewCell.SetDecimalPlaces(rowIndex, value); - } } + DataGridView.InvalidateColumn(Index); // TODO: Call the grid's autosizing methods to autosize the column, rows, column headers / row headers as needed. } @@ -89,144 +82,176 @@ namespace GradeCalc } /// - /// Replicates the Increment property of the DataGridViewNumericUpDownCell cell type. + /// Replicates the Increment property of the DataGridViewNumericUpDownCell cell type. /// - [ - Category("Data"), - Description("Indicates the amount to increment or decrement on each button click.") - ] + [Category("Data")] + [Description("Indicates the amount to increment or decrement on each button click.")] public decimal Increment { - get { + get + { if (NumericUpDownCellTemplate == null) - { - throw new InvalidOperationException("Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); - } + throw new InvalidOperationException( + "Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); return NumericUpDownCellTemplate.Increment; } - set { + set + { if (NumericUpDownCellTemplate == null) - { - throw new InvalidOperationException("Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); - } + throw new InvalidOperationException( + "Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); NumericUpDownCellTemplate.Increment = value; if (DataGridView != null) { - DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; - int rowCount = dataGridViewRows.Count; - for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) + var dataGridViewRows = DataGridView.Rows; + var rowCount = dataGridViewRows.Count; + for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) { - DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewNumericUpDownCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewNumericUpDownCell; - if (dataGridViewCell != null) - { - dataGridViewCell.SetIncrement(rowIndex, value); - } + var dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); + var dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewNumericUpDownCell; + if (dataGridViewCell != null) dataGridViewCell.SetIncrement(rowIndex, value); } } } } + /// + /// Replicates the Maximum property of the DataGridViewNumericUpDownCell cell type. + /// + [Category("Data")] + [Description("Indicates the maximum value for the numeric up-down cells.")] + [RefreshProperties(RefreshProperties.All)] + public decimal Maximum + { + get + { + if (NumericUpDownCellTemplate == null) + throw new InvalidOperationException( + "Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); + return NumericUpDownCellTemplate.Maximum; + } + set + { + if (NumericUpDownCellTemplate == null) + throw new InvalidOperationException( + "Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); + NumericUpDownCellTemplate.Maximum = value; + if (DataGridView != null) + { + var dataGridViewRows = DataGridView.Rows; + var rowCount = dataGridViewRows.Count; + for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) + { + var dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); + var dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewNumericUpDownCell; + if (dataGridViewCell != null) dataGridViewCell.SetMaximum(rowIndex, value); + } + + DataGridView.InvalidateColumn(Index); + // TODO: This column and/or grid rows may need to be autosized depending on their + // autosize settings. Call the autosizing methods to autosize the column, rows, + // column headers / row headers as needed. + } + } + } + + /// + /// Replicates the Minimum property of the DataGridViewNumericUpDownCell cell type. + /// + [Category("Data")] + [Description("Indicates the minimum value for the numeric up-down cells.")] + [RefreshProperties(RefreshProperties.All)] + public decimal Minimum + { + get + { + if (NumericUpDownCellTemplate == null) + throw new InvalidOperationException( + "Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); + return NumericUpDownCellTemplate.Minimum; + } + set + { + if (NumericUpDownCellTemplate == null) + throw new InvalidOperationException( + "Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); + NumericUpDownCellTemplate.Minimum = value; + if (DataGridView != null) + { + var dataGridViewRows = DataGridView.Rows; + var rowCount = dataGridViewRows.Count; + for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) + { + var dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); + var dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewNumericUpDownCell; + if (dataGridViewCell != null) dataGridViewCell.SetMinimum(rowIndex, value); + } + + DataGridView.InvalidateColumn(Index); + // TODO: This column and/or grid rows may need to be autosized depending on their + // autosize settings. Call the autosizing methods to autosize the column, rows, + // column headers / row headers as needed. + } + } + } + + /// + /// Replicates the ThousandsSeparator property of the DataGridViewNumericUpDownCell cell type. + /// + [Category("Data")] + [DefaultValue(DataGridViewNumericUpDownCell.DATAGRIDVIEWNUMERICUPDOWNCELL_defaultThousandsSeparator)] + [Description("Indicates whether the thousands separator will be inserted between every three decimal digits.")] + public bool ThousandsSeparator + { + get + { + if (NumericUpDownCellTemplate == null) + throw new InvalidOperationException( + "Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); + return NumericUpDownCellTemplate.ThousandsSeparator; + } + set + { + if (NumericUpDownCellTemplate == null) + throw new InvalidOperationException( + "Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); + NumericUpDownCellTemplate.ThousandsSeparator = value; + if (DataGridView != null) + { + var dataGridViewRows = DataGridView.Rows; + var rowCount = dataGridViewRows.Count; + for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) + { + var dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); + var dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewNumericUpDownCell; + if (dataGridViewCell != null) dataGridViewCell.SetThousandsSeparator(rowIndex, value); + } + + DataGridView.InvalidateColumn(Index); + // TODO: This column and/or grid rows may need to be autosized depending on their + // autosize settings. Call the autosizing methods to autosize the column, rows, + // column headers / row headers as needed. + } + } + } + + /// + /// Small utility function that returns the template cell as a DataGridViewNumericUpDownCell + /// + private DataGridViewNumericUpDownCell NumericUpDownCellTemplate => (DataGridViewNumericUpDownCell) CellTemplate; + /// Indicates whether the Increment property should be persisted. private bool ShouldSerializeIncrement() { return !Increment.Equals(DataGridViewNumericUpDownCell.DATAGRIDVIEWNUMERICUPDOWNCELL_defaultIncrement); } - /// - /// Replicates the Maximum property of the DataGridViewNumericUpDownCell cell type. - /// - [ - Category("Data"), - Description("Indicates the maximum value for the numeric up-down cells."), - RefreshProperties(RefreshProperties.All) - ] - public decimal Maximum - { - get { - if (NumericUpDownCellTemplate == null) - { - throw new InvalidOperationException("Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); - } - return NumericUpDownCellTemplate.Maximum; - } - set { - if (NumericUpDownCellTemplate == null) - { - throw new InvalidOperationException("Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); - } - NumericUpDownCellTemplate.Maximum = value; - if (DataGridView != null) - { - DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; - int rowCount = dataGridViewRows.Count; - for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) - { - DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewNumericUpDownCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewNumericUpDownCell; - if (dataGridViewCell != null) - { - dataGridViewCell.SetMaximum(rowIndex, value); - } - } - DataGridView.InvalidateColumn(Index); - // TODO: This column and/or grid rows may need to be autosized depending on their - // autosize settings. Call the autosizing methods to autosize the column, rows, - // column headers / row headers as needed. - } - } - } - /// Indicates whether the Maximum property should be persisted. private bool ShouldSerializeMaximum() { return !Maximum.Equals(DataGridViewNumericUpDownCell.DATAGRIDVIEWNUMERICUPDOWNCELL_defaultMaximum); } - /// - /// Replicates the Minimum property of the DataGridViewNumericUpDownCell cell type. - /// - [ - Category("Data"), - Description("Indicates the minimum value for the numeric up-down cells."), - RefreshProperties(RefreshProperties.All) - ] - public decimal Minimum - { - get { - if (NumericUpDownCellTemplate == null) - { - throw new InvalidOperationException("Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); - } - return NumericUpDownCellTemplate.Minimum; - } - set { - if (NumericUpDownCellTemplate == null) - { - throw new InvalidOperationException("Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); - } - NumericUpDownCellTemplate.Minimum = value; - if (DataGridView != null) - { - DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; - int rowCount = dataGridViewRows.Count; - for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) - { - DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewNumericUpDownCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewNumericUpDownCell; - if (dataGridViewCell != null) - { - dataGridViewCell.SetMinimum(rowIndex, value); - } - } - DataGridView.InvalidateColumn(Index); - // TODO: This column and/or grid rows may need to be autosized depending on their - // autosize settings. Call the autosizing methods to autosize the column, rows, - // column headers / row headers as needed. - } - } - } - /// Indicates whether the Maximum property should be persisted. private bool ShouldSerializeMinimum() { @@ -234,65 +259,11 @@ namespace GradeCalc } /// - /// Replicates the ThousandsSeparator property of the DataGridViewNumericUpDownCell cell type. - /// - [ - Category("Data"), - DefaultValue(DataGridViewNumericUpDownCell.DATAGRIDVIEWNUMERICUPDOWNCELL_defaultThousandsSeparator), - Description("Indicates whether the thousands separator will be inserted between every three decimal digits.") - ] - public bool ThousandsSeparator - { - get { - if (NumericUpDownCellTemplate == null) - { - throw new InvalidOperationException("Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); - } - return NumericUpDownCellTemplate.ThousandsSeparator; - } - set { - if (NumericUpDownCellTemplate == null) - { - throw new InvalidOperationException("Operation cannot be completed because this DataGridViewColumn does not have a CellTemplate."); - } - NumericUpDownCellTemplate.ThousandsSeparator = value; - if (DataGridView != null) - { - DataGridViewRowCollection dataGridViewRows = DataGridView.Rows; - int rowCount = dataGridViewRows.Count; - for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) - { - DataGridViewRow dataGridViewRow = dataGridViewRows.SharedRow(rowIndex); - DataGridViewNumericUpDownCell dataGridViewCell = dataGridViewRow.Cells[Index] as DataGridViewNumericUpDownCell; - if (dataGridViewCell != null) - { - dataGridViewCell.SetThousandsSeparator(rowIndex, value); - } - } - DataGridView.InvalidateColumn(Index); - // TODO: This column and/or grid rows may need to be autosized depending on their - // autosize settings. Call the autosizing methods to autosize the column, rows, - // column headers / row headers as needed. - } - } - } - - /// - /// Small utility function that returns the template cell as a DataGridViewNumericUpDownCell - /// - private DataGridViewNumericUpDownCell NumericUpDownCellTemplate - { - get { - return (DataGridViewNumericUpDownCell)CellTemplate; - } - } - - /// - /// Returns a standard compact string representation of the column. + /// Returns a standard compact string representation of the column. /// public override string ToString() { - StringBuilder sb = new StringBuilder(100); + var sb = new StringBuilder(100); sb.Append("DataGridViewNumericUpDownColumn { Name="); sb.Append(Name); sb.Append(", Index="); diff --git a/Misc/HID.cs b/Misc/HID.cs index 529dc0b..9e26cd7 100644 --- a/Misc/HID.cs +++ b/Misc/HID.cs @@ -1,4 +1,6 @@ -using System.Linq; +using System; +using System.Diagnostics; +using System.Linq; using System.Management; using System.Security.Cryptography; using System.Text; @@ -27,47 +29,80 @@ Win32_NetworkAdapterConfiguration:MACAddress:IPEnabled"; public static byte[] Value { - get { + get + { if (_fingerPrint == null) { - string fingerprint_tmp = ""; - HIDClasses.Split('\r').Select(s => + var fingerprint_tmp = ""; + if (Type.GetType("Mono.Runtime") == null) { - if (s.StartsWith("\n")) - s = s.Remove(0, 1); - return s.Split(':'); - }).ToList().ForEach(s => - { - using (ManagementClass mc = new ManagementClass(s[0])) - using (ManagementObjectCollection moc = mc.GetInstances()) + HIDClasses.Split('\r').Select(s => { - ManagementBaseObject[] array = moc.OfType().ToArray(); - for (int j = 0; j < array.Length; j++) + if (s.StartsWith("\n")) + s = s.Remove(0, 1); + return s.Split(':'); + }).ToList().ForEach(s => + { + using (var mc = new ManagementClass(s[0])) + using (var moc = mc.GetInstances()) { - if ((s.Length > 2) && array[j][s[2]].ToString() != "True") continue; - try - { - fingerprint_tmp += array[j][s[1]].ToString(); - break; - } - catch + var array = moc.OfType().ToArray(); + for (var j = 0; j < array.Length; j++) { + if (s.Length > 2 && array[j][s[2]].ToString() != "True") continue; + try + { + fingerprint_tmp += array[j][s[1]].ToString(); + break; + } + catch + { + } } } - } - }); + }); + } + else //Linux implementation. This will not work if you are using Mono on windows or do not have uname and lscpu available + { + var p = new Process + { + StartInfo = + { + UseShellExecute = false, + RedirectStandardOutput = true, + FileName = "uname", + Arguments = "-nmpio" + } + }; + p.Start(); + fingerprint_tmp = p.StandardOutput.ReadToEnd(); + p.WaitForExit(); + p.StartInfo.FileName = "lscpu"; + p.StartInfo.Arguments = ""; + p.Start(); + fingerprint_tmp += p.StandardOutput.ReadToEnd(); + p.WaitForExit(); + } + using (MD5 sec = new MD5CryptoServiceProvider()) { - byte[] bt = Encoding.ASCII.GetBytes(fingerprint_tmp); + var bt = Encoding.ASCII.GetBytes(fingerprint_tmp); _fingerPrint = sec.ComputeHash(bt); } } + return _fingerPrint; } } - public static byte[] EncryptLocal(byte[] unencrypted) => ProtectedData.Protect(unencrypted, Value, DataProtectionScope.CurrentUser); + public static byte[] EncryptLocal(byte[] unencrypted) + { + return ProtectedData.Protect(unencrypted, Value, DataProtectionScope.CurrentUser); + } - public static byte[] DecryptLocal(byte[] encrypted) => ProtectedData.Unprotect(encrypted, Value, DataProtectionScope.CurrentUser); + public static byte[] DecryptLocal(byte[] encrypted) + { + return ProtectedData.Unprotect(encrypted, Value, DataProtectionScope.CurrentUser); + } } } \ No newline at end of file diff --git a/Misc/Properties/AssemblyInfo.cs b/Misc/Properties/AssemblyInfo.cs index 8bf88fb..2daa139 100644 --- a/Misc/Properties/AssemblyInfo.cs +++ b/Misc/Properties/AssemblyInfo.cs @@ -5,7 +5,9 @@ using System.Runtime.InteropServices; // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CC-Functions.W32")] -[assembly: AssemblyDescription("Random pieces of code used across my projects. I do NOT recommend using this in your own project!")] +[assembly: + AssemblyDescription( + "Random pieces of code used across my projects. I do NOT recommend using this in your own project!")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("CC24")] [assembly: AssemblyProduct("CC-Functions")] diff --git a/W32.Test/Form1.cs b/W32.Test/Form1.cs index 265de13..ac1ac3d 100644 --- a/W32.Test/Form1.cs +++ b/W32.Test/Form1.cs @@ -1,20 +1,24 @@ -using CC_Functions.Misc; -using System; +using System; using System.Drawing; using System.Linq; using System.Windows.Forms; +using CC_Functions.Misc; using static CC_Functions.W32.Power; namespace CC_Functions.W32.Test { public partial class Form1 : Form { - private MouseHook mHook; - private KeyboardHook kHook; public static Wnd32 tmpWnd; public static Form1 mainF; public static Form frm; public static Label lab; + private readonly KeyboardHook kHook; + private Point locDelB; + private readonly MouseHook mHook; + + private bool moving; + private DateTime mST; public Form1() { @@ -42,27 +46,49 @@ namespace CC_Functions.W32.Test box.DataSource = Enum.GetNames(enumT); var tmp = Enum.GetValues(enumT); box.Tag = new object[tmp.Length]; - int i = 0; - foreach (object o in tmp) + var i = 0; + foreach (var o in tmp) { - ((object[])box.Tag)[i] = o; + ((object[]) box.Tag)[i] = o; i++; } } - public object get_box_value(ComboBox box) => ((object[])box.Tag)[box.SelectedIndex]; + public object get_box_value(ComboBox box) + { + return ((object[]) box.Tag)[box.SelectedIndex]; + } - private void Power_execute_Click(object sender, EventArgs e) => RaiseEvent((ShutdownMode)get_box_value(power_mode_box), (ShutdownReason)get_box_value(power_reason_box), (ShutdownMod)get_box_value(power_mod_box)); + private void Power_execute_Click(object sender, EventArgs e) + { + RaiseEvent((ShutdownMode) get_box_value(power_mode_box), (ShutdownReason) get_box_value(power_reason_box), + (ShutdownMod) get_box_value(power_mod_box)); + } - private void Wnd_select_self_Click(object sender, EventArgs e) => tmpWnd = Wnd32.fromForm(this); + private void Wnd_select_self_Click(object sender, EventArgs e) + { + tmpWnd = Wnd32.fromForm(this); + } - private void wnd_select_list_Click(object sender, EventArgs e) => tmpWnd = SelectBox.Show(Wnd32.getVisible(), "Please select a window") ?? tmpWnd; + private void wnd_select_list_Click(object sender, EventArgs e) + { + tmpWnd = SelectBox.Show(Wnd32.getVisible(), "Please select a window") ?? tmpWnd; + } - private void Wnd_select_title_button_Click(object sender, EventArgs e) => tmpWnd = Wnd32.fromMetadata(null, wnd_select_title_box.Text); + private void Wnd_select_title_button_Click(object sender, EventArgs e) + { + tmpWnd = Wnd32.fromMetadata(null, wnd_select_title_box.Text); + } - private void Wnd_selet_class_button_Click(object sender, EventArgs e) => tmpWnd = Wnd32.fromMetadata(wnd_select_class_box.Text, null); + private void Wnd_selet_class_button_Click(object sender, EventArgs e) + { + tmpWnd = Wnd32.fromMetadata(wnd_select_class_box.Text); + } - private void Wnd_action_title_set_Click(object sender, EventArgs e) => tmpWnd.title = wnd_select_title_box.Text; + private void Wnd_action_title_set_Click(object sender, EventArgs e) + { + tmpWnd.title = wnd_select_title_box.Text; + } private void Wnd_action_title_get_Click(object sender, EventArgs e) { @@ -70,26 +96,76 @@ namespace CC_Functions.W32.Test tmpWnd = Wnd32.fromForm(this); wnd_select_title_box.Text = tmpWnd.title; wnd_action_enabled.Checked = tmpWnd.enabled; - wnd_select_selected.Text = "Selected: " + tmpWnd.hWnd.ToString(); - wnd_action_style.SelectedIndex = (int)tmpWnd.state; + wnd_select_selected.Text = "Selected: " + tmpWnd.hWnd; + wnd_action_style.SelectedIndex = (int) tmpWnd.state; wnd_select_class_box.Text = tmpWnd.className; wnd_action_visible.Checked = tmpWnd.shown; - try { wnd_action_icon.BackgroundImage = tmpWnd.icon.ToBitmap(); } catch { wnd_action_icon.BackgroundImage = null; } - try { wnd_action_pos_x_bar.Value = tmpWnd.position.X; } catch { } - try { wnd_action_pos_y_bar.Value = tmpWnd.position.Y; } catch { } - try { wnd_action_pos_w_bar.Value = tmpWnd.position.Width; } catch { } - try { wnd_action_pos_h_bar.Value = tmpWnd.position.Height; } catch { } + try + { + wnd_action_icon.BackgroundImage = tmpWnd.icon.ToBitmap(); + } + catch + { + wnd_action_icon.BackgroundImage = null; + } + + try + { + wnd_action_pos_x_bar.Value = tmpWnd.position.X; + } + catch + { + } + + try + { + wnd_action_pos_y_bar.Value = tmpWnd.position.Y; + } + catch + { + } + + try + { + wnd_action_pos_w_bar.Value = tmpWnd.position.Width; + } + catch + { + } + + try + { + wnd_action_pos_h_bar.Value = tmpWnd.position.Height; + } + catch + { + } } - private void Wnd_action_enabled_CheckedChanged(object sender, EventArgs e) => tmpWnd.enabled = wnd_action_enabled.Checked; + private void Wnd_action_enabled_CheckedChanged(object sender, EventArgs e) + { + tmpWnd.enabled = wnd_action_enabled.Checked; + } - private void Wnd_action_visible_CheckedChanged(object sender, EventArgs e) => tmpWnd.shown = wnd_action_visible.Checked; + private void Wnd_action_visible_CheckedChanged(object sender, EventArgs e) + { + tmpWnd.shown = wnd_action_visible.Checked; + } - private void Wnd_action_front_Click(object sender, EventArgs e) => tmpWnd.isForeground = true; + private void Wnd_action_front_Click(object sender, EventArgs e) + { + tmpWnd.isForeground = true; + } - private void Wnd_action_overlay_Click(object sender, EventArgs e) => tmpWnd.MakeOverlay(); + private void Wnd_action_overlay_Click(object sender, EventArgs e) + { + tmpWnd.MakeOverlay(); + } - private void Wnd_action_destroy_Click(object sender, EventArgs e) => tmpWnd.Destroy(); + private void Wnd_action_destroy_Click(object sender, EventArgs e) + { + tmpWnd.Destroy(); + } private void Wnd_select_mouse_Click(object sender, EventArgs e) { @@ -113,7 +189,7 @@ namespace CC_Functions.W32.Test { frm.Hide(); frm.WindowState = FormWindowState.Minimized; - Wnd32 tmp = Wnd32.fromPoint(MousePosition); + var tmp = Wnd32.fromPoint(MousePosition); tmpWnd.enabled = true; tmpWnd.isForeground = true; tmpWnd = tmp; @@ -130,18 +206,14 @@ namespace CC_Functions.W32.Test private void Mouse_enabled_CheckedChanged(object sender, EventArgs e) { if (mouse_enabled.Checked) - { mHook.OnMouse += MHook_OnMouse; - } else - { mHook.OnMouse -= MHook_OnMouse; - } } private void MHook_OnMouse(MouseHookEventArgs _args) { - mouse_log.Text = _args.Message.ToString() + " -|- " + _args.Point.ToString() + "\r\n" + mouse_log.Text; + mouse_log.Text = _args.Message + " -|- " + _args.Point + "\r\n" + mouse_log.Text; } private void Mouse_log_TextChanged(object sender, EventArgs e) @@ -158,18 +230,14 @@ namespace CC_Functions.W32.Test private void Keyboard_enabled_CheckedChanged(object sender, EventArgs e) { if (keyboard_enabled.Checked) - { kHook.OnKeyPress += KHook_OnKeyPress; - } else - { kHook.OnKeyPress -= KHook_OnKeyPress; - } } private void KHook_OnKeyPress(KeyboardHookEventArgs _args) { - keyboard_log.Text = _args.Key.ToString() + "\r\n" + keyboard_log.Text; + keyboard_log.Text = _args.Key + "\r\n" + keyboard_log.Text; } private void Keyboard_log_TextChanged(object sender, EventArgs e) @@ -185,7 +253,8 @@ namespace CC_Functions.W32.Test private void Wnd_action_pos_Click(object sender, EventArgs e) { - tmpWnd.position = new Rectangle(wnd_action_pos_x_bar.Value, wnd_action_pos_y_bar.Value, wnd_action_pos_w_bar.Value, wnd_action_pos_h_bar.Value); + tmpWnd.position = new Rectangle(wnd_action_pos_x_bar.Value, wnd_action_pos_y_bar.Value, + wnd_action_pos_w_bar.Value, wnd_action_pos_h_bar.Value); } private void Exit_Click(object sender, EventArgs e) @@ -194,10 +263,6 @@ namespace CC_Functions.W32.Test Application.Exit(); } - private bool moving; - private Point locDelB; - private DateTime mST; - private void Exit_MouseMove(object sender, MouseEventArgs e) { if (moving && (DateTime.Now - mST).TotalSeconds >= 0.1f) @@ -222,6 +287,9 @@ namespace CC_Functions.W32.Test tmpWnd.state = status; } - private void wnd_action_overlay_CheckedChanged(object sender, EventArgs e) => tmpWnd.overlay = wnd_action_overlay.Checked; + private void wnd_action_overlay_CheckedChanged(object sender, EventArgs e) + { + tmpWnd.overlay = wnd_action_overlay.Checked; + } } } \ No newline at end of file diff --git a/W32.Test/Program.cs b/W32.Test/Program.cs index be098dc..b362382 100644 --- a/W32.Test/Program.cs +++ b/W32.Test/Program.cs @@ -6,7 +6,7 @@ namespace CC_Functions.W32.Test internal static class Program { /// - /// The main entry point for the application. + /// The main entry point for the application. /// [STAThread] private static void Main() diff --git a/W32/Hooks/KeyboardHook.cs b/W32/Hooks/KeyboardHook.cs index 221186c..3cd5a16 100644 --- a/W32/Hooks/KeyboardHook.cs +++ b/W32/Hooks/KeyboardHook.cs @@ -8,22 +8,14 @@ namespace CC_Functions.W32 { public sealed class KeyboardHook : IDisposable { - public void Dispose() - { - instances.Remove(this); - if (instances.Count == 0) - UnhookWindowsHookEx(_hookID); - } - - private static List instances = new List(); - private const int WH_KEYBOARD_LL = 13; - private const int WM_KEYDOWN = 0x0100; - private static LowLevelKeyboardProc _proc = HookCallback; - private static IntPtr _hookID = IntPtr.Zero; - public delegate void keyPress(KeyboardHookEventArgs _args); - public event keyPress OnKeyPress; + private const int WH_KEYBOARD_LL = 13; + private const int WM_KEYDOWN = 0x0100; + + private static readonly List instances = new List(); + private static readonly LowLevelKeyboardProc _proc = HookCallback; + private static IntPtr _hookID = IntPtr.Zero; public KeyboardHook() { @@ -32,32 +24,39 @@ namespace CC_Functions.W32 instances.Add(this); } + public void Dispose() + { + instances.Remove(this); + if (instances.Count == 0) + UnhookWindowsHookEx(_hookID); + } + + public event keyPress OnKeyPress; + private IntPtr SetHook(LowLevelKeyboardProc proc) { - using (Process curProcess = Process.GetCurrentProcess()) - using (ProcessModule curModule = curProcess.MainModule) + using (var curProcess = Process.GetCurrentProcess()) + using (var curModule = curProcess.MainModule) { return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0); } } - private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam); - private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) { - if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN) + if (nCode >= 0 && wParam == (IntPtr) WM_KEYDOWN) { - int vkCode = Marshal.ReadInt32(lParam); - for (int i = 0; i < instances.Count; i++) - { - instances[i].OnKeyPress?.Invoke(new KeyboardHookEventArgs((Keys)vkCode)); - } + var vkCode = Marshal.ReadInt32(lParam); + for (var i = 0; i < instances.Count; i++) + instances[i].OnKeyPress?.Invoke(new KeyboardHookEventArgs((Keys) vkCode)); } + return CallNextHookEx(_hookID, nCode, wParam, lParam); } [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] - private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId); + private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, + uint dwThreadId); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] @@ -68,5 +67,7 @@ namespace CC_Functions.W32 [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern IntPtr GetModuleHandle(string lpModuleName); + + private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam); } } \ No newline at end of file diff --git a/W32/Hooks/KeyboardHookEventArgs.cs b/W32/Hooks/KeyboardHookEventArgs.cs index 34f07d8..e9e6c58 100644 --- a/W32/Hooks/KeyboardHookEventArgs.cs +++ b/W32/Hooks/KeyboardHookEventArgs.cs @@ -12,6 +12,9 @@ namespace CC_Functions.W32 public Keys Key { get; } - public override string ToString() => Key.ToString(); + public override string ToString() + { + return Key.ToString(); + } } } \ No newline at end of file diff --git a/W32/Hooks/MouseHook.cs b/W32/Hooks/MouseHook.cs index 5367b99..6ee2b93 100644 --- a/W32/Hooks/MouseHook.cs +++ b/W32/Hooks/MouseHook.cs @@ -8,54 +8,8 @@ namespace CC_Functions.W32 { public sealed class MouseHook : IDisposable { - public void Dispose() - { - instances.Remove(this); - if (instances.Count == 0) - UnhookWindowsHookEx(_hookID); - } - - private static List instances = new List(); - private static LowLevelMouseProc _proc = HookCallback; - private static IntPtr _hookID = IntPtr.Zero; - public delegate void mouseEvent(MouseHookEventArgs _args); - public event mouseEvent OnMouse; - - public MouseHook() - { - if (instances.Count == 0) - _hookID = SetHook(_proc); - instances.Add(this); - } - - private static IntPtr SetHook(LowLevelMouseProc proc) - { - using (Process curProcess = Process.GetCurrentProcess()) - using (ProcessModule curModule = curProcess.MainModule) - { - return SetWindowsHookEx(WH_MOUSE_LL, proc, GetModuleHandle(curModule.ModuleName), 0); - } - } - - private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam); - - private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) - { - if (nCode >= 0) - { - MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)); - for (int i = 0; i < instances.Count; i++) - { - instances[i].OnMouse?.Invoke(new MouseHookEventArgs(new Point(hookStruct.pt.x, hookStruct.pt.y), (MouseMessages)wParam)); - } - } - return CallNextHookEx(_hookID, nCode, wParam, lParam); - } - - private const int WH_MOUSE_LL = 14; - public enum MouseMessages { WM_LBUTTONDOWN = 0x0201, @@ -66,21 +20,48 @@ namespace CC_Functions.W32 WM_RBUTTONUP = 0x0205 } - [StructLayout(LayoutKind.Sequential)] - private struct POINT + private const int WH_MOUSE_LL = 14; + + private static readonly List instances = new List(); + private static readonly LowLevelMouseProc _proc = HookCallback; + private static IntPtr _hookID = IntPtr.Zero; + + public MouseHook() { - public int x; - public int y; + if (instances.Count == 0) + _hookID = SetHook(_proc); + instances.Add(this); } - [StructLayout(LayoutKind.Sequential)] - private struct MSLLHOOKSTRUCT + public void Dispose() { - public POINT pt; - public uint mouseData; - public uint flags; - public uint time; - public IntPtr dwExtraInfo; + instances.Remove(this); + if (instances.Count == 0) + UnhookWindowsHookEx(_hookID); + } + + public event mouseEvent OnMouse; + + private static IntPtr SetHook(LowLevelMouseProc proc) + { + using (var curProcess = Process.GetCurrentProcess()) + using (var curModule = curProcess.MainModule) + { + return SetWindowsHookEx(WH_MOUSE_LL, proc, GetModuleHandle(curModule.ModuleName), 0); + } + } + + private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam) + { + if (nCode >= 0) + { + var hookStruct = (MSLLHOOKSTRUCT) Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT)); + for (var i = 0; i < instances.Count; i++) + instances[i].OnMouse?.Invoke(new MouseHookEventArgs(new Point(hookStruct.pt.x, hookStruct.pt.y), + (MouseMessages) wParam)); + } + + return CallNextHookEx(_hookID, nCode, wParam, lParam); } [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] @@ -95,5 +76,24 @@ namespace CC_Functions.W32 [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern IntPtr GetModuleHandle(string lpModuleName); + + private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam); + + [StructLayout(LayoutKind.Sequential)] + private struct POINT + { + public readonly int x; + public readonly int y; + } + + [StructLayout(LayoutKind.Sequential)] + private struct MSLLHOOKSTRUCT + { + public readonly POINT pt; + public readonly uint mouseData; + public readonly uint flags; + public readonly uint time; + public readonly IntPtr dwExtraInfo; + } } } \ No newline at end of file diff --git a/W32/Hooks/MouseHookEventArgs.cs b/W32/Hooks/MouseHookEventArgs.cs index aaf8733..8934752 100644 --- a/W32/Hooks/MouseHookEventArgs.cs +++ b/W32/Hooks/MouseHookEventArgs.cs @@ -16,7 +16,7 @@ namespace CC_Functions.W32 public override string ToString() { - return Message.ToString() + "; " + Point.ToString(); + return Message + "; " + Point; } } } \ No newline at end of file diff --git a/W32/KeyboardReader.cs b/W32/KeyboardReader.cs index 7b690ee..2c5cfec 100644 --- a/W32/KeyboardReader.cs +++ b/W32/KeyboardReader.cs @@ -10,20 +10,13 @@ namespace CC_Functions.W32 public static bool IsKeyDown(Keys key) { - try - { - int state = 0; - short retVal = GetKeyState((int)key); - if ((retVal & 0x8000) == 0x8000) - state |= 1; - if ((retVal & 1) == 1) - state |= 2; - return (state & 1) == 1; - } - catch - { - throw; - } + var state = 0; + var retVal = GetKeyState((int) key); + if ((retVal & 0x8000) == 0x8000) + state |= 1; + if ((retVal & 1) == 1) + state |= 2; + return (state & 1) == 1; } } } \ No newline at end of file diff --git a/W32/Power.cs b/W32/Power.cs index c9fd1f1..982286d 100644 --- a/W32/Power.cs +++ b/W32/Power.cs @@ -6,22 +6,41 @@ namespace CC_Functions.W32 { public static class Power { - [DllImport("ntdll.dll", SetLastError = true)] - private static extern IntPtr RtlAdjustPrivilege(int Privilege, bool bEnablePrivilege, bool IsThreadPrivilege, out bool PreviousValue); + [Flags] + public enum ExitWindows : uint + { + // ONE of the following five: + LogOff = 0x00, - [DllImport("ntdll.dll")] - private static extern uint NtRaiseHardError( - uint ErrorStatus, - uint NumberOfParameters, - uint UnicodeStringParameterMask, - IntPtr Parameters, - uint ValidResponseOption, - out uint Response - ); + ShutDown = 0x01, + Reboot = 0x02, + PowerOff = 0x08, + RestartApps = 0x40, - [DllImport("user32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool ExitWindowsEx(ExitWindows uFlags, ShutdownReason dwReason); + // plus AT MOST ONE of the following two: + Force = 0x04, + + ForceIfHung = 0x10 + } + + [Flags] + public enum ShutdownMod : uint + { + None = 0x00, + Force = 0x04, + ForceIfHung = 0x10 + } + + [Flags] + public enum ShutdownMode : uint + { + LogOff = 0x00, + ShutDown = 0x01, + Reboot = 0x02, + PowerOff = 0x08, + RestartApps = 0x40, + BSoD = 0x29a + } [Flags] public enum ShutdownReason : uint @@ -66,43 +85,26 @@ namespace CC_Functions.W32 FlagPlanned = 0x80000000 } - [Flags] - public enum ExitWindows : uint - { - // ONE of the following five: - LogOff = 0x00, + [DllImport("ntdll.dll", SetLastError = true)] + private static extern IntPtr RtlAdjustPrivilege(int Privilege, bool bEnablePrivilege, bool IsThreadPrivilege, + out bool PreviousValue); - ShutDown = 0x01, - Reboot = 0x02, - PowerOff = 0x08, - RestartApps = 0x40, + [DllImport("ntdll.dll")] + private static extern uint NtRaiseHardError( + uint ErrorStatus, + uint NumberOfParameters, + uint UnicodeStringParameterMask, + IntPtr Parameters, + uint ValidResponseOption, + out uint Response + ); - // plus AT MOST ONE of the following two: - Force = 0x04, + [DllImport("user32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool ExitWindowsEx(ExitWindows uFlags, ShutdownReason dwReason); - ForceIfHung = 0x10, - } - - [Flags] - public enum ShutdownMode : uint - { - LogOff = 0x00, - ShutDown = 0x01, - Reboot = 0x02, - PowerOff = 0x08, - RestartApps = 0x40, - BSoD = 0x29a - } - - [Flags] - public enum ShutdownMod : uint - { - None = 0x00, - Force = 0x04, - ForceIfHung = 0x10 - } - - public static unsafe void RaiseEvent(ShutdownMode mode, ShutdownReason reason = ShutdownReason.MinorOther, ShutdownMod mod = ShutdownMod.None) + public static void RaiseEvent(ShutdownMode mode, ShutdownReason reason = ShutdownReason.MinorOther, + ShutdownMod mod = ShutdownMod.None) { if (mode == ShutdownMode.BSoD) { @@ -114,7 +116,7 @@ namespace CC_Functions.W32 else { EnablePrivilege(SecurityEntity.SeShutdownPrivilege); - ExitWindowsEx((ExitWindows)((uint)mode | (uint)mod), reason); + ExitWindowsEx((ExitWindows) ((uint) mode | (uint) mod), reason); } } } diff --git a/W32/Privileges.cs b/W32/Privileges.cs index 0572c22..600428a 100644 --- a/W32/Privileges.cs +++ b/W32/Privileges.cs @@ -7,62 +7,6 @@ namespace CC_Functions.W32 { public static class Privileges { - public static void EnablePrivilege(SecurityEntity securityEntity) - { - if (!Enum.IsDefined(typeof(SecurityEntity), securityEntity)) - throw new InvalidEnumArgumentException("securityEntity", (int)securityEntity, typeof(SecurityEntity)); - var securityEntityValue = securityEntity.ToString(); - try - { - var locallyUniqueIdentifier = new NativeMethods.LUID(); - if (NativeMethods.LookupPrivilegeValue(null, securityEntityValue, ref locallyUniqueIdentifier)) - { - var TOKEN_PRIVILEGES = new NativeMethods.TOKEN_PRIVILEGES - { - PrivilegeCount = 1, - Attributes = NativeMethods.SE_PRIVILEGE_ENABLED, - Luid = locallyUniqueIdentifier - }; - var tokenHandle = IntPtr.Zero; - try - { - var currentProcess = NativeMethods.GetCurrentProcess(); - if (NativeMethods.OpenProcessToken(currentProcess, NativeMethods.TOKEN_ADJUST_PRIVILEGES | NativeMethods.TOKEN_QUERY, out tokenHandle)) - { - if (NativeMethods.AdjustTokenPrivileges(tokenHandle, false, ref TOKEN_PRIVILEGES, 1024, IntPtr.Zero, IntPtr.Zero)) - { - if (Marshal.GetLastWin32Error() == NativeMethods.ERROR_NOT_ALL_ASSIGNED) - { - throw new InvalidOperationException("AdjustTokenPrivileges failed.", 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 - { - if (tokenHandle != IntPtr.Zero) - NativeMethods.CloseHandle(tokenHandle); - } - } - else - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "LookupPrivilegeValue failed. SecurityEntityValue: {0}", securityEntityValue), new Win32Exception()); - } - } - catch (Exception e) - { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "GrantPrivilege failed. SecurityEntity: {0}", securityEntityValue), e); - } - } - public enum SecurityEntity { SeAssignPrimaryTokenPrivilege, @@ -143,19 +87,79 @@ namespace CC_Functions.W32 SE_UNSOLICITED_INPUT_NAME_TEXT } - public static SecurityEntity EntityToEntity(SecurityEntity2 entity) => (SecurityEntity)entity; + public static void EnablePrivilege(SecurityEntity securityEntity) + { + if (!Enum.IsDefined(typeof(SecurityEntity), securityEntity)) + throw new InvalidEnumArgumentException("securityEntity", (int) securityEntity, typeof(SecurityEntity)); + var securityEntityValue = securityEntity.ToString(); + try + { + var locallyUniqueIdentifier = new NativeMethods.LUID(); + if (NativeMethods.LookupPrivilegeValue(null, securityEntityValue, ref locallyUniqueIdentifier)) + { + var TOKEN_PRIVILEGES = new NativeMethods.TOKEN_PRIVILEGES + { + PrivilegeCount = 1, + Attributes = NativeMethods.SE_PRIVILEGE_ENABLED, + Luid = locallyUniqueIdentifier + }; + var tokenHandle = IntPtr.Zero; + try + { + var currentProcess = NativeMethods.GetCurrentProcess(); + if (NativeMethods.OpenProcessToken(currentProcess, + NativeMethods.TOKEN_ADJUST_PRIVILEGES | NativeMethods.TOKEN_QUERY, out tokenHandle)) + { + if (NativeMethods.AdjustTokenPrivileges(tokenHandle, false, ref TOKEN_PRIVILEGES, 1024, + IntPtr.Zero, IntPtr.Zero)) + { + if (Marshal.GetLastWin32Error() == NativeMethods.ERROR_NOT_ALL_ASSIGNED) + throw new InvalidOperationException("AdjustTokenPrivileges failed.", + 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 + { + if (tokenHandle != IntPtr.Zero) + NativeMethods.CloseHandle(tokenHandle); + } + } + else + { + throw new InvalidOperationException( + string.Format(CultureInfo.InvariantCulture, + "LookupPrivilegeValue failed. SecurityEntityValue: {0}", securityEntityValue), + new Win32Exception()); + } + } + catch (Exception e) + { + throw new InvalidOperationException( + string.Format(CultureInfo.InvariantCulture, "GrantPrivilege failed. SecurityEntity: {0}", + securityEntityValue), e); + } + } + + public static SecurityEntity EntityToEntity(SecurityEntity2 entity) + { + return (SecurityEntity) entity; + } internal static class NativeMethods { - [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool LookupPrivilegeValue(string lpsystemname, string lpname, [MarshalAs(UnmanagedType.Struct)] ref LUID lpLuid); - - [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool AdjustTokenPrivileges(IntPtr tokenhandle, [MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges, - [MarshalAs(UnmanagedType.Struct)]ref TOKEN_PRIVILEGES newstate, uint bufferlength, IntPtr previousState, IntPtr returnlength); - internal const int SE_PRIVILEGE_ENABLED = 0x00000002; internal const int ERROR_NOT_ALL_ASSIGNED = 1300; @@ -171,17 +175,32 @@ namespace CC_Functions.W32 internal const uint TOKEN_ADJUST_GROUPS = 0x0040; internal const uint TOKEN_ADJUST_DEFAULT = 0x0080; internal const uint TOKEN_ADJUST_SESSIONID = 0x0100; - internal const uint TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY); + internal const uint TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY; - internal const uint TOKEN_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY - | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID; + internal const uint TOKEN_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | + TOKEN_IMPERSONATE | TOKEN_QUERY + | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | + TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID; + + [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool LookupPrivilegeValue(string lpsystemname, string lpname, + [MarshalAs(UnmanagedType.Struct)] ref LUID lpLuid); + + [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool AdjustTokenPrivileges(IntPtr tokenhandle, + [MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges, + [MarshalAs(UnmanagedType.Struct)] ref TOKEN_PRIVILEGES newstate, uint bufferlength, + IntPtr previousState, IntPtr returnlength); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] internal static extern IntPtr GetCurrentProcess(); [DllImport("Advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool OpenProcessToken(IntPtr processHandle, uint desiredAccesss, out IntPtr tokenHandle); + internal static extern bool OpenProcessToken(IntPtr processHandle, uint desiredAccesss, + out IntPtr tokenHandle); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] diff --git a/W32/Wnd32.cs b/W32/Wnd32.cs index b7bf504..5fe6451 100644 --- a/W32/Wnd32.cs +++ b/W32/Wnd32.cs @@ -15,56 +15,72 @@ namespace CC_Functions.W32 #region CreateInstance - private Wnd32(IntPtr wndref) => hWnd = wndref; + private Wnd32(IntPtr wndref) + { + hWnd = wndref; + } - public static Wnd32 fromHandle(IntPtr handle) => new Wnd32(handle); + public static Wnd32 fromHandle(IntPtr handle) + { + return new Wnd32(handle); + } - public static Wnd32 fromMetadata(string lpClassName = null, string lpWindowName = null) => fromHandle(FindWindow(lpClassName, lpWindowName)); + public static Wnd32 fromMetadata(string lpClassName = null, string lpWindowName = null) + { + return fromHandle(FindWindow(lpClassName, lpWindowName)); + } - public static Wnd32 fromPoint(Point point) => fromHandle(WindowFromPoint(point.X, point.Y)); + public static Wnd32 fromPoint(Point point) + { + return fromHandle(WindowFromPoint(point.X, point.Y)); + } - public static Wnd32 fromForm(Form form) => fromHandle(form.Handle); + public static Wnd32 fromForm(Form form) + { + return fromHandle(form.Handle); + } - public static Wnd32 foreground() => fromHandle(GetForegroundWindow()); + public static Wnd32 foreground() + { + return fromHandle(GetForegroundWindow()); + } public static Wnd32[] getVisible() { WindowHandles = new List(); if (!EnumDesktopWindows(IntPtr.Zero, FilterCallback, IntPtr.Zero)) - { throw new Win32Exception("There was a native error. This should never happen!"); - } - else - { - return WindowHandles.Select(s => fromHandle(s)).ToArray(); - } + return WindowHandles.Select(s => fromHandle(s)).ToArray(); } + #endregion CreateInstance #region InstanceActions public string title { - get { - int length = GetWindowTextLength(hWnd); - StringBuilder sb = new StringBuilder(length + 1); + get + { + var length = GetWindowTextLength(hWnd); + var sb = new StringBuilder(length + 1); GetWindowText(hWnd, sb, sb.Capacity); return sb.ToString(); } - set { - SetWindowText(hWnd, value); - } + set => SetWindowText(hWnd, value); } public Rectangle position { - get { - RECT Rect = new RECT(); + get + { + var Rect = new RECT(); GetWindowRect(hWnd, ref Rect); - return new Rectangle(new Point(Rect.left, Rect.top), new Size(Rect.right - Rect.left, Rect.bottom - Rect.top)); + return new Rectangle(new Point(Rect.left, Rect.top), + new Size(Rect.right - Rect.left, Rect.bottom - Rect.top)); } - set { - RECT Rect = new RECT(); + set + { + var Rect = new RECT(); GetWindowRect(hWnd, ref Rect); MoveWindow(hWnd, value.X, value.Y, value.Width, value.Height, true); } @@ -72,30 +88,27 @@ namespace CC_Functions.W32 public bool isForeground { - get { - return GetForegroundWindow() == hWnd; - } - set { + get => GetForegroundWindow() == hWnd; + set + { if (value) SetForegroundWindow(hWnd); else - throw new InvalidOperationException("You can't set a Window not to be in the foreground. Move another one over it!"); + throw new InvalidOperationException( + "You can't set a Window not to be in the foreground. Move another one over it!"); } } public bool enabled { - get { - return IsWindowEnabled(hWnd); - } - set { - EnableWindow(hWnd, value); - } + get => IsWindowEnabled(hWnd); + set => EnableWindow(hWnd, value); } public Icon icon { - get { + get + { var hicon = SendMessage(hWnd, 0x7F, 1, 0); if (hicon == IntPtr.Zero) hicon = SendMessage(hWnd, 0x7F, 0, 0); @@ -107,10 +120,9 @@ namespace CC_Functions.W32 public bool shown { - get { - return IsWindowVisible(hWnd); - } - set { + get => IsWindowVisible(hWnd); + set + { if (value) ShowWindow(hWnd, 9); else @@ -120,8 +132,9 @@ namespace CC_Functions.W32 public string className { - get { - StringBuilder ClassName = new StringBuilder(256); + get + { + var ClassName = new StringBuilder(256); _ = GetClassName(hWnd, ClassName, ClassName.Capacity); return ClassName.ToString(); } @@ -129,22 +142,17 @@ namespace CC_Functions.W32 public FormWindowState state { - get { - int style = (int)GetWindowLong(hWnd, -16); + get + { + var style = GetWindowLong(hWnd, -16); if ((style & 0x01000000) == 0x01000000) - { return FormWindowState.Maximized; - } - else if ((style & 0x20000000) == 0x20000000) - { + if ((style & 0x20000000) == 0x20000000) return FormWindowState.Minimized; - } - else - { - return FormWindowState.Normal; - } + return FormWindowState.Normal; } - set { + set + { switch (value) { case FormWindowState.Minimized: @@ -162,13 +170,18 @@ namespace CC_Functions.W32 } } - public void MakeOverlay() => overlay = true; + public void MakeOverlay() + { + overlay = true; + } public bool overlay { - set { - Rectangle tmp = position; - _ = SetWindowPos(hWnd, value ? HWND_TOPMOST : HWND_NOTOPMOST, tmp.X, tmp.Y, tmp.Width, tmp.Height, value ? SWP_NOMOVE | SWP_NOSIZE : 0); + set + { + var tmp = position; + _ = SetWindowPos(hWnd, value ? HWND_TOPMOST : HWND_NOTOPMOST, tmp.X, tmp.Y, tmp.Width, tmp.Height, + value ? SWP_NOMOVE | SWP_NOSIZE : 0); } } @@ -176,23 +189,40 @@ namespace CC_Functions.W32 { if (DestroyWindow(hWnd)) return true; - else - throw new Exception("Failed."); + throw new Exception("Failed."); } public bool stillExists => IsWindow(hWnd); - public override string ToString() => hWnd.ToString() + "; " + title + "; " + position.ToString(); + public override string ToString() + { + return hWnd + "; " + title + "; " + position; + } - public override bool Equals(object obj) => Equals(obj as Wnd32); + public override bool Equals(object obj) + { + return Equals(obj as Wnd32); + } - public bool Equals(Wnd32 other) => other != null && EqualityComparer.Default.Equals(hWnd, other.hWnd); + public bool Equals(Wnd32 other) + { + return other != null && EqualityComparer.Default.Equals(hWnd, other.hWnd); + } - public override int GetHashCode() => -75345830 + EqualityComparer.Default.GetHashCode(hWnd); + public override int GetHashCode() + { + return -75345830 + EqualityComparer.Default.GetHashCode(hWnd); + } - public static bool operator ==(Wnd32 left, Wnd32 right) => EqualityComparer.Default.Equals(left, right); + public static bool operator ==(Wnd32 left, Wnd32 right) + { + return EqualityComparer.Default.Equals(left, right); + } - public static bool operator !=(Wnd32 left, Wnd32 right) => !(left == right); + public static bool operator !=(Wnd32 left, Wnd32 right) + { + return !(left == right); + } #endregion InstanceActions @@ -241,17 +271,19 @@ namespace CC_Functions.W32 private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); private static readonly IntPtr HWND_TOP = new IntPtr(0); private static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2); - private const UInt32 SWP_NOSIZE = 0x0001; - private const UInt32 SWP_NOMOVE = 0x0002; + private const uint SWP_NOSIZE = 0x0001; + private const uint SWP_NOMOVE = 0x0002; [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); + private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, + uint uFlags); [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount); - [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, ExactSpelling = true, SetLastError = true)] + [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, + ExactSpelling = true, SetLastError = true)] private static extern bool GetWindowRect(IntPtr hWnd, ref RECT rect); private struct RECT @@ -278,22 +310,24 @@ namespace CC_Functions.W32 [DllImport("user32.dll", SetLastError = true)] private static extern int GetWindowLong(IntPtr hWnd, int nIndex); - [DllImport("user32.dll", EntryPoint = "EnumDesktopWindows", ExactSpelling = false, CharSet = CharSet.Auto, SetLastError = true)] - private static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDelegate lpEnumCallbackFunction, IntPtr lParam); + [DllImport("user32.dll", EntryPoint = "EnumDesktopWindows", ExactSpelling = false, CharSet = CharSet.Auto, + SetLastError = true)] + private static extern bool EnumDesktopWindows(IntPtr hDesktop, EnumDelegate lpEnumCallbackFunction, + IntPtr lParam); // Define the callback delegate's type. private delegate bool EnumDelegate(IntPtr hWnd, int lParam); + private static List WindowHandles; + private static bool FilterCallback(IntPtr hWnd, int lParam) { - StringBuilder sb_title = new StringBuilder(1024); + var sb_title = new StringBuilder(1024); GetWindowText(hWnd, sb_title, sb_title.Capacity); - if (IsWindowVisible(hWnd) && string.IsNullOrEmpty(sb_title.ToString()) == false) - { - WindowHandles.Add(hWnd); - } + if (IsWindowVisible(hWnd) && string.IsNullOrEmpty(sb_title.ToString()) == false) WindowHandles.Add(hWnd); return true; } + #endregion W32 } } \ No newline at end of file