Skip to content

Instantly share code, notes, and snippets.

@decay88
Created March 9, 2020 14:54
Show Gist options
  • Select an option

  • Save decay88/761a3f081269b96191bb77d4813f23d3 to your computer and use it in GitHub Desktop.

Select an option

Save decay88/761a3f081269b96191bb77d4813f23d3 to your computer and use it in GitHub Desktop.

Revisions

  1. xCONFLiCTiONx revised this gist Mar 6, 2020. 21 changed files with 70 additions and 331 deletions.
    67 changes: 67 additions & 0 deletions Admin Check.cs
    Original file line number Diff line number Diff line change
    @@ -9,3 +9,70 @@ public static bool IsAdministrator
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    }



    // Current Application
    static bool IsElevated
    {
    get
    {
    return WindowsIdentity.GetCurrent().Owner
    .IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid);
    }
    }



    // Another Application
    public class ProcessHelper
    {
    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool CloseHandle(IntPtr hObject);

    private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;
    private const int TOKEN_ASSIGN_PRIMARY = 0x1;
    private const int TOKEN_DUPLICATE = 0x2;
    private const int TOKEN_IMPERSONATE = 0x4;
    private const int TOKEN_QUERY = 0x8;
    private const int TOKEN_QUERY_SOURCE = 0x10;
    private const int TOKEN_ADJUST_GROUPS = 0x40;
    private const int TOKEN_ADJUST_PRIVILEGES = 0x20;
    private const int TOKEN_ADJUST_SESSIONID = 0x100;
    private const int TOKEN_ADJUST_DEFAULT = 0x80;
    private const int 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_SESSIONID | TOKEN_ADJUST_DEFAULT);

    public static bool IsProcessOwnerAdmin(string processName)
    {
    Process proc = Process.GetProcessesByName(processName)[0];

    IntPtr ph = IntPtr.Zero;

    OpenProcessToken(proc.Handle, TOKEN_ALL_ACCESS, out ph);

    WindowsIdentity iden = new WindowsIdentity(ph);

    bool result = false;

    foreach (IdentityReference role in iden.Groups)
    {
    if (role.IsValidTargetType(typeof(SecurityIdentifier)))
    {
    SecurityIdentifier sid = role as SecurityIdentifier;

    if (sid.IsWellKnown(WellKnownSidType.AccountAdministratorSid) || sid.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid))
    {
    result = true;
    break;
    }
    }
    }

    CloseHandle(ph);

    return result;
    }
    }
    35 changes: 0 additions & 35 deletions Crash Handler.cs
    Original file line number Diff line number Diff line change
    @@ -1,35 +0,0 @@
    using System;
    using System.Security.Permissions;

    public class Example
    {
    [SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlAppDomain)]
    public static void Main()
    {
    AppDomain currentDomain = AppDomain.CurrentDomain;
    currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

    try {
    throw new Exception("1");
    } catch (Exception e) {
    Console.WriteLine("Catch clause caught : {0} \n", e.Message);
    }

    throw new Exception("2");
    }

    static void MyHandler(object sender, UnhandledExceptionEventArgs args)
    {
    Exception e = (Exception) args.ExceptionObject;
    Console.WriteLine("MyHandler caught : " + e.Message);
    Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
    }
    }
    // The example displays the following output:
    // Catch clause caught : 1
    //
    // MyHandler caught : 2
    // Runtime terminating: True
    //
    // Unhandled Exception: System.Exception: 2
    // at Example.Main()
    10 changes: 0 additions & 10 deletions Exit (Proper).cs
    Original file line number Diff line number Diff line change
    @@ -1,10 +0,0 @@
    if (System.Windows.Forms.Application.MessageLoop)
    {
    // WinForms app
    System.Windows.Forms.Application.Exit();
    }
    else
    {
    // Console app
    System.Environment.Exit(1);
    }
    File renamed without changes.
    10 changes: 0 additions & 10 deletions MessageBox.cs
    Original file line number Diff line number Diff line change
    @@ -17,14 +17,4 @@ private DialogResult MessageForm(string text, string title, MessageBoxButtons bu
    }
    return dialogResult;
    }
    }

    // or

    DialogResult dialogResult = MessageBox.Show("Information", "Title", MessageBoxButtons.YesNo);
    if (dialogResult == DialogResult.Yes)
    {
    }
    else if (dialogResult == DialogResult.No)
    {
    }
    7 changes: 0 additions & 7 deletions OptionalParameters.cs
    Original file line number Diff line number Diff line change
    @@ -1,7 +0,0 @@
    string[] array = SelectedItemPaths.Cast<string>().ToArray();
    MessageBox.Show(array.ToStringArray());
    MessageBox.Show(array.ToStringArray(true));
    public static string ToStringArray(this string[] array, bool Naming = false)
    {

    }
    60 changes: 0 additions & 60 deletions Program.exe.config
    Original file line number Diff line number Diff line change
    @@ -1,60 +0,0 @@
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    <configSections>
    <section name="Paths" type="System.Configuration.NameValueSectionHandler" />
    </configSections>
    <startup>
    <!-- Framwork Version -->
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
    <!-- Environment Variable Paths -->
    <Paths>
    <add key="Path1" value="%USERPROFILE%\Workspace\" />
    <add key="Path2" value="%LOCALAPPDATA%\Temp\" />
    </Paths>
    </configuration>

    <!-- Environment Variables
    %ALLUSERSPROFILE% C:\ProgramData
    %APPDATA% C:\Users\%USERNAME%\AppData\Roaming
    %COMMONPROGRAMFILES% C:\Program Files\Common Files
    %COMMONPROGRAMFILES(x86)% C:\Program Files (x86)\Common Files
    %COMSPEC% C:\Windows\System32\cmd.exe
    %HOMEDRIVE% C:
    %HOMEPATH% C:\Users\%USERNAME%
    %LOCALAPPDATA% C:\Users\%USERNAME%\AppData\Local
    %PROGRAMFILES% C:\Program Files
    %PROGRAMFILES(X86)% C:\Program Files (x86) (only in 64-bit version)
    %SystemDrive% C:
    %SystemRoot% C:\Windows
    %TEMP% and %TMP% C:\Users\%USERNAME%\AppData\Local\Temp
    %USERPROFILE% C:\Users\%USERNAME%
    %WINDIR% C:\Windows
    -->

    <!-- C# Code
    if (ConfigurationManager.GetSection("Directories") as NameValueCollection != null)
    {
    foreach (var directory in (ConfigurationManager.GetSection("Directories") as NameValueCollection).AllKeys)
    {
    string Value = (ConfigurationManager.GetSection("Directories") as NameValueCollection).GetValues(directory).FirstOrDefault();
    string DirectoriesValue = Environment.ExpandEnvironmentVariables(Value);
    if (directory == "Xpadder")
    {
    if (DirectoriesValue != "")
    {
    }
    }
    }
    }
    else
    {
    MessageBox.Show("Either the configuration File is missing or is corrupt.\n\nYou will need to recreate this file in order for the application to work correctly and process any settings.", "Configuration File Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
    Environment.Exit(0);
    }
    -->
    3 changes: 0 additions & 3 deletions Quotes.cs
    Original file line number Diff line number Diff line change
    @@ -1,3 +0,0 @@
    string SYSTEM = "\"NT AUTHORITY\\SYSTEM\"";

    string TaskPath = "\"" + AssemblyDirectory + "\\NightMode.exe\"";
    1 change: 0 additions & 1 deletion REGEX.cs
    Original file line number Diff line number Diff line change
    @@ -1 +0,0 @@
    ^(?([^\r\n])\s)*\r?$\r?\n // Remove Empty Lines
    18 changes: 0 additions & 18 deletions Read From App.config.cs
    Original file line number Diff line number Diff line change
    @@ -1,18 +0,0 @@
    //program
    using System.Configuration;
    using System.Collections.Specialized;
    using System.Linq;

    var MouseX = ConfigurationManager.GetSection("MouseX") as NameValueCollection;

    if (MouseX != null)
    {
    foreach (var games in MouseX.AllKeys)
    {
    string gamesValue = MouseX.GetValues(games).FirstOrDefault();
    if (gamesValue.Contains(GameRunning))
    {
    //Do something with the string
    }
    }
    }
    25 changes: 0 additions & 25 deletions Reminder.cs
    Original file line number Diff line number Diff line change
    @@ -1,25 +0,0 @@
    Thread Remind = new Thread(Reminder);
    Remind.IsBackground = true;
    Remind.Start();
    static void Reminder()
    {
    bool Timer = true;
    while(Timer)
    {
    TimeSpan T1A = TimeSpan.Parse("11:00");
    TimeSpan now = DateTime.Now.TimeOfDay;

    if (now > T1A)
    {
    using (System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"C:\Windows\Media\Alarm09.wav"))
    {
    player.Play();
    }
    Thread.Sleep(60000);
    }
    else
    {
    Thread.Sleep(2000);
    }
    }
    }
    2 changes: 0 additions & 2 deletions Replace Text.cs
    Original file line number Diff line number Diff line change
    @@ -1,2 +0,0 @@
    string text = "Some String";
    text = text.Replace("Some", "New");
    4 changes: 0 additions & 4 deletions Run Form In The Background.cs
    Original file line number Diff line number Diff line change
    @@ -1,4 +0,0 @@
    // Make form run in the background
    Visible = false;
    ShowInTaskbar = false;
    Hide();
    62 changes: 0 additions & 62 deletions Running as Admin.cs
    Original file line number Diff line number Diff line change
    @@ -1,62 +0,0 @@
    // Current Application
    static bool IsElevated
    {
    get
    {
    return WindowsIdentity.GetCurrent().Owner
    .IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid);
    }
    }

    // Another Application
    public class ProcessHelper
    {
    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool CloseHandle(IntPtr hObject);

    private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;
    private const int TOKEN_ASSIGN_PRIMARY = 0x1;
    private const int TOKEN_DUPLICATE = 0x2;
    private const int TOKEN_IMPERSONATE = 0x4;
    private const int TOKEN_QUERY = 0x8;
    private const int TOKEN_QUERY_SOURCE = 0x10;
    private const int TOKEN_ADJUST_GROUPS = 0x40;
    private const int TOKEN_ADJUST_PRIVILEGES = 0x20;
    private const int TOKEN_ADJUST_SESSIONID = 0x100;
    private const int TOKEN_ADJUST_DEFAULT = 0x80;
    private const int 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_SESSIONID | TOKEN_ADJUST_DEFAULT);

    public static bool IsProcessOwnerAdmin(string processName)
    {
    Process proc = Process.GetProcessesByName(processName)[0];

    IntPtr ph = IntPtr.Zero;

    OpenProcessToken(proc.Handle, TOKEN_ALL_ACCESS, out ph);

    WindowsIdentity iden = new WindowsIdentity(ph);

    bool result = false;

    foreach (IdentityReference role in iden.Groups)
    {
    if (role.IsValidTargetType(typeof(SecurityIdentifier)))
    {
    SecurityIdentifier sid = role as SecurityIdentifier;

    if (sid.IsWellKnown(WellKnownSidType.AccountAdministratorSid) || sid.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid))
    {
    result = true;
    break;
    }
    }
    }

    CloseHandle(ph);

    return result;
    }
    }
    1 change: 0 additions & 1 deletion String Before Comma.cs
    Original file line number Diff line number Diff line change
    @@ -1 +0,0 @@
    substring = str.Split(',')[0];
    4 changes: 3 additions & 1 deletion Strings.cs
    Original file line number Diff line number Diff line change
    @@ -42,4 +42,6 @@ public static string NullIfWhiteSpace(this string s)
    somestring.Split(new[] { "some text" }, StringSplitOptions.None)[1]

    // or
    string[] args = arg.Split(',');
    string[] args = arg.Split(',');

    substring = str.Split(',')[0];
    18 changes: 0 additions & 18 deletions System Events.cs
    Original file line number Diff line number Diff line change
    @@ -1,18 +0,0 @@
    protected override void WndProc(ref Message m)
    {
    switch (m.Msg)
    {
    case UnsafeNativeMethods.CurrentStateUsb.Wmdevicechange:
    if (!UnsafeNativeMethods.CriticalHandle.ScreenDetection.AreApplicationFullScreen())
    {
    Thread.Sleep(500);
    Thread th = new Thread(DevCheck)
    {
    IsBackground = true
    };
    th.Start();
    }
    break;
    }
    base.WndProc(ref m);
    }
    17 changes: 0 additions & 17 deletions System UpTime.cs
    Original file line number Diff line number Diff line change
    @@ -1,17 +0,0 @@
    TimeSpan TimeCompare = TimeSpan.FromMinutes(5);
    if (SystemUpTime < TimeCompare)
    {
    Environment.Exit(0);
    }

    static TimeSpan SystemUpTime
    {
    get
    {
    using (var uptime = new PerformanceCounter("System", "System Up Time"))
    {
    uptime.NextValue();
    return TimeSpan.FromSeconds(uptime.NextValue());
    }
    }
    }
    3 changes: 0 additions & 3 deletions SystemIcons.cs
    Original file line number Diff line number Diff line change
    @@ -1,3 +0,0 @@
    using System.Drawing;

    this.Icon = SystemIcons.Warning;
    40 changes: 0 additions & 40 deletions Validate.cs
    Original file line number Diff line number Diff line change
    @@ -1,40 +0,0 @@
    PassThroughNonNull(firstImage);

    static Image PassThroughNonNull(Image firstImage)
    {
    if (firstImage == null)
    throw new InvalidOperationException(firstImage.ToString());//Try to find an exception like ArgumentNullException if dealing with args
    return firstImage;
    }

    // EXAMPLE
    public static Bitmap MergeTwoImages(Image firstImage, Image secondImage)
    {
    int outputImageWidth = 460;

    int outputImageHeight = 215;

    outputImage = new Bitmap(outputImageWidth, outputImageHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

    using (Graphics graphics = Graphics.FromImage(outputImage))
    {
    graphics.DrawImage(PassThroughNonNull(firstImage), new Rectangle(new System.Drawing.Point(), PassThroughNonNull(firstImage).Size),
    new Rectangle(new System.Drawing.Point(), PassThroughNonNull(firstImage).Size), GraphicsUnit.Pixel);
    graphics.DrawImage(PassThroughNonNull2(secondImage), new Rectangle(new System.Drawing.Point(0, 0), PassThroughNonNull2(secondImage).Size),
    new Rectangle(new System.Drawing.Point(), PassThroughNonNull2(secondImage).Size), GraphicsUnit.Pixel);
    }

    return outputImage;
    }
    static Image PassThroughNonNull(Image firstImage)
    {
    if (firstImage == null)
    throw new InvalidOperationException(firstImage.ToString());
    return firstImage;
    }
    static Image PassThroughNonNull2(Image secondImage)
    {
    if (secondImage == null)
    throw new InvalidOperationException(secondImage.ToString());
    return secondImage;
    }
    14 changes: 0 additions & 14 deletions WPF Dynamically add button.cs
    Original file line number Diff line number Diff line change
    @@ -1,14 +0,0 @@
    StackPanel stackPanel1 = new StackPanel();
    System.Windows.Controls.Button button1 = new System.Windows.Controls.Button();
    button1.Width = 461;
    button1.Height = 217;

    button1.SetValue(Canvas.LeftProperty, 0.0);
    button1.SetValue(Canvas.TopProperty, 0.0);
    stackPanel1.Children.Add(button1);
    button1.Focus();
    button1.Content = stackPanel1;
    button1.Content = new Image
    {
    Source = new BitmapImage(new Uri(GameImage1))
    };
  2. xCONFLiCTiONx revised this gist Mar 2, 2020. 5 changed files with 40 additions and 5 deletions.
    11 changes: 7 additions & 4 deletions Admin Check.cs
    Original file line number Diff line number Diff line change
    @@ -1,8 +1,11 @@
    using System.Security.Principal;

    public static bool IsAdministrator()
    public static bool IsAdministrator
    {
    var identity = WindowsIdentity.GetCurrent();
    var principal = new WindowsPrincipal(identity);
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
    get
    {
    var identity = WindowsIdentity.GetCurrent();
    var principal = new WindowsPrincipal(identity);
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    }
    17 changes: 17 additions & 0 deletions Catch Handler.cs
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,20 @@
    AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
    Application.ThreadException += Application_ThreadException;
    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

    private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
    EasyLogger.Error("Application.ThreadException: Base Exception: " + e.Exception.GetBaseException() + Environment.NewLine + "Exception Message: " + e.Exception.Message);
    }

    private static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
    EasyLogger.Error("AppDomain.UnhandledException: Exception Object: " + e.ExceptionObject + Environment.NewLine + "Exception Object: " + ((Exception)e.ExceptionObject).Message);
    }


    // OR

    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

    private static void CurrentDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
    10 changes: 10 additions & 0 deletions Clipboard.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    using System.Windows.Forms;

    [STAThread]
    private static void Main(string[] arg)
    {
    Thread thread = new Thread(() => Clipboard.SetText("Test!"));
    thread.SetApartmentState(ApartmentState.STA); //Set the thread to STA
    thread.Start();
    thread.Join(); //Wait for the thread to end
    }
    6 changes: 6 additions & 0 deletions For Loop.cs
    Original file line number Diff line number Diff line change
    @@ -6,4 +6,10 @@
    for (int i = 10 - 1; i >= 0; i--)
    {
    Console.WriteLine(i);
    }


    for (int i = 0; i < Titles.Count; i++)
    {
    Console.WriteLine((i + 1) + " | " + SomeTitles[i]);
    }
    1 change: 0 additions & 1 deletion SetApartmentState Error.cs
    Original file line number Diff line number Diff line change
    @@ -1 +0,0 @@
    Invoke((Action)(() => { }));
  3. xCONFLiCTiONx revised this gist Feb 25, 2020. 2 changed files with 24 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions Current Directory.cs
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,5 @@
    static string CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);


    // Has \\ at the end so no need to put "\\file"
    AppDomain.CurrentDomain.BaseDirectory
    22 changes: 22 additions & 0 deletions Registry.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    // Create key
    Microsoft.Win32.RegistryKey key;
    key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Names");
    key.SetValue("Name", "Isabella");
    key.Close();

    // Delete or close the new subkey.
    Console.Write("\nDelete newly created registry key? (Y/N) ");
    if(Char.ToUpper(Convert.ToChar(Console.Read())) == 'Y')
    {
    Registry.CurrentUser.DeleteSubKeyTree("Test9999");
    Console.WriteLine("\nRegistry key {0} deleted.",
    test9999.Name);
    }
    else
    {
    Console.WriteLine("\nRegistry key {0} closed.",
    test9999.ToString());
    test9999.Close();
    }


  4. xCONFLiCTiONx revised this gist Feb 21, 2020. 2 changed files with 106 additions and 0 deletions.
    70 changes: 70 additions & 0 deletions Encryption.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,70 @@
    using System;
    using System.Security.Cryptography;
    using System.IO;
    using System.Text;

    public class Program
    {
    public static void Main()
    {
    // declaring key
    var key = "b14ca5898a4e4133bbce2ea2315a1916";

    // encrypt parameters
    var input = string.Concat("https://myDomain.in/", "Encrypt.aspx?query=", EncryptString(key, string.Format("emailID={0}", "myemail@gmail.com")));

    Console.WriteLine("Encrypted Input: " + input);

    // decrypt parameters
    var decrptedInput = DecryptString(key, input.Substring(input.IndexOf("=") + 1));
    Console.WriteLine("Decrypted Input: " + decrptedInput);
    }

    public static string EncryptString(string key, string plainInput)
    {
    byte[] iv = new byte[16];
    byte[] array;
    using (Aes aes = Aes.Create())
    {
    aes.Key = Encoding.UTF8.GetBytes(key);
    aes.IV = iv;
    ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
    using (MemoryStream memoryStream = new MemoryStream())
    {
    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
    {
    using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
    {
    streamWriter.Write(plainInput);
    }

    array = memoryStream.ToArray();
    }
    }
    }

    return Convert.ToBase64String(array);
    }

    public static string DecryptString(string key, string cipherText)
    {
    byte[] iv = new byte[16];
    byte[] buffer = Convert.FromBase64String(cipherText);
    using (Aes aes = Aes.Create())
    {
    aes.Key = Encoding.UTF8.GetBytes(key);
    aes.IV = iv;
    ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
    using (MemoryStream memoryStream = new MemoryStream(buffer))
    {
    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read))
    {
    using (StreamReader streamReader = new StreamReader((Stream)cryptoStream))
    {
    return streamReader.ReadToEnd();
    }
    }
    }
    }
    }
    }
    36 changes: 36 additions & 0 deletions Get Set.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    class ClientListConnection
    {
    private string connection; // field
    public string Connection // property
    {
    get { return connection; }
    set { connection = value; }
    }
    }

    class Program
    {
    static void Main(string[] args)
    {
    ClientListConnection myObj = new ClientListConnection();
    myObj.Connection = "Your Connection String";
    }
    }

    // or

    class Person
    {
    public string Name // property
    { get; set; }
    }

    class Program
    {
    static void Main(string[] args)
    {
    Person myObj = new Person();
    myObj.Name = "Liam";
    Console.WriteLine(myObj.Name);
    }
    }
  5. xCONFLiCTiONx revised this gist Feb 17, 2020. 2 changed files with 57 additions and 30 deletions.
    59 changes: 30 additions & 29 deletions RedirectStandardOutput.cs
    Original file line number Diff line number Diff line change
    @@ -1,42 +1,43 @@
    private static void RunCommand(string filename, string args)
    private static void RunCommand(string directory, string filename, string args)
    {
    using (Process process = new Process())
    {
    ProcessStartInfo startInfo = new ProcessStartInfo
    {
    WindowStyle = ProcessWindowStyle.Hidden,
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    CreateNoWindow = true,
    UseShellExecute = false,
    StandardOutputEncoding = Encoding.GetEncoding(437),
    FileName = filename,
    Arguments = args
    };

    process.EnableRaisingEvents = true;
    process.EnableRaisingEvents = true;
    process.StartInfo = startInfo;

    process.Exited += new EventHandler(ProcExited);
    process.ErrorDataReceived += Proc_DataReceived;
    process.OutputDataReceived += Proc_DataReceived;
    using (Process process = new Process())
    {
    ProcessStartInfo startInfo = new ProcessStartInfo
    {
    WindowStyle = ProcessWindowStyle.Hidden,
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    CreateNoWindow = true,
    UseShellExecute = false,
    StandardOutputEncoding = Encoding.GetEncoding(437),
    WorkingDirectory = directory,
    FileName = filename,
    Arguments = args
    };

    process.Start();
    process.EnableRaisingEvents = true;
    process.EnableRaisingEvents = true;
    process.StartInfo = startInfo;

    process.BeginErrorReadLine();
    process.BeginOutputReadLine();
    process.Exited += new EventHandler(ProcExited);
    process.ErrorDataReceived += Proc_DataReceived;
    process.OutputDataReceived += Proc_DataReceived;

    process.WaitForExit();
    }
    process.Start();

    process.BeginErrorReadLine();
    process.BeginOutputReadLine();

    process.WaitForExit();
    }
    }

    private static void Proc_DataReceived(object sender, DataReceivedEventArgs e)
    {
    Logging.Info(e.Data, "Full Checkup");
    EasyLogger.Info(e.Data);
    }

    private static void ProcExited(object sender, EventArgs e)
    {
    // Process has exited
    EasyLogger.Info("Process Exited..." + Environment.NewLine);
    }
    28 changes: 27 additions & 1 deletion Strings.cs
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,26 @@
    EasyLogger.Info("Arguments: " + args[0].NullIfEmpty() ?? string.Empty + args[2].NullIfEmpty() ?? string.Empty + args[3].NullIfEmpty() ?? string.Empty + args[4].NullIfEmpty() ?? string.Empty);

    public static class StringExtensions
    {
    public static string NullIfEmpty(this string s)
    {
    return string.IsNullOrEmpty(s) ? null : s;
    }
    public static string NullIfWhiteSpace(this string s)
    {
    return string.IsNullOrEmpty(s) ? null : s;
    }
    }

    // Get first 3 letter from string
    char[] array = BarcodeDataTemp.Take(3).ToArray();
    // or
    string str = BarcodeDataTemp.Substring(0, 5);
    // or with error checking
    string UIDTemp = null;
    if(!string.IsNullOrEmpty(BarcodeDataTemp) && BarcodeDataTemp.Length >= 3)
    UIDTemp = BarcodeDataTemp.Substring(0, 3);

    // Split
    char[] delimiterChars = { ' ', ',', '.', ':', '\t' };

    @@ -16,4 +39,7 @@
    // Split
    string somestring = "this is some text that is here!";
    somestring.Split(new[] { "some text" }, StringSplitOptions.None)[0]
    somestring.Split(new[] { "some text" }, StringSplitOptions.None)[1]
    somestring.Split(new[] { "some text" }, StringSplitOptions.None)[1]

    // or
    string[] args = arg.Split(',');
  6. xCONFLiCTiONx revised this gist Feb 4, 2020. 1 changed file with 19 additions and 0 deletions.
    19 changes: 19 additions & 0 deletions Strings.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    // Split
    char[] delimiterChars = { ' ', ',', '.', ':', '\t' };

    string text = "one\ttwo three:four,five six seven";
    System.Console.WriteLine($"Original text: '{text}'");

    string[] words = text.Split(delimiterChars);
    System.Console.WriteLine($"{words.Length} words in text:");

    foreach (var word in words)
    {
    System.Console.WriteLine($"<{word}>");
    }


    // Split
    string somestring = "this is some text that is here!";
    somestring.Split(new[] { "some text" }, StringSplitOptions.None)[0]
    somestring.Split(new[] { "some text" }, StringSplitOptions.None)[1]
  7. xCONFLiCTiONx revised this gist Feb 2, 2020. 1 changed file with 0 additions and 26 deletions.
    26 changes: 0 additions & 26 deletions Check if process is running.cs
    Original file line number Diff line number Diff line change
    @@ -1,29 +1,3 @@
    // Pinvoke Quit
    internal const uint WM_QUIT = 0x12;
    [DllImport("user32.dll", EntryPoint = "PostThreadMessage", CharSet = CharSet.Unicode)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool PostThreadMessage(int idThread, uint Msg, IntPtr wParam, IntPtr lParam);

    foreach (Process process in Process.GetProcessesByName("APPNAME"))
    {
    if (process.Id != Process.GetCurrentProcess().Id)
    {
    try
    {
    foreach (ProcessThread thread in process.Threads)
    {
    PostThreadMessage(thread.Id, WM_QUIT, IntPtr.Zero, IntPtr.Zero);
    }
    }
    catch (Exception ex)
    {
    ErrorHandler(ex);
    }
    }
    }



    Process[] pname = Process.GetProcessesByName("APPNAME");
    if (pname.Length == 0)
    {
  8. xCONFLiCTiONx revised this gist Jan 26, 2020. 1 changed file with 13 additions and 0 deletions.
    13 changes: 13 additions & 0 deletions Exception Handler.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    AppDomain.CurrentDomain.UnhandledException += AppDomain_UnhandledException;
    Application.ThreadException += Application_ThreadException;
    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

    static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
    EasyLogger.Error(e.Exception.Message + " Application.ThreadException");
    }

    static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
    EasyLogger.Error(((Exception)e.ExceptionObject).Message + " AppDomain.UnhandledException");
    }
  9. xCONFLiCTiONx revised this gist Jan 18, 2020. 2 changed files with 116 additions and 15 deletions.
    25 changes: 10 additions & 15 deletions Catch Handler.cs
    Original file line number Diff line number Diff line change
    @@ -1,19 +1,14 @@
    try
    {

    }
    catch (Exception ex)
    {
    ErrorHandler(ex.Message, ex.GetBaseException().ToString());
    }
    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

    public static void ErrorHandler(string message, string ex)
    private static void CurrentDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
    {
    MessageBox.Show("Error: " + ex, message, MessageBoxButtons.OK, MessageBoxIcon.Error);
    Trace.WriteLine(DateTime.Now + Resources.ResourceManager.GetString("Error") + message + "\n" + ex + "\n");
    return;
    }

    var ex = e.ExceptionObject as Exception;

    if (null == ex) return;

    ex.GetBaseException() + Environment.NewLine + ex.TargetSite, ex.Message
    // Log this error. Logging the exception doesn't correct the problem but at least now
    // you may have more insight as to why the exception is being thrown.
    Debug.WriteLine("Unhandled Exception: " + ex.Message);
    Debug.WriteLine("Unhandled Exception: " + ex);
    MessageBox.Show(ex.Message);
    }
    106 changes: 106 additions & 0 deletions Rolling String.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,106 @@
    using System;
    using System.Collections.Generic;

    namespace read_input_stream
    {
    // parser state to switch between checking and reading
    enum ParserState
    {
    CheckForPrefix,
    ReadQRCode
    }

    class Program
    {
    // static variables, could be encapuslated into a class object
    // could also read values such as the prefix from a config file
    const int qrCodeLength = 10;
    const string prefix = "UID#";
    static ParserState state = ParserState.CheckForPrefix;
    static char[] rollingArray = new char[prefix.Length];
    static List<char> qrCodeBuilder;

    static void Main(string[] args)
    {
    Console.WriteLine("Type a string and then hit enter:");

    var fakeStream = Console.ReadLine().ToCharArray();

    foreach (var value in fakeStream)
    {
    // process one char value at a time
    // allows using any stream of data
    ProcessNextChar(value);
    }

    System.Console.WriteLine("... Done.");
    }

    private static void ProcessNextChar(char value)
    {
    // based on program state either use next chart to
    // watch for known prefix or read QR code from input
    switch (state)
    {
    case ParserState.CheckForPrefix:
    CheckForPrefixMethod(value);
    break;
    case ParserState.ReadQRCode:
    ReadQRCodeMethod(value);
    break;
    default:
    System.Console.WriteLine($"Invalid ParserState: {state}");
    break;
    }
    }

    private static void CheckForPrefixMethod(char value)
    {
    // shift chars
    for (int i = 0; i < rollingArray.Length; i++)
    {
    var nextIndex = i + 1;
    if (nextIndex < rollingArray.Length)
    {
    rollingArray[i] = rollingArray[i + 1];
    }
    }

    // add to end
    rollingArray[rollingArray.Length - 1] = value;

    // compare to known prefix
    // if match change state
    var rollingInputString = new string(rollingArray);

    if(rollingInputString == prefix)
    {
    state = ParserState.ReadQRCode;
    }
    }

    private static void ReadQRCodeMethod(char value)
    {
    // ensure we have a list to work with
    if(qrCodeBuilder == null)
    {
    qrCodeBuilder = new List<char>(qrCodeLength);
    }

    // add char to list
    qrCodeBuilder.Add(value);

    if(qrCodeBuilder.Count == qrCodeLength)
    {
    // event to save qrCode id to database
    System.Console.WriteLine($"QR Code: {new string(qrCodeBuilder.ToArray())}");

    // clear our builder for the next qr code
    qrCodeBuilder.Clear();

    // change state back to checking for prefix
    state = ParserState.CheckForPrefix;
    }
    }
    }
    }
  10. xCONFLiCTiONx revised this gist Jan 18, 2020. 3 changed files with 9 additions and 72 deletions.
    9 changes: 0 additions & 9 deletions Dispose.cs
    Original file line number Diff line number Diff line change
    @@ -13,13 +13,4 @@ public void Dispose()
    Dispose(true);
    GC.SuppressFinalize(this);
    }
    }

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
    // base.OnFormClosing(e);

    if (e.CloseReason == CloseReason.WindowsShutDown) return;

    Dispose();
    }
    63 changes: 0 additions & 63 deletions IDisposable.cs
    Original file line number Diff line number Diff line change
    @@ -1,63 +0,0 @@
    public partial class MainWindow : Window, IDisposable

    private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
    Dispose(true); // Make sure and call Closing += MainWindow_Closing; somewhere in the startup
    }

    #region IDisposable Support
    private bool disposedValue = false; // To detect redundant calls

    protected virtual void Dispose(bool disposing)
    {
    if (!disposedValue)
    {
    if (disposing)
    {
    // Examples of what to dispose and then exit
    if (ms != null)
    ms.Dispose();
    if (destImage != null)
    destImage.Dispose();
    if (image != null)
    image.Dispose();
    if (outputImage != null)
    outputImage.Dispose();
    if (ImagePath != null)
    ImagePath.Dispose();
    if (dImg != null)
    dImg.Dispose();

    panel1.Children.Clear();
    grid1.Children.Clear();
    b.Click -= B_Click;
    b.MouseEnter -= B_MouseEnter;
    b.MouseLeave -= B_MouseLeave;
    b.MouseRightButtonDown -= B_MouseRightButtonDown;
    scrollViewer.PreviewMouseWheel -= new System.Windows.Input.MouseWheelEventHandler(OnPreviewMouseWheelScrolled);
    SystemEvents.DisplaySettingsChanged -= new EventHandler(DisplayChanged);
    Closing -= MainWindow_Closing;
    Environment.Exit(0);
    }

    // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
    // TODO: set large fields to null.

    disposedValue = true;
    }
    }

    // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
    // ~MainWindow() {
    // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
    // Dispose(false);
    // }

    // This code added to correctly implement the disposable pattern.
    public void Dispose()
    {
    // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
    Dispose(true);
    GC.SuppressFinalize(this);
    }
    #endregion
    9 changes: 9 additions & 0 deletions Override.cs
    Original file line number Diff line number Diff line change
    @@ -10,4 +10,13 @@ protected override void OnClosed(EventArgs e)
    base.OnClosed(e);

    // put code here
    }

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
    // base.OnFormClosing(e);

    if (e.CloseReason == CloseReason.WindowsShutDown) return;

    Dispose();
    }
  11. xCONFLiCTiONx revised this gist Jan 17, 2020. 1 changed file with 13 additions and 0 deletions.
    13 changes: 13 additions & 0 deletions Override.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    protected override void OnLoad(EventArgs e)
    {
    base.OnLoad(e);

    // put code here
    }

    protected override void OnClosed(EventArgs e)
    {
    base.OnClosed(e);

    // put code here
    }
  12. xCONFLiCTiONx revised this gist Jan 16, 2020. 1 changed file with 9 additions and 0 deletions.
    9 changes: 9 additions & 0 deletions Dispose.cs
    Original file line number Diff line number Diff line change
    @@ -13,4 +13,13 @@ public void Dispose()
    Dispose(true);
    GC.SuppressFinalize(this);
    }
    }

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
    // base.OnFormClosing(e);

    if (e.CloseReason == CloseReason.WindowsShutDown) return;

    Dispose();
    }
  13. xCONFLiCTiONx created this gist Jan 13, 2020.
    1 change: 1 addition & 0 deletions # Useful C# References.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    # Useful C# References
    25 changes: 25 additions & 0 deletions 32 or 64 bit Check.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    Environment.Is64BitOperatingSystem;
    Environment.Is64BitProcess;

    // or

    if (IntPtr.Size == 8)
    {
    // 64 bit machine
    }
    else if (IntPtr.Size == 4)
    {
    // 32 bit machine
    }

    // or

    bool is64Bit = System.Environment.Is64BitOperatingSystem;
    if (is64Bit)
    {

    }
    else
    {

    }
    8 changes: 8 additions & 0 deletions Admin Check.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    using System.Security.Principal;

    public static bool IsAdministrator()
    {
    var identity = WindowsIdentity.GetCurrent();
    var principal = new WindowsPrincipal(identity);
    return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    25 changes: 25 additions & 0 deletions Assembly.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    AppDomain.CurrentDomain.BaseDirectory // Directory

    using System.Reflection;
    Assembly.GetEntryAssembly().Location // Exe File
    Assembly.GetExecutingAssembly().GetName().Name // Program Name
    Assembly.GetEntryAssembly().GetName().Version;

    // GUID
    var assembly = typeof(Program).Assembly;
    var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0];
    var id = attribute.Value;

    // or (not sure how accurate this is anymore)
    static Assembly assembly = Assembly.GetExecutingAssembly();
    static Mutex mutex = new Mutex(true, assembly.GetType().GUID.ToString());


    public static string AssemblyDirectory {
    get {
    string codeBase = Assembly.GetExecutingAssembly().CodeBase;
    UriBuilder uri = new UriBuilder(codeBase);
    string path = Uri.UnescapeDataString(uri.Path);
    return Path.GetDirectoryName(path);
    }
    }
    10 changes: 10 additions & 0 deletions Async Task.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    public static async Task Method1()
    {
    await Task.Run(() =>
    {
    for (int i = 0; i < 100; i++)
    {
    Console.WriteLine(" Method 1");
    }
    });
    }
    52 changes: 52 additions & 0 deletions Attributes.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    // File Attributes [C#]

    string filePath = @"c:\test.txt";

    // get file attributes
    FileAttributes fileAttributes = File.GetAttributes(filePath);

    Set file attributes
    To set file attributes use static method File.SetAttri­butes. Parameter of the method is a bitwise combination of FileAttributes enumeration.

    // clear all file attributes
    File.SetAttributes(filePath, FileAttributes.Normal);

    // set just only archive and read only attributes (no other attribute will set)
    File.SetAttributes(filePath, FileAttributes.Archive |
    FileAttributes.ReadOnly);




    // check whether a file is read only
    bool isReadOnly = ((File.GetAttributes(filePath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly);

    // check whether a file is hidden
    bool isHidden = ((File.GetAttributes(filePath) & FileAttributes.Hidden) == FileAttributes.Hidden);

    // check whether a file has archive attribute
    bool isArchive = ((File.GetAttributes(filePath) & FileAttributes.Archive) == FileAttributes.Archive);

    // check whether a file is system file
    bool isSystem = ((File.GetAttributes(filePath) & FileAttributes.System) == FileAttributes.System);





    // set (add) hidden attribute (hide a file)
    File.SetAttributes(filePath, File.GetAttributes(filePath) | FileAttributes.Hidden);

    // set (add) both archive and read only attributes
    File.SetAttributes(filePath, File.GetAttributes(filePath) | (FileAttributes.Archive |
    FileAttributes.ReadOnly));

    Delete/clear file attributes from current ones
    To delete file attributes from the existing ones get the current file attributes first and use AND (&) operator with a mask (bitwise complement of desired attributes combination).

    // delete/clear hidden attribute
    File.SetAttributes(filePath, File.GetAttributes(filePath) & ~FileAttributes.Hidden);

    // delete/clear archive and read only attributes
    File.SetAttributes(filePath, File.GetAttributes(filePath) & ~(FileAttributes.Archive |
    FileAttributes.ReadOnly));
    31 changes: 31 additions & 0 deletions AutoClosingMessageBox.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    AutoClosingMessageBox.Show("Message", "Caption", 2000);

    public class AutoClosingMessageBox
    {
    System.Threading.Timer _timeoutTimer;
    string _caption;
    AutoClosingMessageBox(string text, string caption, int timeout)
    {
    _caption = caption;
    _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
    null, timeout, System.Threading.Timeout.Infinite);
    using (_timeoutTimer)
    MessageBox.Show(text, caption);
    }
    public static void Show(string text, string caption, int timeout)
    {
    new AutoClosingMessageBox(text, caption, timeout);
    }
    void OnTimerElapsed(object state)
    {
    IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox
    if (mbWnd != IntPtr.Zero)
    SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
    _timeoutTimer.Dispose();
    }
    const int WM_CLOSE = 0x0010;
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
    }
    46 changes: 46 additions & 0 deletions Background Worker.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    private delegate void WorkerDelegate();
    private void ActualWork()
    {
    // Do the background work here
    }
    public void ActualWorkAsync()
    {
    WorkerDelegate worker = new WorkerDelegate(ActualWork);
    AsyncCallback completedCallback = new AsyncCallback(Callback);
    AsyncOperation async = AsyncOperationManager.CreateOperation(null);
    worker.BeginInvoke(completedCallback, async);

    }
    private void Callback(IAsyncResult ar)
    {
    WorkerDelegate worker = (WorkerDelegate)((AsyncResult)ar).AsyncDelegate;
    AsyncOperation async = (AsyncOperation)ar.AsyncState;
    worker.EndInvoke(ar);

    AsyncCompletedEventArgs completedArgs = new AsyncCompletedEventArgs(null, false, null);
    async.PostOperationCompleted(delegate(object e) { onWorkCompleted((AsyncCompletedEventArgs)e); },completedArgs);
    }
    protected void onWorkCompleted(AsyncCompletedEventArgs e)
    {

    }

    // or simplified version

    BackgroundWorker worker;
    private void Worker()
    {
    worker = new BackgroundWorker();
    worker.DoWork += DoWork;
    worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
    worker.RunWorkerAsync();
    }
    private void DoWork(object sender, DoWorkEventArgs e)
    {
    // Do the background work here
    }
    private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    worker.DoWork -= DoWork;
    worker.RunWorkerCompleted -= Worker_RunWorkerCompleted;
    }
    70 changes: 70 additions & 0 deletions BlurBehind.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,70 @@
    // Put in your main
    protected override void OnContentRendered(EventArgs e)
    {
    base.OnContentRendered(e);

    BlurBehind.EnableBlur(mainWindow);
    }


    // BlurBehind.cs
    [DllImport("user32.dll")]
    internal static extern int SetWindowCompositionAttribute(IntPtr hwnd, ref WindowCompositionAttributeData data);

    [StructLayout(LayoutKind.Sequential)]
    internal struct WindowCompositionAttributeData
    {
    public WindowCompositionAttribute Attribute;
    public IntPtr Data;
    public int SizeOfData;
    }

    internal enum WindowCompositionAttribute
    {
    // ...
    WCA_ACCENT_POLICY = 19
    // ...
    }

    internal enum AccentState
    {
    ACCENT_DISABLED = 0,
    ACCENT_ENABLE_GRADIENT = 1,
    ACCENT_ENABLE_TRANSPARENTGRADIENT = 2,
    ACCENT_ENABLE_BLURBEHIND = 3,
    ACCENT_INVALID_STATE = 4
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct AccentPolicy
    {
    public AccentState AccentState;
    public int AccentFlags;
    public int GradientColor;
    public int AnimationId;
    }





    internal void EnableBlur()
    {
    var windowHelper = new WindowInteropHelper(this);

    var accent = new AccentPolicy();
    var accentStructSize = Marshal.SizeOf(accent);
    accent.AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND;

    var accentPtr = Marshal.AllocHGlobal(accentStructSize);
    Marshal.StructureToPtr(accent, accentPtr, false);

    var data = new WindowCompositionAttributeData();
    data.Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY;
    data.SizeOfData = accentStructSize;
    data.Data = accentPtr;

    SetWindowCompositionAttribute(windowHelper.Handle, ref data);

    Marshal.FreeHGlobal(accentPtr);
    }
    12 changes: 12 additions & 0 deletions CMD Hidden.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    string args = "args";
    string program = "/C sc start" + " " + args;
    using (Process proc = new Process())
    {
    proc.StartInfo.FileName = "CMD.exe";
    proc.StartInfo.Arguments = program;
    proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    proc.StartInfo.CreateNoWindow = true;
    proc.StartInfo.Verb = "runas"; // run as admin
    proc.Start();
    proc.WaitForExit();
    }
    19 changes: 19 additions & 0 deletions Catch Handler.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    try
    {

    }
    catch (Exception ex)
    {
    ErrorHandler(ex.Message, ex.GetBaseException().ToString());
    }

    public static void ErrorHandler(string message, string ex)
    {
    MessageBox.Show("Error: " + ex, message, MessageBoxButtons.OK, MessageBoxIcon.Error);
    Trace.WriteLine(DateTime.Now + Resources.ResourceManager.GetString("Error") + message + "\n" + ex + "\n");
    return;
    }



    ex.GetBaseException() + Environment.NewLine + ex.TargetSite, ex.Message
    4 changes: 4 additions & 0 deletions Check If Integer.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,4 @@
    if (int.TryParse(SomeNumber, out int value))
    {

    }
    80 changes: 80 additions & 0 deletions Check if process is running.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,80 @@
    // Pinvoke Quit
    internal const uint WM_QUIT = 0x12;
    [DllImport("user32.dll", EntryPoint = "PostThreadMessage", CharSet = CharSet.Unicode)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool PostThreadMessage(int idThread, uint Msg, IntPtr wParam, IntPtr lParam);

    foreach (Process process in Process.GetProcessesByName("APPNAME"))
    {
    if (process.Id != Process.GetCurrentProcess().Id)
    {
    try
    {
    foreach (ProcessThread thread in process.Threads)
    {
    PostThreadMessage(thread.Id, WM_QUIT, IntPtr.Zero, IntPtr.Zero);
    }
    }
    catch (Exception ex)
    {
    ErrorHandler(ex);
    }
    }
    }



    Process[] pname = Process.GetProcessesByName("APPNAME");
    if (pname.Length == 0)
    {
    Thread.Sleep(500);
    }
    else
    {

    }

    // OR

    class MyProcess
    {
    void BindToRunningProcesses()
    {
    // Get the current process.
    Process currentProcess = Process.GetCurrentProcess();

    // Get all processes running on the local computer.
    Process[] localAll = Process.GetProcesses();

    // Get all instances of Notepad running on the local computer.
    // This will return an empty array if notepad isn't running.
    Process[] localByName = Process.GetProcessesByName("notepad");

    // Get a process on the local computer, using the process id.
    // This will throw an exception if there is no such process.
    Process localById = Process.GetProcessById(1234);


    // Get processes running on a remote computer. Note that this
    // and all the following calls will timeout and throw an exception
    // if "myComputer" and 169.0.0.0 do not exist on your local network.

    // Get all processes on a remote computer.
    Process[] remoteAll = Process.GetProcesses("myComputer");

    // Get all instances of Notepad running on the specific computer, using machine name.
    Process[] remoteByName = Process.GetProcessesByName("notepad", "myComputer");

    // Get all instances of Notepad running on the specific computer, using IP address.
    Process[] ipByName = Process.GetProcessesByName("notepad", "169.0.0.0");

    // Get a process on a remote computer, using the process id and machine name.
    Process remoteById = Process.GetProcessById(2345, "myComputer");
    }

    static void Main()
    {
    MyProcess myProcess = new MyProcess();
    myProcess.BindToRunningProcesses();
    }
    }
    45 changes: 45 additions & 0 deletions Close Another App.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    // Pinvoke Quit
    internal const uint WM_QUIT = 0x12;
    [DllImport("user32.dll", EntryPoint = "PostThreadMessage", CharSet = CharSet.Unicode)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool PostThreadMessage(int idThread, uint Msg, IntPtr wParam, IntPtr lParam);

    foreach (Process process in Process.GetProcessesByName("APPNAME"))
    {
    if (process.Id != Process.GetCurrentProcess().Id)
    {
    try
    {
    foreach (ProcessThread thread in process.Threads)
    {
    PostThreadMessage(thread.Id, WM_QUIT, IntPtr.Zero, IntPtr.Zero);
    }
    }
    catch (Exception ex)
    {
    ErrorHandler(ex);
    }
    }
    }




    // or pinvoke closing
    internal const int WM_CLOSE = 0x0010;
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    internal static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

    NativeMethods.SendMessage(hWindow, NativeMethods.WM_CLOSE, IntPtr.Zero, IntPtr.Zero);



    // or Process
    Process[] processes = Process.GetProcessesByName("APPNAME");
    foreach (Process process in processes)
    {
    if (process.Id != Process.GetCurrentProcess().Id)
    {
    process.CloseMainWindow();
    }
    }
    37 changes: 37 additions & 0 deletions Colors.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    // WPF Recolor in code behind
    button1.Background = Brushes.Gray;

    // Windows Accent
    // Reference PresentationCore and PresentationFramework
    static System.Windows.Media.Color color = System.Windows.SystemParameters.WindowGlassColor;

    System.Windows.SystemParameters.StaticPropertyChanged += WindowGlassBrush_Changed;

    window.BorderBrush = System.Windows.SystemParameters.WindowGlassBrush;




    // ColorShade

    namespace APPNAME
    {
    public static class ColorHelper
    {
    private static System.Drawing.Color TempColor;

    public static System.Windows.Media.SolidColorBrush ColorShade(System.Windows.Media.Color color, bool SetLightColor)
    {
    if (SetLightColor)
    {
    TempColor = System.Windows.Forms.ControlPaint.Light(System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B));
    }
    else
    {
    TempColor = System.Windows.Forms.ControlPaint.Dark(System.Drawing.Color.FromArgb(color.A, color.R, color.G, color.B));
    }

    return new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(TempColor.A, TempColor.R, TempColor.G, TempColor.B));
    }
    }
    }
    191 changes: 191 additions & 0 deletions Context Menu.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,191 @@
    // Main

    public class MyColorTable : ProfessionalColorTable
    {
    public override Color MenuItemBorder
    {
    get { return Color.FromArgb(0); }
    }
    public override Color MenuItemSelected
    {
    get { return Color.FromArgb(0, 82, 164); }
    }
    public override Color ToolStripDropDownBackground
    {
    get { return Color.FromArgb(22, 22, 22); }
    }
    public override Color ImageMarginGradientBegin
    {
    get { return Color.FromArgb(22, 22, 22); }
    }
    public override Color ImageMarginGradientMiddle
    {
    get { return Color.FromArgb(22, 22, 22); }
    }
    public override Color ImageMarginGradientEnd
    {
    get { return Color.FromArgb(22, 22, 22); }
    }
    }

    public class MyRenderer : ToolStripProfessionalRenderer
    {
    public MyRenderer()
    : base(new MyColorTable())
    {
    }
    protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e)
    {
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    var r = new Rectangle(e.ArrowRectangle.Location, e.ArrowRectangle.Size);
    r.Inflate(-2, -6);

    Pen pen = new Pen(Color.FromArgb(255, 230, 230, 230));
    e.Graphics.DrawLines(pen, new Point[]{
    new Point(r.Left, r.Top),
    new Point(r.Right, r.Top + r.Height /2),
    new Point(r.Left, r.Top+ r.Height)});
    }

    protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e)
    {
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    var r = new Rectangle(e.ImageRectangle.Location, e.ImageRectangle.Size);
    r.Inflate(-4, -6);
    Pen pen = new Pen(Color.FromArgb(255, 230, 230, 230));
    e.Graphics.DrawLines(pen, new Point[]{
    new Point(r.Left, r.Bottom - r.Height /2),
    new Point(r.Left + r.Width /3, r.Bottom),
    new Point(r.Right, r.Top)});
    }
    }


    // Make sure to subscribe to this event
    private void Form_Load(object sender, EventArgs e)
    {
    this._shortcutsMenuItem.ForeColor = Color.FromArgb(230, 230, 230);
    this.contextMenuStrip1.ForeColor = Color.FromArgb(230, 230, 230);
    this.contextMenuStrip1.Name = "contextMenuStrip1";
    this.contextMenuStrip1.RenderMode = ToolStripRenderMode.ManagerRenderMode;
    this.contextMenuStrip1.ShowCheckMargin = false;
    this.contextMenuStrip1.ShowImageMargin = true;
    this.contextMenuStrip1.Size = new Size(242, 204);

    this.contextMenuStrip1.Renderer = new MyRenderer();

    if (ShortcutsFolder != null)
    {
    foreach (var _shortcut in ShortcutsFolder)
    {
    _shortcutItem = new ToolStripMenuItem();
    _shortcutItem.ForeColor = Color.White;
    _shortcutItem.Name = Path.GetFileNameWithoutExtension(_shortcut);
    _shortcutItem.Text = Path.GetFileNameWithoutExtension(_shortcut);
    try
    {
    if (File.Exists(_shortcut))
    {
    IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();

    IWshRuntimeLibrary.IWshShortcut link = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(_shortcut);

    _shortcutItem.Image = Icon.ExtractAssociatedIcon(link.TargetPath).ToBitmap();
    }
    }
    catch (Exception)
    {
    // ignore
    }
    _shortcutItem.Click += Open_shortcut_Click;

    _shortcutsMenuItem.DropDownItems.Add(_shortcutItem);
    }
    this.contextMenuStrip1.Items.Add(_shortcutsMenuItem);
    this.contextMenuStrip1.Items.Add(toolStripSeparator1);
    }

    this.contextMenuStrip1.Items.AddRange(new ToolStripItem[] {
    this.ExitMenuItem});

    contextMenuStrip1.Opacity = 0.8;
    _shortcutsMenuItem.DropDown.Opacity = 0.8;
    }


    // Designer.cs
    using AppName.Properties;

    namespace AppName
    {
    partial class AppNameForm
    {
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
    if (disposing && (components != null))
    {
    components.Dispose();
    }
    base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
    this.components = new System.ComponentModel.Container();
    System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AppNameForm));
    notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
    this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
    this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
    this.ExitMenuItem = new System.Windows.Forms.ToolStripMenuItem();
    this._shortcutsMenuItem = new System.Windows.Forms.ToolStripMenuItem();
    this.contextMenuStrip1.SuspendLayout();
    this.SuspendLayout();
    //
    // notifyIcon1
    //
    notifyIcon1.ContextMenuStrip = this.contextMenuStrip1;
    notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon")));
    //
    // ExitMenuItem
    //
    this.ExitMenuItem.Name = "ExitMenuItem";
    this.ExitMenuItem.Size = new System.Drawing.Size(241, 22);
    this.ExitMenuItem.Text = "Exit";
    this.ExitMenuItem.Click += new System.EventHandler(this.ExitMenuItem_Click);
    //
    // toolStripSeparator1
    //
    this.toolStripSeparator1.Name = "toolStripSeparator";
    this.toolStripSeparator1.Size = new System.Drawing.Size(238, 6);
    //
    // _shortcutsMenuItem
    //
    this._shortcutsMenuItem.Name = "_shortcutsMenuItem";
    this._shortcutsMenuItem.Size = new System.Drawing.Size(241, 22);
    this._shortcutsMenuItem.Text = "Shortcuts";

    }

    #endregion
    private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
    private System.Windows.Forms.ToolStripMenuItem ExitMenuItem;
    private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
    private System.Windows.Forms.ToolStripMenuItem _shortcutsMenuItem;
    static internal System.Windows.Forms.NotifyIcon notifyIcon1;
    }
    }
    35 changes: 35 additions & 0 deletions Crash Handler.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    using System;
    using System.Security.Permissions;

    public class Example
    {
    [SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlAppDomain)]
    public static void Main()
    {
    AppDomain currentDomain = AppDomain.CurrentDomain;
    currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

    try {
    throw new Exception("1");
    } catch (Exception e) {
    Console.WriteLine("Catch clause caught : {0} \n", e.Message);
    }

    throw new Exception("2");
    }

    static void MyHandler(object sender, UnhandledExceptionEventArgs args)
    {
    Exception e = (Exception) args.ExceptionObject;
    Console.WriteLine("MyHandler caught : " + e.Message);
    Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
    }
    }
    // The example displays the following output:
    // Catch clause caught : 1
    //
    // MyHandler caught : 2
    // Runtime terminating: True
    //
    // Unhandled Exception: System.Exception: 2
    // at Example.Main()
    25 changes: 25 additions & 0 deletions Create Shortcut.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    using IWshRuntimeLibrary; // Select the "COM" tab, find and select the "Windows Script Host Object Model"

    private void CreateShortcut()
    {
    try
    {
    WshShell lib = new WshShell();

    IWshShortcut _startupShortcut;

    string _programs = Environment.GetFolderPath(Environment.SpecialFolder.Programs);

    _startupShortcut = (IWshShortcut)lib.CreateShortcut(_programs + "\\" + Assembly.GetExecutingAssembly().GetName().Name + "\\" + Assembly.GetExecutingAssembly().GetName().Name + ".lnk");
    _startupShortcut.TargetPath = Assembly.GetEntryAssembly().Location;
    _startupShortcut.WorkingDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
    _startupShortcut.Description = Assembly.GetExecutingAssembly().GetName().Name;
    _startupShortcut.Save();
    }
    catch (Exception ex)
    {
    EasyLogger.Error(ex);
    }
    }


    3 changes: 3 additions & 0 deletions Current Directory.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,3 @@
    static string CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

    AppDomain.CurrentDomain.BaseDirectory
    95 changes: 95 additions & 0 deletions CustomEvent.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,95 @@
    Creating custom eventsSection
    Events can be created with the Event constructor as follows:

    var event = new Event('build');

    // Listen for the event.
    elem.addEventListener('build', function (e) { /* ... */ }, false);

    // Dispatch the event.
    elem.dispatchEvent(event);
    The above code example uses the EventTarget.dispatchEvent() method.

    This constructor is supported in most modern browsers (with Internet Explorer being the exception). For a more verbose approach (which works with Internet Explorer), see the old-fashioned way below.

    Adding custom data – CustomEvent()Section
    To add more data to the event object, the CustomEvent interface exists and the detail property can be used to pass custom data.
    For example, the event could be created as follows:

    var event = new CustomEvent('build', { detail: elem.dataset.time });
    This will then allow you to access the additional data in the event listener:

    function eventHandler(e) {
    console.log('The time is: ' + e.detail);
    }
    The old-fashioned waySection
    The older approach to creating events uses APIs inspired by Java. The following shows an example:

    // Create the event.
    var event = document.createEvent('Event');

    // Define that the event name is 'build'.
    event.initEvent('build', true, true);

    // Listen for the event.
    elem.addEventListener('build', function (e) {
    // e.target matches elem
    }, false);

    // target can be any Element or other EventTarget.
    elem.dispatchEvent(event);
    Event bubblingSection
    It is often desirable to trigger an event from a child element, and have an ancestor catch it; optionally, with data:

    <form>
    <textarea></textarea>
    </form>
    const form = document.querySelector('form');
    const textarea = document.querySelector('textarea');

    // Create a new event, allow bubbling, and provide any data you want to pass to the "details" property
    const eventAwesome = new CustomEvent('awesome', {
    bubbles: true,
    detail: { text: () => textarea.value }
    });

    // The form element listens for the custom "awesome" event and then consoles the output of the passed text() method
    form.addEventListener('awesome', e => console.log(e.detail.text()));

    // As the user types, the textarea inside the form dispatches/triggers the event to fire, and uses itself as the starting point
    textarea.addEventListener('input', e => e.target.dispatchEvent(eventAwesome));
    Creating and dispatching events dynamicallySection
    Elements can listen for events that haven't been created yet:

    <form>
    <textarea></textarea>
    </form>
    const form = document.querySelector('form');
    const textarea = document.querySelector('textarea');

    form.addEventListener('awesome', e => console.log(e.detail.text()));

    textarea.addEventListener('input', function() {
    // Create and dispatch/trigger an event on the fly
    // Note: Optionally, we've also leveraged the "function expression" (instead of the "arrow function expression") so "this" will represent the element
    this.dispatchEvent(new CustomEvent('awesome', { bubbles: true, detail: { text: () => textarea.value } }))
    });
    Triggering built-in eventsSection
    This example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using DOM methods. View the example in action.

    function simulateClick() {
    var event = new MouseEvent('click', {
    view: window,
    bubbles: true,
    cancelable: true
    });
    var cb = document.getElementById('checkbox');
    var cancelled = !cb.dispatchEvent(event);
    if (cancelled) {
    // A handler called preventDefault.
    alert("cancelled");
    } else {
    // None of the handlers called preventDefault.
    alert("not cancelled");
    }
    }
    4 changes: 4 additions & 0 deletions DataGridView.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,4 @@
    // Get value of cell from row selected
    int rowindex = dataGridView1.CurrentCell.RowIndex;
    int columnindex = dataGridView1.CurrentCell.ColumnIndex;
    dataGridView1.Rows[rowindex].Cells[columnindex].Value.ToString();
    16 changes: 16 additions & 0 deletions Dispose.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,16 @@
    public partial class MainWindow : Window, IDisposable
    {
    protected virtual void Dispose(bool disposing)
    {
    if (disposing)
    {
    timer.Close();
    }
    }

    public void Dispose()
    {
    Dispose(true);
    GC.SuppressFinalize(this);
    }
    }
    25 changes: 25 additions & 0 deletions Do While.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    do
    {
    if (!proc.HasExited)
    {
    proc.Refresh();
    if (proc.HasExited)
    {
    goto Finish;
    }
    if (proc.Responding)
    {
    Console.WriteLine("Process is responding...");
    }
    else
    {
    Console.WriteLine("Process is not responding...");
    }
    }
    }
    while (!proc.WaitForExit(500));
    if (proc.HasExited)
    {
    goto Finish;
    }
    Finish:;
    11 changes: 11 additions & 0 deletions Drag Window.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,11 @@
    window.MouseDown += Window_MouseDown;

    private void Window_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
    e.Handled = true;

    if (e.ChangedButton == System.Windows.Input.MouseButton.Left)
    {
    DragMove();
    }
    }
    10 changes: 10 additions & 0 deletions Exit (Proper).cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    if (System.Windows.Forms.Application.MessageLoop)
    {
    // WinForms app
    System.Windows.Forms.Application.Exit();
    }
    else
    {
    // Console app
    System.Environment.Exit(1);
    }
    44 changes: 44 additions & 0 deletions FileSystemWatcher.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    FileSystemWatcher watcher;

    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public MainWindow()
    {
    InitializeComponent();

    if (Args.Length > 1)
    {
    CurrentImage = Args[1];

    ImageFolderWatcher();

    OpenImage(CurrentImage);
    }
    }

    private void ImageFolderWatcher()
    {
    watcher = new FileSystemWatcher();
    watcher.Path = CurrentImage;

    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
    | NotifyFilters.FileName | NotifyFilters.DirectoryName;

    watcher.Filter = "*.*";

    watcher.Changed += new FileSystemEventHandler(OnChanged);
    watcher.Created += new FileSystemEventHandler(OnChanged);
    watcher.Deleted += new FileSystemEventHandler(OnChanged);
    watcher.Renamed += new RenamedEventHandler(OnChanged);

    watcher.EnableRaisingEvents = true;
    }

    private void OnChanged(object source, FileSystemEventArgs e)
    {
    // Do something
    }

    private void OnRenamed(object source, RenamedEventArgs e)
    {
    // Do something
    }
    9 changes: 9 additions & 0 deletions For Loop.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,9 @@
    for (int i = 0; i < (int)count; i++)
    {

    }

    for (int i = 10 - 1; i >= 0; i--)
    {
    Console.WriteLine(i);
    }
    13 changes: 13 additions & 0 deletions Form Closing.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    protected override void OnFormClosing(FormClosingEventArgs e)
    {
    if (variable != null)
    {
    variable.Dispose();
    }

    base.OnFormClosing(e);

    if (e.CloseReason == CloseReason.WindowsShutDown) return;

    this.Visible = false;
    }
    21 changes: 21 additions & 0 deletions Get SID.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    public static SecurityIdentifier SIDState
    {
    get
    {
    WindowsIdentity identity = WindowsIdentity.GetCurrent();

    return identity.User;
    }
    }
    static bool SID(string user)
    {
    if (SIDState != null)
    {
    return true;
    }
    else
    {

    return false;
    }
    }
    23 changes: 23 additions & 0 deletions GetIdleTime.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    public static int GetIdleTime()
    {
    return (Environment.TickCount & Int32.MaxValue)- (int)GetLastInputTime();
    }

    /// <summary>
    /// Get the last input time from the input devices.
    /// Exception:
    /// If it cannot get the last input information then it throws an exception with
    /// the appropriate message.
    /// </summary>
    /// <returns>Last input time in milliseconds.</returns>
    public static uint GetLastInputTime()
    {
    LastInputInfo lastInPut = new LastInputInfo();
    lastInPut.BlockSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInPut);
    if (!GetLastInputInfo(ref lastInPut))
    {
    throw new Exception(GetLastError().ToString());
    }

    return lastInPut.Time;
    }
    124 changes: 124 additions & 0 deletions Guide Button Code.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,124 @@
    //Begin dynamic library
    [DllImport("xinput1_3.dll", EntryPoint = "#100", CharSet = CharSet.Unicode)]
    static extern int gamepadGuide(int playerIndex, out XINPUT_Guide struc);


    public struct XINPUT_Guide
    {
    public UInt32 eventCount;
    public ushort wButtons;
    public Byte bLeftTrigger;
    public Byte bRightTrigger;
    public short sThumbLX;
    public short sThumbLY;
    public short sThumbRX;
    public short sThumbRY;
    }
    public static int guide(int playerIndex, out XINPUT_Guide struc)
    {
    return gamepadGuide(playerIndex, out struc);
    }



    public class Variables
    {
    //Guide Button
    public static NativeMethods.CriticalHandle.XINPUT_Guide xgs;
    }


    public static bool GuideButton = false;

    //End of dynamic library

    //Begin Main Program XBox Guide Button
    static void GuideButtonPress()
    {
    while (true)
    {
    Thread.Sleep(500);
    if (!NativeMethods.CriticalHandle.ScreenDetection.AreApplicationFullScreen() && !Variables.WindowedGame && !Variables.GUIShowing)
    {
    int stat;
    bool value;
    for (int i = 0; i < 4; i++)
    {
    stat = NativeMethods.CriticalHandle.guide(0, out Variables.xgs);
    if (stat != 0)
    {
    continue;
    }
    value = ((Variables.xgs.wButtons & 0x0400) != 0);
    if (value && !Variables.GUIShowing)
    {
    try
    {
    Thread.Sleep(1000);
    int stat2;
    bool value2;
    for (int i2 = 0; i2 < 4; i2++)
    {
    stat2 = NativeMethods.CriticalHandle.guide(0, out Variables.xgs);
    if (stat2 != 0)
    {
    continue;
    }
    value2 = ((Variables.xgs.wButtons & 0x0400) != 0);
    if (value2 && !Variables.GUIShowing)
    {
    if (Variables.GamePadConnected && !Variables.GuideButton)
    {
    Variables.GuideButton = true;
    GamePad.SetVibration(PlayerIndex.One, 0.2f, 0.2f);
    Thread.Sleep(300);
    GamePad.SetVibration(PlayerIndex.One, 0f, 0f);
    }
    Stream stream = null;
    try
    {
    stream = new FileStream(Variables.SysFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    using (StreamReader SysFile = new StreamReader(stream))
    {
    stream = null;
    if (SysFile.ReadToEnd().Contains("Fan=true"))
    {
    try
    {
    using (Process proc = new Process())
    {
    proc.StartInfo.FileName = Environment.CurrentDirectory + @"\FanControl\FanOn.exe";
    proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    proc.Start();
    }
    Variables.Fan = true;
    }
    catch (Exception ex)
    {
    Trace.WriteLine(DateTime.Now + Properties.Resources.ResourceManager.GetString("FailedOperationMessage") + "\n" + " " + ex.Message);
    MessageBox.Show(Properties.Resources.ResourceManager.GetString("FailedOperationMessage") + "\n\n" + ex.Message, Properties.Resources.ResourceManager.GetString("FailedOperationTitle"), MessageBoxButton.OK, MessageBoxImage.Stop);
    }
    }
    }
    }
    finally
    {
    if (stream != null)
    stream.Dispose();
    }
    }
    Thread.Sleep(3000);
    }
    }
    catch (Exception ex)
    {
    Trace.WriteLine(DateTime.Now + Properties.Resources.ResourceManager.GetString("FailedOperationMessage") + "\n" + " " + ex.Message);
    MessageBox.Show(Properties.Resources.ResourceManager.GetString("FailedOperationMessage") + "\n\n" + ex.Message, Properties.Resources.ResourceManager.GetString("FailedOperationTitle"), MessageBoxButton.OK, MessageBoxImage.Stop);
    }
    }
    }
    }
    }
    }

    //End Main
    11 changes: 11 additions & 0 deletions Handle.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,11 @@
    foreach (Process process in Process.GetProcessesByName("notepad"))
    {
    if (process.Id != Process.GetCurrentProcess().Id) //Excludes the process the code is being run from
    {
    foreach (ProcessThread thread in process.Threads)
    {
    int HwND = process.MainWindowHandle.ToInt32();
    // use the handle however you need
    }
    }
    }
    41 changes: 41 additions & 0 deletions Hide Window.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Drawing;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Threading;
    using System.Windows.Forms;

    namespace WindowsFormsApplication1
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    Thread thread = new Thread(bLend);
    thread.Start();
    }

    [DllImport("user32.dll")]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    private void bLend()
    {
    Thread.Sleep(2000);
    Process.Start(@"App\bLend.exe");
    Thread.Sleep(50);
    IntPtr hWnd = FindWindow(null, "bLend Preferences..");
    if (hWnd != IntPtr.Zero) ShowWindow(hWnd, 0);
    Thread.Sleep(1000);
    Environment.Exit(0);
    }
    }
    }
    63 changes: 63 additions & 0 deletions IDisposable.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,63 @@
    public partial class MainWindow : Window, IDisposable

    private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
    Dispose(true); // Make sure and call Closing += MainWindow_Closing; somewhere in the startup
    }

    #region IDisposable Support
    private bool disposedValue = false; // To detect redundant calls

    protected virtual void Dispose(bool disposing)
    {
    if (!disposedValue)
    {
    if (disposing)
    {
    // Examples of what to dispose and then exit
    if (ms != null)
    ms.Dispose();
    if (destImage != null)
    destImage.Dispose();
    if (image != null)
    image.Dispose();
    if (outputImage != null)
    outputImage.Dispose();
    if (ImagePath != null)
    ImagePath.Dispose();
    if (dImg != null)
    dImg.Dispose();

    panel1.Children.Clear();
    grid1.Children.Clear();
    b.Click -= B_Click;
    b.MouseEnter -= B_MouseEnter;
    b.MouseLeave -= B_MouseLeave;
    b.MouseRightButtonDown -= B_MouseRightButtonDown;
    scrollViewer.PreviewMouseWheel -= new System.Windows.Input.MouseWheelEventHandler(OnPreviewMouseWheelScrolled);
    SystemEvents.DisplaySettingsChanged -= new EventHandler(DisplayChanged);
    Closing -= MainWindow_Closing;
    Environment.Exit(0);
    }

    // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
    // TODO: set large fields to null.

    disposedValue = true;
    }
    }

    // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
    // ~MainWindow() {
    // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
    // Dispose(false);
    // }

    // This code added to correctly implement the disposable pattern.
    public void Dispose()
    {
    // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
    Dispose(true);
    GC.SuppressFinalize(this);
    }
    #endregion
    17 changes: 17 additions & 0 deletions Invoke.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    BeginInvoke(new MethodInvoker(DisplayData));

    // FORM
    this.Invoke(new Action(() => {
    Show();
    }));


    // WPF
    Application.Current.Dispatcher.Invoke(delegate
    {
    Show();
    });

    // or

    Dispatcher.Invoke(() => SendToast(false));
    93 changes: 93 additions & 0 deletions Logging.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,93 @@
    //Main
    using static Logger.Logging;
    Log();
    Info("Application started.", "NetworkPing");
    Warning("Application about to exit!", "MyApp");
    Error(ex, "MyApp");

    //Logger.cs
    using System;
    using System.Diagnostics;
    using System.IO;

    class Logging
    {
    static readonly string LogDirectory = Path.GetTempPath() + "\\" + AppDomain.CurrentDomain.FriendlyName;
    internal static string LogFile = LogDirectory + @"\Application.log";
    static readonly string LogBak = LogDirectory + @"\Application.log.bak";

    public static void Log()
    {
    if (!Directory.Exists(LogDirectory))
    {
    Directory.CreateDirectory(LogDirectory);
    }
    if (File.Exists(LogBak))
    {
    File.Delete(LogBak);
    }
    if (File.Exists(LogFile))
    {
    File.Copy(LogFile, LogBak);
    File.Delete(LogFile);
    }
    Trace.Listeners.Clear();
    TextWriterTraceListener twtl = null;
    try
    {
    twtl = new TextWriterTraceListener(LogFile);
    ConsoleTraceListener ctl = null;
    try
    {
    ctl = new ConsoleTraceListener(false);
    Trace.Listeners.Add(twtl);
    Trace.Listeners.Add(ctl);
    Trace.AutoFlush = true;
    }
    finally
    {
    if (ctl != null)
    {
    ctl.Dispose();
    }
    }
    }
    finally
    {
    if (twtl != null)
    {
    twtl.Dispose();
    }
    }
    }

    public static void Error(string message, string module)
    {
    WriteEntry(message, "error", module);
    }

    public static void Error(Exception ex, string module)
    {
    WriteEntry(ex.Message, "error", module);
    }

    public static void Warning(string message, string module)
    {
    WriteEntry(message, "warning", module);
    }

    public static void Info(string message, string module)
    {
    WriteEntry(message, "info", module);
    }

    private static void WriteEntry(string message, string type, string module)
    {
    Trace.WriteLine(
    string.Format("{0} ( {1} - {2} ) | {3}",
    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
    type,
    module,
    message));
    }
    }
    3 changes: 3 additions & 0 deletions MarshalAs & CharSet.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,3 @@
    [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool SHGetSpecialFolderPath(IntPtr hwndOwner, [Out] StringBuilder lpszPath, int nFolder, [MarshalAs(UnmanagedType.Bool)] bool fCreate);
    30 changes: 30 additions & 0 deletions MessageBox.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    private DialogResult MessageForm(string text, string title, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton = MessageBoxDefaultButton.Button2)
    {
    using (Form form = new Form())
    {
    form.Opacity = 0;

    form.Show();

    form.WindowState = FormWindowState.Minimized;

    form.WindowState = FormWindowState.Normal;

    DialogResult dialogResult = MessageBox.Show(form, text, title, buttons, icon, defaultButton);
    if (dialogResult == DialogResult.Yes)
    {
    form.Close();
    }
    return dialogResult;
    }
    }

    // or

    DialogResult dialogResult = MessageBox.Show("Information", "Title", MessageBoxButtons.YesNo);
    if (dialogResult == DialogResult.Yes)
    {
    }
    else if (dialogResult == DialogResult.No)
    {
    }
    79 changes: 79 additions & 0 deletions NotificationIcon.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,79 @@
    using System;
    using System.Windows.Forms;

    namespace NotifyTest
    {
    static class Program
    {
    static NotifyIcon notifyIcon;
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    notifyIcon = new NotifyIcon
    {
    Visible = true,
    Icon = System.Drawing.SystemIcons.Information,
    BalloonTipTitle = "Testing",
    BalloonTipText = "This is only a test... " + Environment.NewLine + Environment.NewLine + "This message will close in 5 seconds."
    };

    notifyIcon.BalloonTipClicked += NotifyIcon_BalloonTipClicked;

    notifyIcon.MouseClick += NotifyIcon_MouseClick;

    notifyIcon.ShowBalloonTip(5000);

    notifyIcon.BalloonTipClosed += NotifyIcon_BalloonTipClosed;


    ContextMenu contextMenu = new ContextMenu();

    MenuItem menuItemClose = new MenuItem("&Close Tray");

    menuItemClose.Click += MenuItemClose_Click;

    contextMenu.MenuItems.Add(menuItemClose);

    notifyIcon.ContextMenu = contextMenu;

    Application.Run();
    }

    private static void NotifyIcon_BalloonTipClosed(object sender, EventArgs e)
    {
    notifyIcon.Visible = false;
    Application.Exit();
    }

    private static void NotifyIcon_Click(object sender, EventArgs e)
    {
    notifyIcon.Visible = false;
    Application.Exit();
    }

    private void NotifyIcon_MouseClick(object sender, MouseEventArgs e)
    {
    if (e.Button == MouseButtons.Right)
    {
    notifyIcon.Visible = false;
    Application.Exit();
    }
    else
    {
    // Show();
    }
    }

    private static void NotifyIcon_BalloonTipClicked(object sender, EventArgs e)
    {
    notifyIcon.Visible = false;
    Application.Exit();
    }
    }
    }
    7 changes: 7 additions & 0 deletions OptionalParameters.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    string[] array = SelectedItemPaths.Cast<string>().ToArray();
    MessageBox.Show(array.ToStringArray());
    MessageBox.Show(array.ToStringArray(true));
    public static string ToStringArray(this string[] array, bool Naming = false)
    {

    }
    14 changes: 14 additions & 0 deletions Performance Counter.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    static PerformanceCounter cpuCounter;
    static PerformanceCounter ramCounter;

    cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
    ramCounter = new PerformanceCounter("Memory", "Available MBytes");


    public string getCurrentCpuUsage(){
    return cpuCounter.NextValue()+"%";
    }

    public string getAvailableRAM(){
    return ramCounter.NextValue()+"MB";
    }
    25 changes: 25 additions & 0 deletions Ping.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    public static bool PingHost(string nameOrAddress)
    {
    bool pingable = false;
    Ping pinger = null;

    try
    {
    pinger = new Ping();
    PingReply reply = pinger.Send(nameOrAddress);
    pingable = reply.Status == IPStatus.Success;
    }
    catch (PingException)
    {
    return false;
    }
    finally
    {
    if (pinger != null)
    {
    pinger.Dispose();
    }
    }

    return pingable;
    }
    98 changes: 98 additions & 0 deletions Pinvoke.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,98 @@
    // Get HResult
    try
    {
    SetWindowLong(explorer.HWND, GWL_EXSTYLE,
    GetWindowLong(explorer.HWND, GWL_EXSTYLE) | WS_EX_LAYERED).GetTypeCode();
    SetLayeredWindowAttributes(explorer.HWND, LWA_COLORKEY, 255, LWA_ALPHA);
    }
    catch (Win32Exception)
    {
    throw new Win32Exception(Marshal.GetLastWin32Error());
    }


    // Notice the .GetTypeCode(); after the request



    // Activate a window from anywhere by attaching to the foreground window
    using System.Windows.Interop;
    using System.Runtime.InteropServices;

    namespace System.Windows
    {
    public static class SystemWindows
    {
    #region Constants

    const UInt32 SWP_NOSIZE = 0x0001;
    const UInt32 SWP_NOMOVE = 0x0002;
    const UInt32 SWP_SHOWWINDOW = 0x0040;

    #endregion

    /// <summary>
    /// Activate a window from anywhere by attaching to the foreground window
    /// </summary>
    public static void GlobalActivate(this Window window)
    {
    var interopHelper = new WindowInteropHelper(PassThroughNonNull(window));
    var thisWindowThreadId = NativeMethods.GetWindowThreadProcessId(interopHelper.Handle, IntPtr.Zero);

    var currentForegroundWindow = NativeMethods.GetForegroundWindow();
    var currentForegroundWindowThreadId = NativeMethods.GetWindowThreadProcessId(currentForegroundWindow, IntPtr.Zero);

    NativeMethods.AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, true);

    NativeMethods.SetWindowPos(interopHelper.Handle, new IntPtr(0), 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW);

    NativeMethods.AttachThreadInput(currentForegroundWindowThreadId, thisWindowThreadId, false);

    if (PassThroughNonNull(window).WindowState == WindowState.Minimized) PassThroughNonNull(window).WindowState = WindowState.Normal;
    PassThroughNonNull(window).Show();
    PassThroughNonNull(window).Focus(); // Changed from Activate(); due to flashing the window which is unwanted for this instance
    }
    static Window PassThroughNonNull(Window window)
    {
    if (window == null)
    throw new ArgumentNullException(window.ToString());
    return window;
    }
    }
    }
    internal static class NativeMethods
    {
    #region Imports

    [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    internal static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    internal static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);

    [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)] // For 32 bit U1
    internal static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, [MarshalAs(UnmanagedType.Bool)] bool fAttach); // For 32 bit U1

    [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)] // For 32 bit U1
    internal static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

    #endregion
    }

    // Use this to activate it
    Focus(); // I use this to make sure it has focus but not needed to bring the window to the top
    SystemWindows.GlobalActivate(this);

    // Can also be used at startup to make sure it starts on top
    private void Window_ContentRendered(object sender, EventArgs e)
    {
    this.Topmost = false;
    }
    private void Window_Initialized(object sender, EventArgs e)
    {
    this.Topmost = true;
    Focus();
    SystemWindows.GlobalActivate(this);
    }
    2 changes: 2 additions & 0 deletions Play Sound.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,2 @@
    System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:\mywavfile.wav");
    player.Play();
    55 changes: 55 additions & 0 deletions Print File.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    private Font verdana10Font;
    private StreamReader reader;

    private void SendToPrinter(string filename)
    {
    reader = new StreamReader(filename);

    verdana10Font = new Font("Verdana", 10);
    PrintDialog printDialog = new PrintDialog();
    printDialog.ShowDialog();

    PrintDocument pd = new PrintDocument();
    pd.PrinterSettings = printDialog.PrinterSettings;

    pd.PrintPage += new PrintPageEventHandler(this.PrintTextFileHandler);

    pd.Print();

    if (reader != null)
    reader.Close();

    File.Delete(filename);
    }

    private void PrintTextFileHandler(object sender, PrintPageEventArgs ppeArgs)
    {
    Graphics g = ppeArgs.Graphics;
    float linesPerPage = 0;
    float yPos = 0;
    int count = 0;

    float leftMargin = ppeArgs.MarginBounds.Left;
    float topMargin = ppeArgs.MarginBounds.Top;
    string line = null;

    linesPerPage = ppeArgs.MarginBounds.Height / verdana10Font.GetHeight(g);

    while (count < linesPerPage && ((line = reader.ReadLine()) != null))
    {
    yPos = topMargin + (count * verdana10Font.GetHeight(g));

    g.DrawString(line, verdana10Font, Brushes.Black, leftMargin, yPos, new StringFormat());

    count++;
    }

    if (line != null)
    {
    ppeArgs.HasMorePages = true;
    }
    else
    {
    ppeArgs.HasMorePages = false;
    }
    }
    60 changes: 60 additions & 0 deletions Process Hidden.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    proc.StartInfo.CreateNoWindow = true;
    proc.StartInfo.UseShellExecute = false;


    string arguments = "";
    proc.StartInfo.Arguments = arguments;
    proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    proc.StartInfo.CreateNoWindow = true;
    proc.StartInfo.FileName = "schtasks.exe";
    proc.Start();
    proc.WaitForExit();
    System.Threading.Thread.Sleep(5000);
    bool running = true;
    while (running)
    {
    if (Process.GetProcessesByName("CLOS2").Length == 0)
    {
    running = false;
    Environment.Exit(0);
    }
    else
    {
    System.Threading.Thread.Sleep(1000);
    }

    }

    //or use

    private static string ExecCommand(string filename, string arguments)
    {
    Process process = new Process();
    ProcessStartInfo psi = new ProcessStartInfo(filename);
    psi.Arguments = arguments;
    psi.CreateNoWindow = true;
    psi.RedirectStandardOutput = true;
    psi.RedirectStandardError = true;
    psi.UseShellExecute = false;
    process.StartInfo = psi;

    StringBuilder output = new StringBuilder();
    process.OutputDataReceived += (sender, e) => { output.AppendLine(e.Data); };
    process.ErrorDataReceived += (sender, e) => { output.AppendLine(e.Data); };

    // run the process
    process.Start();

    // start reading output to events
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();

    // wait for process to exit
    process.WaitForExit();

    if (process.ExitCode != 0)
    throw new Exception("Command " + psi.FileName + " returned exit code " + process.ExitCode);

    return output.ToString();
    }
    60 changes: 60 additions & 0 deletions Program.exe.config
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    <configSections>
    <section name="Paths" type="System.Configuration.NameValueSectionHandler" />
    </configSections>
    <startup>
    <!-- Framwork Version -->
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
    <!-- Environment Variable Paths -->
    <Paths>
    <add key="Path1" value="%USERPROFILE%\Workspace\" />
    <add key="Path2" value="%LOCALAPPDATA%\Temp\" />
    </Paths>
    </configuration>

    <!-- Environment Variables
    %ALLUSERSPROFILE% C:\ProgramData
    %APPDATA% C:\Users\%USERNAME%\AppData\Roaming
    %COMMONPROGRAMFILES% C:\Program Files\Common Files
    %COMMONPROGRAMFILES(x86)% C:\Program Files (x86)\Common Files
    %COMSPEC% C:\Windows\System32\cmd.exe
    %HOMEDRIVE% C:
    %HOMEPATH% C:\Users\%USERNAME%
    %LOCALAPPDATA% C:\Users\%USERNAME%\AppData\Local
    %PROGRAMFILES% C:\Program Files
    %PROGRAMFILES(X86)% C:\Program Files (x86) (only in 64-bit version)
    %SystemDrive% C:
    %SystemRoot% C:\Windows
    %TEMP% and %TMP% C:\Users\%USERNAME%\AppData\Local\Temp
    %USERPROFILE% C:\Users\%USERNAME%
    %WINDIR% C:\Windows
    -->

    <!-- C# Code
    if (ConfigurationManager.GetSection("Directories") as NameValueCollection != null)
    {
    foreach (var directory in (ConfigurationManager.GetSection("Directories") as NameValueCollection).AllKeys)
    {
    string Value = (ConfigurationManager.GetSection("Directories") as NameValueCollection).GetValues(directory).FirstOrDefault();
    string DirectoriesValue = Environment.ExpandEnvironmentVariables(Value);
    if (directory == "Xpadder")
    {
    if (DirectoriesValue != "")
    {
    }
    }
    }
    }
    else
    {
    MessageBox.Show("Either the configuration File is missing or is corrupt.\n\nYou will need to recreate this file in order for the application to work correctly and process any settings.", "Configuration File Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
    Environment.Exit(0);
    }
    -->
    55 changes: 55 additions & 0 deletions ProgressBar.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    namespace pBarBW
    {
    public partial class Form1 : Form
    {
    ProgressBar progressBar1 = new ProgressBar();
    BackgroundWorker backgroundWorker1 = new BackgroundWorker();


    public Form1()
    {
    InitializeComponent();

    InitializeComponent();
    Shown += new EventHandler(Form1_Shown);

    // To report progress from the background worker we need to set this property
    backgroundWorker1.WorkerReportsProgress = true;
    // This event will be raised on the worker thread when the worker starts
    backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
    // This event will be raised when we call ReportProgress
    backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);


    }
    void Form1_Shown(object sender, EventArgs e)
    {
    // Start the background worker
    backgroundWorker1.RunWorkerAsync();
    }
    // On worker thread so do our thing!
    void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
    // Your background task goes here
    for (int i = 0; i <= 100; i++)
    {
    // Report progress to 'UI' thread
    backgroundWorker1.ReportProgress(i);
    // Simulate long task
    System.Threading.Thread.Sleep(100);
    }
    }
    // Back on the 'UI' thread so we can update the progress bar
    void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
    // The progress percentage is a property of e
    progressBar1.Value = e.ProgressPercentage;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
    this.Controls.Add(progressBar1);

    }
    }
    }
    3 changes: 3 additions & 0 deletions Quotes.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,3 @@
    string SYSTEM = "\"NT AUTHORITY\\SYSTEM\"";

    string TaskPath = "\"" + AssemblyDirectory + "\\NightMode.exe\"";
    1 change: 1 addition & 0 deletions REGEX.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    ^(?([^\r\n])\s)*\r?$\r?\n // Remove Empty Lines
    18 changes: 18 additions & 0 deletions Read From App.config.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    //program
    using System.Configuration;
    using System.Collections.Specialized;
    using System.Linq;

    var MouseX = ConfigurationManager.GetSection("MouseX") as NameValueCollection;

    if (MouseX != null)
    {
    foreach (var games in MouseX.AllKeys)
    {
    string gamesValue = MouseX.GetValues(games).FirstOrDefault();
    if (gamesValue.Contains(GameRunning))
    {
    //Do something with the string
    }
    }
    }
    42 changes: 42 additions & 0 deletions RedirectStandardOutput.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    private static void RunCommand(string filename, string args)
    {
    using (Process process = new Process())
    {
    ProcessStartInfo startInfo = new ProcessStartInfo
    {
    WindowStyle = ProcessWindowStyle.Hidden,
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    CreateNoWindow = true,
    UseShellExecute = false,
    StandardOutputEncoding = Encoding.GetEncoding(437),
    FileName = filename,
    Arguments = args
    };

    process.EnableRaisingEvents = true;
    process.EnableRaisingEvents = true;
    process.StartInfo = startInfo;

    process.Exited += new EventHandler(ProcExited);
    process.ErrorDataReceived += Proc_DataReceived;
    process.OutputDataReceived += Proc_DataReceived;

    process.Start();

    process.BeginErrorReadLine();
    process.BeginOutputReadLine();

    process.WaitForExit();
    }
    }

    private static void Proc_DataReceived(object sender, DataReceivedEventArgs e)
    {
    Logging.Info(e.Data, "Full Checkup");
    }

    private static void ProcExited(object sender, EventArgs e)
    {
    // Process has exited
    }
    77 changes: 77 additions & 0 deletions Refresh Notification Area.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,77 @@
    // NativeMethods Class
    using System;
    using System.Runtime.InteropServices;

    namespace RefreshNotificationArea
    {
    internal class NativeMethods
    {
    [StructLayout(LayoutKind.Sequential)]
    internal struct RECT
    {
    public int left;
    public int top;
    public int right;
    public int bottom;
    }
    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    internal static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    internal static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass,
    string lpszWindow);

    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    internal static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);
    }
    }


    // Main
    using System;

    namespace RefreshNotificationArea
    {
    class Program
    {
    static void Main(string[] args)
    {
    RefreshTrayArea();
    }

    public static void RefreshTrayArea()
    {
    IntPtr systemTrayContainerHandle = NativeMethods.FindWindow("Shell_TrayWnd", null);
    IntPtr systemTrayHandle = NativeMethods.FindWindowEx(systemTrayContainerHandle, IntPtr.Zero, "TrayNotifyWnd", null);
    IntPtr sysPagerHandle = NativeMethods.FindWindowEx(systemTrayHandle, IntPtr.Zero, "SysPager", null);
    IntPtr notificationAreaHandle = NativeMethods.FindWindowEx(sysPagerHandle, IntPtr.Zero, "ToolbarWindow32", "Notification Area");
    if (notificationAreaHandle == IntPtr.Zero)
    {
    notificationAreaHandle = NativeMethods.FindWindowEx(sysPagerHandle, IntPtr.Zero, "ToolbarWindow32",
    "User Promoted Notification Area");
    IntPtr notifyIconOverflowWindowHandle = NativeMethods.FindWindow("NotifyIconOverflowWindow", null);
    IntPtr overflowNotificationAreaHandle = NativeMethods.FindWindowEx(notifyIconOverflowWindowHandle, IntPtr.Zero,
    "ToolbarWindow32", "Overflow Notification Area");
    RefreshTrayArea(overflowNotificationAreaHandle);
    }
    RefreshTrayArea(notificationAreaHandle);
    }

    private static void RefreshTrayArea(IntPtr windowHandle)
    {
    const uint wmMousemove = 0x0200;
    NativeMethods.GetClientRect(windowHandle, out NativeMethods.RECT rect);
    for (var x = 0; x < rect.right; x += 5)
    {
    for (var y = 0; y < rect.bottom; y += 5)
    {
    NativeMethods.SendMessage(windowHandle, wmMousemove, 0, (y << 16) + x);
    }
    }
    }
    }
    }
    25 changes: 25 additions & 0 deletions Reminder.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    Thread Remind = new Thread(Reminder);
    Remind.IsBackground = true;
    Remind.Start();
    static void Reminder()
    {
    bool Timer = true;
    while(Timer)
    {
    TimeSpan T1A = TimeSpan.Parse("11:00");
    TimeSpan now = DateTime.Now.TimeOfDay;

    if (now > T1A)
    {
    using (System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"C:\Windows\Media\Alarm09.wav"))
    {
    player.Play();
    }
    Thread.Sleep(60000);
    }
    else
    {
    Thread.Sleep(2000);
    }
    }
    }
    2 changes: 2 additions & 0 deletions Replace Text.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,2 @@
    string text = "Some String";
    text = text.Replace("Some", "New");
    11 changes: 11 additions & 0 deletions Resources.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,11 @@
    Text = Resources.ResourceManager.GetString("ShadowEx");

    // or

    var message = Properties.Resources.ResourceManager.GetString("EnterMessage");
    var title = Properties.Resources.ResourceManager.GetString("EnterTitle");
    MessageBox.Show(message, title, MessageBoxButton.OK ,MessageBoxImage.Information);


    // Image
    Image = Resources.cmd.ToBitmap(),
    4 changes: 4 additions & 0 deletions Run Form In The Background.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,4 @@
    // Make form run in the background
    Visible = false;
    ShowInTaskbar = false;
    Hide();
    62 changes: 62 additions & 0 deletions Running as Admin.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,62 @@
    // Current Application
    static bool IsElevated
    {
    get
    {
    return WindowsIdentity.GetCurrent().Owner
    .IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid);
    }
    }

    // Another Application
    public class ProcessHelper
    {
    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool CloseHandle(IntPtr hObject);

    private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;
    private const int TOKEN_ASSIGN_PRIMARY = 0x1;
    private const int TOKEN_DUPLICATE = 0x2;
    private const int TOKEN_IMPERSONATE = 0x4;
    private const int TOKEN_QUERY = 0x8;
    private const int TOKEN_QUERY_SOURCE = 0x10;
    private const int TOKEN_ADJUST_GROUPS = 0x40;
    private const int TOKEN_ADJUST_PRIVILEGES = 0x20;
    private const int TOKEN_ADJUST_SESSIONID = 0x100;
    private const int TOKEN_ADJUST_DEFAULT = 0x80;
    private const int 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_SESSIONID | TOKEN_ADJUST_DEFAULT);

    public static bool IsProcessOwnerAdmin(string processName)
    {
    Process proc = Process.GetProcessesByName(processName)[0];

    IntPtr ph = IntPtr.Zero;

    OpenProcessToken(proc.Handle, TOKEN_ALL_ACCESS, out ph);

    WindowsIdentity iden = new WindowsIdentity(ph);

    bool result = false;

    foreach (IdentityReference role in iden.Groups)
    {
    if (role.IsValidTargetType(typeof(SecurityIdentifier)))
    {
    SecurityIdentifier sid = role as SecurityIdentifier;

    if (sid.IsWellKnown(WellKnownSidType.AccountAdministratorSid) || sid.IsWellKnown(WellKnownSidType.BuiltinAdministratorsSid))
    {
    result = true;
    break;
    }
    }
    }

    CloseHandle(ph);

    return result;
    }
    }
    73 changes: 73 additions & 0 deletions Scheduled Tasks.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,73 @@
    using System;
    using System.Diagnostics;
    using System.IO;

    namespace NightMode
    {
    class TasksSchedule
    {
    static bool taskexistance(string taskname)
    {
    ProcessStartInfo start = new ProcessStartInfo();
    start.FileName = "schtasks.exe";
    start.UseShellExecute = false;
    start.CreateNoWindow = true;
    start.WindowStyle = ProcessWindowStyle.Hidden;
    start.Arguments = "/query /TN " + taskname;
    start.RedirectStandardOutput = true;

    using (Process process = Process.Start(start))
    {
    using (StreamReader reader = process.StandardOutput)
    {
    string stdout = reader.ReadToEnd();
    if (stdout.Contains(taskname))
    {
    return true;
    }
    else
    {
    return false;
    }
    }
    }
    }
    }
    }

    // in your main
    // SCHTASKS /Create /RU "NT AUTHORITY\SYSTEM" /TN "Notepad" /TR "C:\windows\system32\notepad.exe"
    if (!TasksSchedule.taskexistance("NightMode"))
    {
    using (Process proc = new Process())
    {
    string SYSTEM = "\"NT AUTHORITY\\SYSTEM\"";
    string TaskPath = "\"" + AssemblyDirectory + "\\NightMode.exe\"";
    string TaskName = "\"NightMode\"";
    string arguments = "/Create /RU " + SYSTEM + " /TN " + TaskName + " / TR " + TaskPath;
    proc.StartInfo.Arguments = arguments;
    proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    proc.StartInfo.FileName = "schtasks.exe";
    proc.Start();
    proc.WaitForExit();
    }
    }

    // or

    var arguments = "/Run /Tn " + "NightMode";

    var p = new Process
    {
    StartInfo =
    {
    UseShellExecute = false,
    FileName = "SCHTASKS.exe",
    RedirectStandardError = true,
    RedirectStandardOutput = true,
    CreateNoWindow = true,
    WindowStyle = ProcessWindowStyle.Hidden,
    Arguments = arguments
    }
    };
    p.Start();
    37 changes: 37 additions & 0 deletions Service Debug.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    using System.ServiceProcess;
    using System.Threading;

    namespace SCTracerService
    {
    static class Program
    {
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
    #if DEBUG
    Service1 myService = new Service1();
    myService.OnDebug();
    Thread.Sleep(Timeout.Infinite);
    #else
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[]
    {
    new Service1()
    };
    ServiceBase.Run(ServicesToRun);
    #endif
    }
    }
    }




    // In Service1

    internal void OnDebug()
    {

    }
    22 changes: 22 additions & 0 deletions Service Running Check.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    using System.ServiceProcess;

    private string IsServiceRunning(string service)
    {
    ServiceController sc = new ServiceController(service);

    switch (sc.Status)
    {
    case ServiceControllerStatus.Running:
    return "Running";
    case ServiceControllerStatus.Stopped:
    return "Stopped";
    case ServiceControllerStatus.Paused:
    return "Paused";
    case ServiceControllerStatus.StopPending:
    return "Stopping";
    case ServiceControllerStatus.StartPending:
    return "Starting";
    default:
    return "Status Changing";
    }
    }
    22 changes: 22 additions & 0 deletions Set Windows Position.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    IntPtr hWnd = WindowHelper.FindWindow(null, "Sticky Pad");

    WindowHelper.SetWindowPos(hWnd, WindowHelper.HWND_TOPMOST, 0, 0, 0, 0, WindowHelper.SWP_NOMOVE | WindowHelper.SWP_NOSIZE | WindowHelper.SWP_SHOWWINDOW);

    WindowHelper.SetWindowPos(hWnd, WindowHelper.HWND_NO_TOPMOST, 0, 0, 0, 0, WindowHelper.SWP_NOMOVE | WindowHelper.SWP_NOSIZE | WindowHelper.SWP_SHOWWINDOW);



    public static class WindowHelper
    {
    [DllImport("user32.dll")]
    public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

    public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
    public static readonly IntPtr HWND_NO_TOPMOST = new IntPtr(-2);
    public const UInt32 SWP_NOSIZE = 0x0001;
    public const UInt32 SWP_NOMOVE = 0x0002;
    public const UInt32 SWP_SHOWWINDOW = 0x0040;

    [DllImport("user32.dll")]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    }
    1 change: 1 addition & 0 deletions SetApartmentState Error.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    Invoke((Action)(() => { }));
    18 changes: 18 additions & 0 deletions Shortcut Shell to Actual File.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    // Reference to "Microsoft Shell Control And Automation"

    public static string GetShortcutTargetFile(string shortcutFilename)
    {
    string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
    string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);

    Shell shell = new Shell();
    Folder folder = shell.NameSpace(pathOnly);
    FolderItem folderItem = folder.ParseName(filenameOnly);
    if (folderItem != null)
    {
    Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink;
    return link.Path;
    }

    return string.Empty;
    }
    219 changes: 219 additions & 0 deletions Single Instance.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,219 @@
    // Mutex

    private static Mutex mutex;

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
    var assembly = typeof(Program).Assembly;
    var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0];
    var id = attribute.Value;

    var mutex = new Mutex(true, id);

    if (mutex.WaitOne(TimeSpan.Zero, true))
    {
    try
    {
    startApp();
    }
    finally
    {
    mutex.ReleaseMutex();
    }
    }
    else
    {
    exitApp();
    }
    }

    // or

    using System;
    using System.Diagnostics;

    namespace APP_NAME
    {
    public class SingleInstance
    {
    internal static void Check()
    {
    foreach (Process proc in Process.GetProcessesByName("PROCESS_NAME"))
    {
    IntPtr hWnd = WindowHelper.FindWindow(null, "WINDOW_TITLE"); // Make sure the window title is unique or it will find the first one

    WindowHelper.GetWindowThreadProcessId(hWnd, out uint id);

    if (id != 0)
    {
    if (id != Process.GetCurrentProcess().Id)
    {
    WindowHelper.SetWindowPos(hWnd, WindowHelper.HWND_TOPMOST, 0, 0, 0, 0, WindowHelper.SWP_NOMOVE | WindowHelper.SWP_NOSIZE | WindowHelper.SWP_SHOWWINDOW);


    WindowHelper.SetWindowPos(hWnd, WindowHelper.HWND_NO_TOPMOST, 0, 0, 0, 0, WindowHelper.SWP_NOMOVE | WindowHelper.SWP_NOSIZE | WindowHelper.SWP_SHOWWINDOW);

    WindowHelper.SetForegroundWindow(hWnd);

    Environment.Exit(0);
    }
    }
    }
    }
    }
    }
    namespace APP_NAME
    {
    public static class WindowHelper
    {
    [DllImport("user32.dll")]
    public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

    public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
    public static readonly IntPtr HWND_NO_TOPMOST = new IntPtr(-2);
    public const UInt32 SWP_NOSIZE = 0x0001;
    public const UInt32 SWP_NOMOVE = 0x0002;
    public const UInt32 SWP_SHOWWINDOW = 0x0040;

    [DllImport("user32.dll")]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [DllImport("user32.dll", SetLastError = true)]
    public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);

    [DllImport("user32.dll", SetLastError = true)]
    public static extern bool SetForegroundWindow(IntPtr hWnd);

    }
    }

    // or

    // Initialize(); from main/form/window
    private void Initialize()
    {
    if (!CreateSingleInstance(
    Assembly.GetExecutingAssembly().GetName().Name,
    SingleInstanceCallback)) return;

    InitializeComponent();
    }

    static EventWaitHandle eventWaitHandle;
    private void SingleInstanceCallback(object sender, InstanceCallbackEventArgs args)
    {
    if (InstanceCallbackEventArgs.CommandLineArgs.Length > 1)
    {
    if (InstanceCallbackEventArgs.CommandLineArgs[1] == "--start")
    {
    DisplayChanged(null, null);
    }
    else if (InstanceCallbackEventArgs.CommandLineArgs[1] == "--shutdown")
    {
    // Do Cleanup here

    Environment.Exit(0);
    }
    }
    }
    private static bool CreateSingleInstance(string name, EventHandler<InstanceCallbackEventArgs> callback)
    {
    string eventName = string.Format("{0}-{1}", Environment.MachineName, name);

    InstanceProxy.IsFirstInstance = false;
    InstanceProxy.CommandLineArgs = Environment.GetCommandLineArgs();

    try
    {
    eventWaitHandle = EventWaitHandle.OpenExisting(eventName);
    }
    catch
    {
    InstanceProxy.IsFirstInstance = true;
    }

    if (InstanceProxy.IsFirstInstance)
    {
    eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName);

    ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, WaitOrTimerCallback, callback, Timeout.Infinite, false);
    eventWaitHandle.Close();

    RegisterRemoteType(name);
    }
    else
    {
    UpdateRemoteObject(name);

    if (eventWaitHandle != null) eventWaitHandle.Set();

    Environment.Exit(0);
    }
    return InstanceProxy.IsFirstInstance;
    }
    private static void UpdateRemoteObject(string uri)
    {
    var clientChannel = new IpcClientChannel();
    ChannelServices.RegisterChannel(clientChannel, true);

    var proxy =
    Activator.GetObject(typeof(InstanceProxy),
    string.Format("ipc://{0}{1}/{1}", Environment.MachineName, uri)) as InstanceProxy;

    if (proxy != null)
    proxy.SetCommandLineArgs(InstanceProxy.IsFirstInstance, InstanceProxy.CommandLineArgs);

    ChannelServices.UnregisterChannel(clientChannel);
    }
    private static void RegisterRemoteType(string uri)
    {
    var serverChannel = new IpcServerChannel(Environment.MachineName + uri);
    ChannelServices.RegisterChannel(serverChannel, true);

    RemotingConfiguration.RegisterWellKnownServiceType(
    typeof(InstanceProxy), uri, WellKnownObjectMode.Singleton);

    Process process = Process.GetCurrentProcess();
    process.Exited += delegate { ChannelServices.UnregisterChannel(serverChannel); };
    }
    private static void WaitOrTimerCallback(object state, bool timedOut)
    {
    var callback = state as EventHandler<InstanceCallbackEventArgs>;
    if (callback == null) return;

    callback(state,
    new InstanceCallbackEventArgs(InstanceProxy.IsFirstInstance,
    InstanceProxy.CommandLineArgs));
    }

    // Classes
    public class InstanceProxy : MarshalByRefObject
    {
    internal static bool IsFirstInstance;

    internal static string[] CommandLineArgs;

    public void SetCommandLineArgs(bool isFirstInstance, string[] commandLineArgs)
    {
    IsFirstInstance = isFirstInstance;
    CommandLineArgs = commandLineArgs;
    }
    }
    public class InstanceCallbackEventArgs : EventArgs
    {
    internal static bool IsFirstInstance;

    internal static string[] CommandLineArgs;

    internal InstanceCallbackEventArgs(bool isFirstInstance, string[] commandLineArgs)
    {
    IsFirstInstance = isFirstInstance;
    CommandLineArgs = commandLineArgs;
    }
    }


    24 changes: 24 additions & 0 deletions Start Process as Admin.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    try
    {
    Process proc = new Process();
    proc.StartInfo.Arguments = "\"" + args[0] + "\"";
    proc.StartInfo.FileName = @"C:\Program Files\Unlocker\Unlocker.exe";
    proc.StartInfo.Verb = "runas";
    proc.Start();
    proc.WaitForExit();
    SendRefresh = false;
    }
    catch (System.ComponentModel.Win32Exception ex) { MessageBox.Show(ex.Message, "The operation was cancelled."); }

    // or

    string args = "args";
    string program = "/C sc start" + " " + args;
    using (Process proc = new Process())
    {
    proc.StartInfo.FileName = "CMD.exe";
    proc.StartInfo.Arguments = program;
    proc.StartInfo.Verb = "runas"; // run as admin
    proc.Start();
    proc.WaitForExit();
    }
    1 change: 1 addition & 0 deletions String Before Comma.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    substring = str.Split(',')[0];
    18 changes: 18 additions & 0 deletions System Events.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    protected override void WndProc(ref Message m)
    {
    switch (m.Msg)
    {
    case UnsafeNativeMethods.CurrentStateUsb.Wmdevicechange:
    if (!UnsafeNativeMethods.CriticalHandle.ScreenDetection.AreApplicationFullScreen())
    {
    Thread.Sleep(500);
    Thread th = new Thread(DevCheck)
    {
    IsBackground = true
    };
    th.Start();
    }
    break;
    }
    base.WndProc(ref m);
    }
    17 changes: 17 additions & 0 deletions System UpTime.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    TimeSpan TimeCompare = TimeSpan.FromMinutes(5);
    if (SystemUpTime < TimeCompare)
    {
    Environment.Exit(0);
    }

    static TimeSpan SystemUpTime
    {
    get
    {
    using (var uptime = new PerformanceCounter("System", "System Up Time"))
    {
    uptime.NextValue();
    return TimeSpan.FromSeconds(uptime.NextValue());
    }
    }
    }
    3 changes: 3 additions & 0 deletions SystemIcons.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,3 @@
    using System.Drawing;

    this.Icon = SystemIcons.Warning;
    5 changes: 5 additions & 0 deletions Thread with Args.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    Thread thread = new Thread(() => Begin(args))
    {
    IsBackground = true
    };
    thread.Start();
    139 changes: 139 additions & 0 deletions Top Most MessageBox.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,139 @@
    Form form;
    using (form = new Form())
    {
    form.Opacity = 0.0;
    form.TopMost = true;
    form.Show();
    form.Activate();
    var dialogResult = System.Windows.Forms.MessageBox.Show(form, "Are you sure you want to put your PC into NightMode?", "NightMode", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    if (dialogResult == System.Windows.Forms.DialogResult.Yes)
    {

    }
    }

    // or



    Message("Installation completed successfully!", "Register" , MessageBoxButtons.OK, MessageBoxIcon.Information);

    static void Message(string message, string title, MessageBoxButtons buttons, MessageBoxIcon icon)
    {
    Form form;
    using (form = new Form())
    {
    form.TopMost = true;
    MessageBox.Show(form, message, title, buttons, icon);
    }
    }

    // or


    MessageBoxButtons buttons = MessageBoxButtons.YesNo;
    MessageBoxIcon icon = MessageBoxIcon.Error;
    string message = Resources.ResourceManager.GetString("MESSAGE");
    string caption = Resources.ResourceManager.GetString("TITLE");
    DialogResult result = null;
    Form form;
    using (form = new Form())
    {
    form.TopMost = true;
    MessageBox.Show(form, caption, message, buttons, icon);
    }
    if (result == DialogResult.Yes)
    {
    // do something with the result
    }

    // or

    //class
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows.Forms;

    namespace TopMostMessageBox
    {
    /// <summary>
    /// Displays MessageBox messages as a top most window
    /// </summary>
    static public class TopMostMessageBox
    {
    /// <summary>
    /// Displays a <see cref="MessageBox"/> but as a TopMost window.
    /// </summary>
    /// <param name="message">The text to appear in the message box.</param>
    /// <param name="title">The title of the message box.</param>
    /// <returns>The button pressed.</returns>
    /// <remarks>This will display with no title and only the OK button.</remarks>
    static public DialogResult Show(string message)
    {
    return Show(message, string.Empty, MessageBoxButtons.OK);
    }

    /// <summary>
    /// Displays a <see cref="MessageBox"/> but as a TopMost window.
    /// </summary>
    /// <param name="message">The text to appear in the message box.</param>
    /// <param name="title">The title of the message box.</param>
    /// <returns>The button pressed.</returns>
    /// <remarks>This will display with only the OK button.</remarks>
    static public DialogResult Show(string message, string title)
    {
    return Show(message, title, MessageBoxButtons.OK);
    }

    /// <summary>
    /// Displays a <see cref="MessageBox"/> but as a TopMost window.
    /// </summary>
    /// <param name="message">The text to appear in the message box.</param>
    /// <param name="title">The title of the message box.</param>
    /// <param name="buttons">The buttons to display in the message box.</param>
    /// <returns>The button pressed.</returns>
    static public DialogResult Show(string message, string title, MessageBoxButtons buttons)
    {
    // Create a host form that is a TopMost window which will be the parent of the MessageBox.
    Form topmostForm = new Form();
    // We do not want anyone to see this window so position it off the visible screen and make it as small as possible
    topmostForm.Size = new System.Drawing.Size(1, 1);
    topmostForm.StartPosition = FormStartPosition.Manual;
    System.Drawing.Rectangle rect = SystemInformation.VirtualScreen;
    topmostForm.Location = new System.Drawing.Point(rect.Bottom + 10, rect.Right + 10);
    topmostForm.Show();
    // Make this form the active form and make it TopMost
    topmostForm.Focus();
    topmostForm.BringToFront();
    topmostForm.TopMost = true;
    topmostForm.Activate();
    // Finally show the MessageBox with the form just created as its owner
    DialogResult result = MessageBox.Show(topmostForm, message, title, buttons);
    topmostForm.Dispose(); // clean it up all the way

    return result;
    }
    }
    }

    //program
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows.Forms;

    namespace TopMostMessageBox
    {
    class Program
    {
    static void Main(string[] args)
    {
    for (int i = 0; i < args.Length; i++)
    {
    MessageBox.Show(args[i]);
    }
    }
    }
    }

    35 changes: 35 additions & 0 deletions UDP Server & Client.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@
    //Server
    using System.Net;
    using System.Net.Sockets;

    string xName = "string to send";
    byte[] packetData = System.Text.ASCIIEncoding.ASCII.GetBytes(xName);
    string IP = "127.0.0.1";
    int port = 80;
    IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);
    Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    client.SendTo(packetData, ep);



    //Client
    using System.Net;
    using System.Net.Sockets;
    using System.Collections.Specialized;
    using System.Linq;

    private static Exception socketException = null;
    static void OpenSocket()
    {
    byte[] data = new Byte[256];
    IPEndPoint ServerEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 80);
    Socket WinSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    WinSocket.ReceiveTimeout = 0;
    WinSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 0);
    WinSocket.Bind(ServerEndPoint);
    IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
    EndPoint Remote = (EndPoint)(sender);

    int recv = WinSocket.ReceiveFrom(data, ref Remote);
    string DataRecieved = Encoding.ASCII.GetString(data, 0, recv);
    }
    40 changes: 40 additions & 0 deletions Validate.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    PassThroughNonNull(firstImage);

    static Image PassThroughNonNull(Image firstImage)
    {
    if (firstImage == null)
    throw new InvalidOperationException(firstImage.ToString());//Try to find an exception like ArgumentNullException if dealing with args
    return firstImage;
    }

    // EXAMPLE
    public static Bitmap MergeTwoImages(Image firstImage, Image secondImage)
    {
    int outputImageWidth = 460;

    int outputImageHeight = 215;

    outputImage = new Bitmap(outputImageWidth, outputImageHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

    using (Graphics graphics = Graphics.FromImage(outputImage))
    {
    graphics.DrawImage(PassThroughNonNull(firstImage), new Rectangle(new System.Drawing.Point(), PassThroughNonNull(firstImage).Size),
    new Rectangle(new System.Drawing.Point(), PassThroughNonNull(firstImage).Size), GraphicsUnit.Pixel);
    graphics.DrawImage(PassThroughNonNull2(secondImage), new Rectangle(new System.Drawing.Point(0, 0), PassThroughNonNull2(secondImage).Size),
    new Rectangle(new System.Drawing.Point(), PassThroughNonNull2(secondImage).Size), GraphicsUnit.Pixel);
    }

    return outputImage;
    }
    static Image PassThroughNonNull(Image firstImage)
    {
    if (firstImage == null)
    throw new InvalidOperationException(firstImage.ToString());
    return firstImage;
    }
    static Image PassThroughNonNull2(Image secondImage)
    {
    if (secondImage == null)
    throw new InvalidOperationException(secondImage.ToString());
    return secondImage;
    }
    152 changes: 152 additions & 0 deletions WPF Common References.xaml
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,152 @@
    <!-- Static Object -->
    ((MainWindow)Application.Current.MainWindow).image.Source
    = new BitmapImage(new Uri(...));

    <!-- START GET ARGS -->
    <!-- App.Xaml -->
    <Application x:Class="Tasks.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="MainWindow.xaml"
    Startup="App_Startup">
    <Application.Resources>

    </Application.Resources>
    </Application>


    <!-- App.Xaml.cs -->
    private void App_Startup(object sender, StartupEventArgs e)
    {
    for (int i = 0; i != e.Args.Length; ++i)
    {
    if (e.Args[i] == "/settings")
    {
    // Do something with settings
    }
    }
    }
    <!-- SINGLE INSTANCE: App.Xaml.cs -->
    private void App_Startup(object sender, StartupEventArgs e)
    {
    Assembly assembly = Assembly.GetExecutingAssembly();
    var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0];
    var id = attribute.Value;

    var mutex = new Mutex(true, id);

    if (mutex.WaitOne(TimeSpan.Zero, true))
    {
    try
    {
    startApp();
    }
    finally
    {
    mutex.ReleaseMutex();
    }
    }
    else
    {
    exitApp();
    }
    }
    <!-- END GET ARGS -->


    <!-- Resize Window (WindowStyle="None") -->
    <!-- MainWindow.xaml -->
    <WindowChrome.WindowChrome>
    <WindowChrome
    CaptionHeight="0"
    ResizeBorderThickness="5" />
    </WindowChrome.WindowChrome>



    <!-- App.xaml -->
    <ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="Resources/Styles.xaml"/>
    <ResourceDictionary Source="Resources/Icons.xaml"/>
    </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>

    <!-- MainWindow.xaml -->
    <Window.Background>
    <SolidColorBrush Opacity="0.9" Color="Black"/>
    </Window.Background>

    <!-- MainWindow -->
    <Window x:Class="Tasks.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Name="window" Title="Tasks" Height="400" Width="500" AllowsTransparency="True"
    WindowStyle="None" WindowStartupLocation="CenterScreen" BorderThickness="1" BorderBrush="#FF292929">
    <Grid>
    <StackPanel>
    <StackPanel Background="Black">
    <!-- CLOSE -->
    <Button x:Name="CloseButton" Style="{StaticResource ControlBoxButtons}" Height="28" Width="44" ToolTip="Close" ToolTipService.InitialShowDelay="1000" ToolTipService.ShowDuration="2500" ToolTipService.BetweenShowDelay="0" Cursor="Hand" HorizontalAlignment="Right" VerticalAlignment="Top" Click="CloseButton_Click">
    <Path Fill="{Binding ElementName=CloseButton, Path=Foreground}" Width="12" Data="{StaticResource CloseIcon}" Stretch="Uniform"/>
    </Button>
    </StackPanel>
    <StackPanel Height="370" Background="#212121">

    </StackPanel>
    </StackPanel>
    </Grid>
    </Window>

    <!-- START STYLES -->
    <!-- Resources/Styles.xaml -->
    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <!-- Button Styles -->
    <Style x:Key="ControlBoxButtons" TargetType="Button">
    <Setter Property="Focusable" Value="False"/>
    <Setter Property="Background" Value="Black"/>
    <Setter Property="Foreground" Value="#FFEAEAEA"/>
    <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
    <Setter Property="Template">
    <Setter.Value>
    <ControlTemplate TargetType="Button">
    <Grid>
    <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" Padding="0" BorderThickness="0">
    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
    </Border>
    <Grid x:Name="visibilityGrid" Visibility="Hidden"/>
    </Grid>
    <ControlTemplate.Triggers>
    <Trigger Property="IsEnabled" Value="False">
    <Setter TargetName="visibilityGrid" Property="Visibility" Value="Visible"/>
    </Trigger>
    <Trigger Property="IsMouseOver" Value="True">
    <Setter Property="Background" Value="#1B1B1B"/>
    </Trigger>
    <Trigger Property="IsPressed" Value="True">
    <Setter Property="Background" Value="#333333"/>
    </Trigger>
    </ControlTemplate.Triggers>
    </ControlTemplate>
    </Setter.Value>
    </Setter>
    </Style>
    </ResourceDictionary>

    <!-- Resources/Icons.xaml -->
    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <PathGeometry x:Key="CloseIcon">
    M6.998 0L0.005 6.997 105.263 112.254 0.005 217.512l6.993 7 105.258 -105.272 105.265 105.272 6.986 -7L119.249 112.254 224.507 6.997 217.521 0 112.256 105.258Z
    </PathGeometry>
    </ResourceDictionary>
    <!-- END STYLES -->



    <!-- Static Controls -->
    <ContentControl>
    14 changes: 14 additions & 0 deletions WPF Dynamically add button.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,14 @@
    StackPanel stackPanel1 = new StackPanel();
    System.Windows.Controls.Button button1 = new System.Windows.Controls.Button();
    button1.Width = 461;
    button1.Height = 217;

    button1.SetValue(Canvas.LeftProperty, 0.0);
    button1.SetValue(Canvas.TopProperty, 0.0);
    stackPanel1.Children.Add(button1);
    button1.Focus();
    button1.Content = stackPanel1;
    button1.Content = new Image
    {
    Source = new BitmapImage(new Uri(GameImage1))
    };
    8 changes: 8 additions & 0 deletions WPF Geometry Buttons.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <!-- Window buttons -->
    <Geometry x:Key="Restore">F1M0,2L0,10 8,10 8,2 0,2 0,3 7,3 7,9 1,9 1,3 M2,0L2,3 8,3 8,8 10,8 10,0 2,0 2,1 9,1 9,7 8,7 8,3 3,3 3,1z</Geometry>
    <Geometry x:Key="Maximize">F1M0,0L0,10 10,10 10,0 0,0 0,1 9,1 9,9 1,9 1,1z</Geometry>
    <Geometry x:Key="Close">F1M0.6,0L10,9.4 9.4,10 0,0.6 0.6,0 M9.4,0L10,0.6 0.6,10 0,9.4 9.4,0z</Geometry>
    <Geometry x:Key="Minimize">M0,0 L8,0 8,1 8,2 0,2 0,1 z</Geometry>
    </ResourceDictionary>
    7 changes: 7 additions & 0 deletions WPF Iterate Children.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    foreach (Control c in panel1.Children)
    {
    if (c.GetType() == typeof(Button))
    {
    c.Background = Brushes.Transparent;
    }
    }
    167 changes: 167 additions & 0 deletions Window Placement.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,167 @@
    // Standard WPF Window: To Show the Window
    // Minimize the Window First then Hide
    ThisWindow.WindowState = WindowState.Minimized;
    ThisWindow.Hide();

    // Show the Window again (A LOT OF WORK JUST TO SHOW A WINDOW)
    ThisWindow.Opacity = 0;
    ThisWindow.Topmost = true;
    ThisWindow.WindowState = WindowState.Normal;
    ThisWindow.Show();
    ThisWindow.WindowState = WindowState.Minimized;
    ThisWindow.BringIntoView();
    ThisWindow.Activate();
    ThisWindow.Topmost = false;
    ThisWindow.Opacity = 1;
    ThisWindow.WindowState = WindowState.Normal;




    // ALL OF THE BELOW USES PINVOKE
    static class RelativeWindows
    {
    public static void SetPlacement(this Window window, string placementXml)
    {
    WindowPlacement.SetPlacement(new WindowInteropHelper(window).Handle, placementXml);
    }

    public static string GetPlacement(this Window window)
    {
    return WindowPlacement.GetPlacement(new WindowInteropHelper(window).Handle);
    }
    }


    // NativeMethods

    // WINDOW_PLACEMENT

    [Serializable]
    [StructLayout(LayoutKind.Sequential)]
    public struct RECT
    {
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;

    public RECT(int left, int top, int right, int bottom)
    {
    Left = left;
    Top = top;
    Right = right;
    Bottom = bottom;
    }
    }

    [Serializable]
    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
    public int X;
    public int Y;

    public POINT(int x, int y)
    {
    X = x;
    Y = y;
    }
    }

    [Serializable]
    [StructLayout(LayoutKind.Sequential)]
    public struct WINDOWPLACEMENT
    {
    public int length;
    public int flags;
    public int showCmd;
    public POINT minPosition;
    public POINT maxPosition;
    public RECT normalPosition;
    }

    public static class WindowPlacement
    {
    private static Encoding encoding = new UTF8Encoding();
    private static XmlSerializer serializer = new XmlSerializer(typeof(WINDOWPLACEMENT));

    [DllImport("user32.dll")]
    private static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);

    [DllImport("user32.dll")]
    private static extern bool GetWindowPlacement(IntPtr hWnd, out WINDOWPLACEMENT lpwndpl);

    private const int SW_SHOWNORMAL = 1;
    private const int SW_SHOWMINIMIZED = 2;

    public static void SetPlacement(IntPtr windowHandle, string placementXml)
    {
    if (string.IsNullOrEmpty(placementXml))
    {
    return;
    }

    WINDOWPLACEMENT placement;
    byte[] xmlBytes = encoding.GetBytes(placementXml);

    try
    {
    using (MemoryStream memoryStream = new MemoryStream(xmlBytes))
    {
    placement = (WINDOWPLACEMENT)serializer.Deserialize(memoryStream);
    }

    placement.length = Marshal.SizeOf(typeof(WINDOWPLACEMENT));
    placement.flags = 0;
    placement.showCmd = (placement.showCmd == SW_SHOWMINIMIZED ? SW_SHOWNORMAL : placement.showCmd);
    SetWindowPlacement(windowHandle, ref placement);
    }
    catch (InvalidOperationException)
    {
    // Parsing placement XML failed. Fail silently.
    }
    }

    public static string GetPlacement(IntPtr windowHandle)
    {
    WINDOWPLACEMENT placement = new WINDOWPLACEMENT();
    GetWindowPlacement(windowHandle, out placement);

    using (MemoryStream memoryStream = new MemoryStream())
    {
    using (XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8))
    {
    serializer.Serialize(xmlTextWriter, placement);
    byte[] xmlBytes = memoryStream.ToArray();
    return encoding.GetString(xmlBytes);
    }
    }
    }








    // WINDOW_TO_FRONT

    [DllImport("user32.dll")]
    public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

    public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
    public static readonly IntPtr HWND_NO_TOPMOST = new IntPtr(-2);
    public const UInt32 SWP_NOSIZE = 0x0001;
    public const UInt32 SWP_NOMOVE = 0x0002;
    public const UInt32 SWP_SHOWWINDOW = 0x0040;

    [DllImport("user32.dll")]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    [DllImport("user32.dll", SetLastError = true)]
    public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);

    [DllImport("user32.dll", SetLastError = true)]
    public static extern bool SetForegroundWindow(IntPtr hWnd);