Friday, September 28, 2012

Password Generator

Today I want to present a "Password Generator" written in C#. Maybe the name is a bit wrong, it is about creating all possible passwords of a given length, so that they can for example be used for brute-force attacks.

The generator is capsuled in a class, when creating an instance of it a new thread is started, which generates the passwords and writes them to a queue. This can then be checked from the outside, so that the creating and asking of possible passwords can be done in parallel.
The creation of passwords happens in the function FillQueue(). Here an iteration counts from the given minimal length to the maximal length of a password and by recursion for every of these characters the function SetLetter() is called.
It goes over all possible characters (in the program can be set, that the characters A-Z, a-z and 0-9 are used), sets the current position to the current character and calls the function with the next position. If the last position is reached, the current password is written to the queue.
With the public function Dequeue() the lowest element of the queue is taken out and returned, that way the created passwords can be collected.

The code:
public class PasswordGenerator
    {
        Queue<string> Results; // queue with created passwords

        bool UpperAZ; // true if capital letters should be used
        bool LowerAZ; // true if lower case letters should be used
        bool Numbers; // true if numbers should be used

        int Min; // min. length of the password
        int Max; // max. length of the password

        const int MaxQueueSize = 30000000; // maximal number of passwords, which can be in the queue simultaneously (protection of memory overflow)

        public PasswordGenerator(bool upperAZ, bool lowerAZ, bool numbers, int min, int max)
        {
            UpperAZ = upperAZ;
            LowerAZ = lowerAZ;
            Numbers = numbers;

            Min = min;
            Max = max;
            Results = new Queue<string>();

            // create new thread for password generation
            Thread Creator = new Thread(new ThreadStart(FillQueue));
            Creator.Start();
        }

        private void FillQueue()
        {
            // fill queue
            for (int i = Min; i <= Max; i++)
            {
                SetLetter(i, 0, "");
            }
        }

        private void SetLetter(int length, int pos, string temp)
        {
            // fill current position with all possible characters
            if (UpperAZ)
            {
                for (int i = 65; i <= 90; i++)
                {
                    NextStep(length, pos, temp + (char)i);
                }
            }
            if (LowerAZ)
            {
                for (int i = 97; i <= 122; i++)
                {
                    NextStep(length, pos, temp + (char)i);
                }
            }
            if (Numbers)
            {
                for (int i = 0; i <= 9; i++)
                {
                    NextStep(length, pos, temp + i.ToString());
                }
            }
        }

        private void NextStep(int length, int pos, string temp)
        {
           // function to finalize a step

           // if the queue is "full", the step is paused
           while (Results.Count > MaxQueueSize)
               Thread.Sleep(500);

            // if not yet the last position is reached, call function with next position
            if (pos < length - 1)
                SetLetter(length, pos + 1, temp);
            else
                // otherwise add complete password to the queue
                Results.Enqueue(temp);
        }

        public string Dequeue()
        {
            // returns the lowest element of the queue
            if (Results.Count > 0)
                return Results.Dequeue();
            else
                return "";
        }
    }

The initialization of the generator then can be done e.g. via
PasswordGenerator Generator = new PasswordGenerator(true, true, true, 1, 4);
The asking for passwords via
Generator.Dequeue();

Tuesday, September 25, 2012

Check Password of a Word Document Automatically

After I explained the basics about including Microsoft Word in the previous post, I today want to put special attention to the opening of password protected documents.
With the following code it can be checked, whether a password is the right one to open a document. By iteration then for example can be automatically searched for a password:

            Object oMissing = System.Reflection.Missing.Value;

            Word.Application WordApp = new Word.Application();

            try
            {
                Word.Document ExistingDocument = WordApp.Documents.Open("Filename", oMissing, false, oMissing, "Password");
                MessageBox.Show("Correct Password");
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                MessageBox.Show("Wrong Password");
            }

Friday, September 21, 2012

Word Tutorial

In this post I want to show, how to connect C# and Microsoft Office Word. I will show, how to create new Word documents using C#, insert texts, change settings, open documents, save and display them.
First we have to add the corresponding component to our project, which can be done via Project - Add Reference - COM - Microsoft Word xx Object Library. xx in that means the current version number.
Then we use the code using Word = Microsoft.Office.Interop.Word to be able to use the Word object under the name Word.


Create Word Instance and Show It:
Word.Application WordApp = new Word.Application();
WordApp.Visible = true;
With that a new instance of the Word object is created. With enabling the visibility, this is shown. Since no documents are loaded yet, simply the grey Word window is shown.

Create New Word Document:
The propety Documents of the instance contains opened documents, we can add documents to this enumeration e.g. by opening or creating new ones. To create a new document, the following command is needed:
Word.Document NewDocument = WordApp.Documents.Add();

Close Document:
For this the function Close() is responsible, which is called from the corresponding document, so with above example:
NewDocument.Close();

Open Existing Word Document:
Object oMissing = System.Reflection.Missing.Value;
Word.Document ExistingDocument = WordApp.Documents.Open("Filename", oMissing, true, oMissing, "Password");
All arguments except the first one are optional. The 3. says, whether the document is to be opened read-only (true if yes). The 5. is the optional password.
The argument oMissing with the value System.Reflection.Missing.Value is very practical, it always returns the default value of the current argument and therefore can always be used as a placeholder for unused arguments.

Insert Text:
WordApp.Selection.TypeText("Hallo Welt");
This code types the given text in the currently top most opened document in the Documents enumeration.

Set Formattings:
Also with the Selection property formattings can be taken. If these are done before a TypeText command, they are applied to the written text. All known formattings are available, as for example:
WordApp.Selection.Font.Size = 20;

Save Document:
A document can either be saved with the parameterless function Save() or SaveAs2(). The last version expects a save path.

Quit Word Instance:
WordApp.Quit();

Wednesday, September 19, 2012

Create System Restore Point

In today's post I want to show, how to create a system restore point using C#.
Therefor we use management classes, which connects with the Windows Management Instrumentation (WMI) and over this way reads information about the computer.
To run the project, via Project - Add Reference System.Management has to be included, furthermore this via using. The application also needs to run with administratrative rights.
Central point is an instance of the class ManagementClass.
Its constructor expects 3 parameters:
First a scope, which is here set to the local computer, then a path, which defines the operation to be executed (here: create a restore point) and lastly a class with options, for that we hand over the default options of a WMI call.
From the created instance the function GetMethodParameters() with the parameter "CreateRestorePoint" is called. This tells the application, to load the parameters of the WMI function "CreateRestorePo", so that these can be filled then. CreateRestorePoint expects 3 parameters:
  • Description: Description of the restore point
  • RestorePointType: Type of the restore point. Detailed information about the possible options can for example be found on this site. Here we hand over 0, which means, that an application was installed. A 10 would for example mean, that a driver was installed. 
  • EventType: Type of the event. We here hand over 100, which indicates, that a change has begun in the system. 101 would mean, that the change was done.
Finally we execute the action caling InvokeMethod and thus create a system restore point.
The code:

                // select local computer
                ManagementScope ManScope = new ManagementScope(@"\\localhost\root\default");
                // create system restore point
                ManagementPath ManPath = new ManagementPath("SystemRestore");
                // select default options
                ObjectGetOptions ManOptions = new ObjectGetOptions();
                // create management class with previous options
                ManagementClass ManClass = new ManagementClass(ManScope, ManPath, ManOptions);
                // load function parameters
                ManagementBaseObject ManBaseObject = ManClass.GetMethodParameters("CreateRestorePoint");
                // description
                ManBaseObject["Description"] = "Mein C# Wiederherstellungspunkt";
                // type of the restore point
                ManBaseObject["RestorePointType"] = 0;
                // ype of the event
                ManBaseObject["EventType"] = 100;

                ManagementBaseObject OutParam = ManClass.InvokeMethod("CreateRestorePoint", ManBaseObject, null);

Wednesday, September 12, 2012

Check If Current User Has Specific Role (e.g. Administrator)

An easy solution of checking whether the current user has specific roles (as administrator or guest), is the following (the example checks, whether the user is guest):

WindowsIdentity CurrentIdentity = WindowsIdentity.GetCurrent();
WindowsPrincipal CurrentPrincipal = new WindowsPrincipal(CurrentIdentity);
bool UserIsAdmin = CurrentPrincipal.IsInRole(WindowsBuiltInRole.Guest);

From Windows Vista on though we get a problem, if the to be tested role is administrator. Although the user running the program might be administrator, the application is at first hand run without administrative rights, so that wrongly false is returned. Only when explicitely running the application as administrator true is returned, of course also then, if the user is no administrator.

I did not find an (easy) solution solving this problem, maybe some good advices come from you?

Sunday, September 9, 2012

Calculate MD5 Hash of a File

In the previous post I explained basics about hashing and hashing of strings, I will start from there on. For that reason I just publish the code which calculates the hash sum of a complete file:

MD5 Md5Hash = MD5.Create();
System.IO.FileStream HashStream = new System.IO.FileStream(@"C:\Users\User\Documents\c#.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] Data = Md5Hash.ComputeHash(HashStream);
string Hash =  System.BitConverter.ToString(Data);

Thursday, September 6, 2012

Calculate MD5 Hash of a String

In today's post I want to present, how to calculate the MD5 hash of a string using C#.
First a little basics about hashing in general:
A hash function is a function, which creates from a input of arbitrary length an output of fixed length. The function should one the one hand be not or hardly invertible, meaning given the output, calculating the corresponding input needs to be hard.
On the other hand the function should create only a few collisions, meaning, different inputs should create different outputs, furthermore little changes to the input should create big changes in the output.

Why all that?
One example is the storage of passwords on a webserver. The passwords are not saved in plain text but hashed. So on the one hand the administrator cannot see the passwords of his clients, since he cannot inverse the hash value, and on the other hand of course intruders cannot do so also.
Another example is the hash sum calculation of files, for example to verify the correct transfer. Comparing the 2 files in total would need too many ressources, so you compare the hash sums. Are these equivalent, the files are identical with a high probablity since there are little hash collisions, if already a small part of the file is different, the hash value is probably totally different.

Now to the code. With using System.Security.Cryptography the following code calculates the hash value of a string:

MD5 Md5Hash = MD5.Create();
byte[] Data = Md5Hash.ComputeHash(Encoding.Default.GetBytes("Zu hashende Zeichenkette"));
string Hash =  System.BitConverter.ToString(Data);

The first line creates a MD5 object. In the second line the string is hashed with MD5 and the hash is returned as a byte array. The function ToString() in the third line of the BitConverter then converts this array to a hexadecimal string, which is mostly used to represent hash values.

Monday, September 3, 2012

Start Program Automatically on Windows Startup

In this post I want to show, how to add a C# program to the autostart of Windows.
For this there are 2 possibilites: One the one hand, we can add a shortcut to the program in the startup folder, on the other hand we can create an entry in the registry.


1. Method: Create Shortcut
How to create a shortcut in general, I described in that post. We now have to set our program as link target and as path the startup folder of Windows, which is located under Windows 7 in C:\Users\User\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup. The path to our own application we get by Application.ExecutablePath.ToString() - so the following code copies the program to the startup folder (as icon we can set an icon):
CreateShortcut(@"C:\Users\User\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" + "\\CAutoStart.url",  Application.ExecutablePath.ToString(), "C:\\MeinIcon.ico");


2. Method: Create Registry Entry
The analogon to above path is located in the registry under HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run. How to use the registry in general with C#, is described in this tutorial. Here I just show the complete code, which creates the needed entry so that the application starts automatically when Windows starts:
RegistryKey AutostartKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true);
AutostartKey.SetValue("CAutoStart", Application.ExecutablePath.ToString());
AutostartKey.Close();

Wednesday, August 29, 2012

Source Code of the League of Legends Timer

In this post I publish the source code for the previous post:

Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Speech.Synthesis;
using System.Net;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        [DllImport("User32.dll")]
        static extern long SetForegroundWindow(IntPtr hwnd);

        [DllImport("user32.dll")]
        private static extern bool IsIconic(IntPtr hWnd);

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

        private const int SW_RESTORE = 9;

        // Verweis auf Hook Prozedur speichern, damit Garbage Collector diese nicht löscht
        KeyHook.HookProc KeyboardHookProcedure = new KeyHook.HookProc(KeyHook.KeyboardHookProc);

        LoLTimer MyTimer; // Timerinstanz
        long LastChange = 0; // Zeit der letzten Änderung des Chat Modes
        bool ChattingEnabled = false; // gibt ob ob Chatten (Ausgabe der Respawn Zeiten) aktiviert ist
        long LastActivation = 0; // Zeit der letzten Aktivierung eines Timers
        long LastCallout = 0; // Zeit der letzten Ausgabe aller Zeiten
        long StartingTime = 0; // Startzeit des Spiels
        int Channel;

        public Form1()
        {
            InitializeComponent();


        }

        private void Form1_Load(object sender, EventArgs e)
        {
            MyTimer = new LoLTimer();

            SwitchChannel(); // Kanal festlegen

            DialogResult Delete = MessageBox.Show("Alte Synchronisation löschen?", "LoLTimer", MessageBoxButtons.YesNo);
            if (Delete == System.Windows.Forms.DialogResult.Yes)
                DeleteTime();

            // Keyhook initialisieren
            KeyHook MyHook = new KeyHook(this, KeyboardHookProcedure);
            MyHook.Hook(KeyHook.KeyboardHookProc);

            CheckSync();
        }

        public void CheckSync()
        {
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

            try
            {
                // versuchen, die Synchronisation auszulesen und zu benutzen
                WebClient Webclient1 = new WebClient();
                Webclient1.DownloadFile("http://servername.de" + "/" + "sync" + Channel, Application.StartupPath + "\\sync" + Channel);
                FileStream fs = new FileStream(Application.StartupPath + "\\sync" + Channel, FileMode.Open);
                byte[] TimeByte = new byte[100];
                fs.Read(TimeByte, 0, 100);
                fs.Close();
                string Time = enc.GetString(TimeByte);
                int TimeInt = Convert.ToInt32(Time.Substring(0, Time.IndexOf('\0')));
            }
            catch (Exception)
            {
                // falls noch keine Synchronisation vorhanden, erstellen
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://servername.de" + "/" + "sync" + Channel);
                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.Credentials = new NetworkCredential("benutzername", "passwort");
                WebResponse Response = request.GetResponse();
                Stream RequestStream = request.GetRequestStream();
                string Time = GetGlobalTime().ToString(); 
                byte[] ByteTime = enc.GetBytes(Time);
                RequestStream.Write(ByteTime, 0, ByteTime.Length);
                RequestStream.Close();
                request.Abort();
                ResetTimes();
            }
        }

        public void SwitchChannel()
        {
            string Response = "";
            while (!CheckString(Response))
                Response = Microsoft.VisualBasic.Interaction.InputBox("Kanal eingeben", "LoLTimer", "1", 0, 0);

            Channel = Convert.ToInt32(Response);
        }

        private bool CheckString(string s)
        {
            if (s.Length == 0)
                return false;
            foreach (char c in s)
            {
                if (!Char.IsDigit(c))
                    return false;
            }
            return true;
        }

        public void StartGame()
        {
            // Startzeit setzen
            StartingTime = DateTime.Now.Ticks;
        }

        public void ChangeChat()
        {
            // aktiviert bzw. deaktiviert die Chat Funktion
            // die Zeit der letzten Änderung des Modus wird gespeichert,
            // damit Gedrückthalten der Taste nicht als Mehrfachänderung gewertet wird
            long now = (int)(DateTime.Now.Ticks / (10000 * 100));
            if (LastChange == 0 || now - LastChange > 3)
            {
                LastChange = now;
                ChattingEnabled = !ChattingEnabled;
                if (ChattingEnabled)
                    pictureBox2.BackColor = Color.Lime;
                else
                    pictureBox2.BackColor = Color.Red;
            }
        }

        public static int GetGlobalTime()
        {
            // Globale Zeit auslesen und zurückgeben
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.uhrzeit.org/atomuhr.php");

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader input = new StreamReader(response.GetResponseStream());
            string Content = input.ReadToEnd();
            string Match = "<div id=\"anzeige_zeit\">";
            int Start = Content.LastIndexOf(Match);
            Content = Content.Substring(Start + Match.Length, 20);
            int End = Content.LastIndexOf("</div>");
            string Time = Content.Substring(0, End);
            string[] Parts = Time.Split(':');
            int Seconds = Convert.ToInt32(Parts[0]) * 60 * 60 + Convert.ToInt32(Parts[1]) * 60 + Convert.ToInt32(Parts[2]);
            return Seconds;
        }

        public void ShowFront()
        {
            // bringt das Fenster nach vorne
            if (IsIconic(this.Handle))
                ShowWindowAsync(this.Handle, SW_RESTORE);
            SetForegroundWindow(this.Handle);
        }

        public void DeleteTime()
        {
            // versucht, die alte Synchronisationsdatei zu löschen
            // nur möglich, wenn älter als 2 Stunden
            try
            {
                WebClient Webclient1 = new WebClient();
                Webclient1.DownloadFile("http://servername.de" + "/" + "sync" + Channel, Application.StartupPath + "\\sync" + Channel);
                StreamReader sr = new StreamReader(Application.StartupPath + "\\sync" + Channel);
                int SyncTime = Convert.ToInt32(sr.ReadLine());
                if ((GetGlobalTime() - SyncTime) / (3600) < 2)
                {
                    MessageBox.Show("Kanal noch in Verwendung, kann nicht gelöscht werden. Anderen benutzen.");
                    return;
                }
                   
                sr.Close();
            }
            catch (Exception)
            {
            }

            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://servername.de" + "/" + "sync" + Channel);
                request.Method = WebRequestMethods.Ftp.DeleteFile;

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                response.Close();
            }
            catch (Exception)
            {
            }
        }

        public void ResetTimes()
        {
            // resettet die Konfigurationsdatei auf dem Server
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://servername.de" + "/" + "times" + Channel);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential("benutzername", "passwort");

            WebResponse Response = request.GetResponse();

            Stream RequestStream = request.GetRequestStream();

            BinaryFormatter bFormatter = new BinaryFormatter();

            LoLTimer Empty = new LoLTimer();

            bFormatter.Serialize(RequestStream, Empty);

            RequestStream.Close();
            request.Abort();

        }

        public void Activate(int nr)
        {
            // die Zeit der letzten Aktivierung wird gespeichert,
            // damit Gedrückthalten der Taste nicht als Mehrfachaktivierung gewertet wird
            long now = (int)(DateTime.Now.Ticks / (10000 * 100));
            if (LastActivation == 0 || now - LastActivation > 9)
            {
                LastActivation = now;

                string Objective = "";
                int Respawn = 0;

                // entsprechenden Timer starten und Respawn Zeit berechnen

                MyTimer.SetTime(nr - 1, LoLTimer.GetStatTime(nr - 1));


                Objective = LoLTimer.GetStatObjective(nr - 1);
                Respawn = LoLTimer.GetStatTime(nr - 1);

                // entsprechendes Timer Steuerelement aktivieren
                switch (nr)
                {
                    case 1:
                        timer1.Enabled = true;
                        break;
                    case 2:
                        timer2.Enabled = true;
                        break;
                    case 3:
                        timer3.Enabled = true;
                        break;
                    case 4:
                        timer4.Enabled = true;
                        break;
                    case 5:
                        timer5.Enabled = true;
                        break;
                    case 6:
                        timer6.Enabled = true;
                        break;
                    default:
                        break;
                }

                if (ChattingEnabled)
                {
                    // wenn Chat Funktion aktiviert, Respawn Zeit berechnen und im Chat eingeben
                    int Diff = (int)((DateTime.Now.Ticks - StartingTime) / (10000 * 1000)) + Respawn;
                    int Mins = (int)(Diff / 60);
                    int Secs = Diff - Mins * 60;
                    string RespawnTime = Mins + ":";
                    if (Secs < 10)
                        RespawnTime += "0" + Secs;
                    else
                        RespawnTime += Secs;
                    SendKeys.SendWait("{ENTER}");
                    Thread.Sleep(300);
                    SendKeys.SendWait(Objective + ": " + RespawnTime);
                    Thread.Sleep(300);
                    SendKeys.SendWait("{ENTER}");
                }
            }
        }

        private void UpdateTimes()
        {
            bool Changed = true;

            try
            {
                try
                {
                    // versucht, die Zeitdatei vom Server herunterzuladen und die darin enthaltenen Zeiten mit den lokalen Zeiten zu mergen
                    WebClient Webclient1 = new WebClient();
                    Webclient1.DownloadFile("http://servername.de/times" + Channel, Application.StartupPath + @"\\times");

                    BinaryFormatter bf = new BinaryFormatter();
                    FileStream fs = new FileStream(Application.StartupPath + @"\\times", FileMode.Open);
                    LoLTimer OtherTimer = (LoLTimer)bf.Deserialize(fs);
                    fs.Close();
                    Changed = MyTimer.Merge(OtherTimer);
                }
                catch (Exception ex)
                {

                }
               
                // wurde lokal etwas geändert, neue Zeiten hochladen
                if (Changed)
                {
                    FtpWebRequest Request = (FtpWebRequest)WebRequest.Create("ftp://servername.de" + "/" + "times" + Channel);
                    Request.Method = WebRequestMethods.Ftp.UploadFile;
                    Request.Credentials = new NetworkCredential("benutzername", "passwort");
                    try
                    {
                        WebResponse Response = Request.GetResponse();
                    }
                    catch (Exception ex)
                    {
                        pictureBox1.BackColor = Color.Red;
                    }
                    Stream RequestStream = Request.GetRequestStream();

                    try
                    {
                        BinaryFormatter bFormatter = new BinaryFormatter();
                        bFormatter.Serialize(RequestStream, MyTimer);
                    }
                    catch (Exception)
                    {
                        pictureBox1.BackColor = Color.Red;
                    }
                    RequestStream.Close();
                    Request.Abort();
                }

                for (int i = 0; i <= 5; i++)
                {
                    if (MyTimer.GetTime(i) > 0 && MyTimer.GetTime(i) < LoLTimer.GetStatTime(i))
                    {
                        MethodInvoker TimerUpdate = delegate
         {

             switch (i)
             {
                 case 0:
                     timer1.Enabled = true;
                     break;
                 case 1:
                     timer2.Enabled = true;
                     break;
                 case 2:
                     timer3.Enabled = true;
                     break;
                 case 3:
                     timer4.Enabled = true;
                     break;
                 case 4:
                     timer5.Enabled = true;
                     break;
                 case 5:
                     timer6.Enabled = true;
                     break;
             }
         };
                        Invoke(TimerUpdate);
                    }
                }
            }
            catch (Exception ex)
            {
                pictureBox1.BackColor = Color.Red;
            }
        }

        public void CallAlltimes()
        {
            long now = (int)(DateTime.Now.Ticks / (10000 * 1000));
            if (LastCallout == 0 || now - LastCallout > 1)
            {

                LastCallout = now;
                SpeechSynthesizer Speaker = new SpeechSynthesizer();
                for (int i = 0; i <= 5; i++)
                {
                    string Objective = LoLTimer.GetStatObjective(i);
                    int Min;
                    int Sec;

                    if (MyTimer.GetTime(i) != -1)
                    {
                        Min = MyTimer.GetTime(i) / 60;
                        Sec = MyTimer.GetTime(i) % 60;
                        if (Min > 0)
                            Speaker.SpeakAsync(Objective + " in " + Min.ToString() + " minutes and " + Sec.ToString() + "seconds");
                        else
                            Speaker.SpeakAsync(Objective + " in " + Sec.ToString() + "seconds");
                    }


                }
            }
        }

        private void CallTimes(int nr, int time)
        {
            SpeechSynthesizer Speaker = new SpeechSynthesizer();
            string Objective = "";
            switch (nr)
            {
                case 0:
                    Objective = "Baron";
                    break;
                case 1:
                    Objective = "Dragon";
                    break;
                case 2:
                    Objective = "Blue";
                    break;
                case 3:
                    Objective = "Red";
                    break;
                case 4:
                    Objective = "Enemy Blue";
                    break;
                case 5:
                    Objective = "Enemy Red";
                    break;
                default:
                    break;
            }

            Speaker.SpeakAsync(Objective + " in " + time.ToString());
        }

        

        private void timer1_Tick(object sender, EventArgs e)
        {

            if (MyTimer.GetTime(0) <= 0)
                timer1.Enabled = false;

            MyTimer.SetTime(0, MyTimer.GetTime(0) - 1);

            label9.Text = MyTimer.GetTime(0).ToString();

            if (MyTimer.GetTime(0) == 60)
                CallTimes(0, 60);
            if (MyTimer.GetTime(0) == 30)
                CallTimes(0, 30);
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            if (MyTimer.GetTime(1) <= 0)
                timer2.Enabled = false;

            MyTimer.SetTime(1, MyTimer.GetTime(1) - 1);

            label10.Text = MyTimer.GetTime(1).ToString();

            if (MyTimer.GetTime(1) == 60)
                CallTimes(1, 60);
            if (MyTimer.GetTime(1) == 30)
                CallTimes(1, 30);
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            if (MyTimer.GetTime(2) <= 0)
                timer3.Enabled = false;

            MyTimer.SetTime(2, MyTimer.GetTime(2) - 1);

            label11.Text = MyTimer.GetTime(2).ToString();

            if (MyTimer.GetTime(2) == 60)
                CallTimes(2, 60);
            if (MyTimer.GetTime(2) == 30)
                CallTimes(2, 30);
        }

        private void timer4_Tick(object sender, EventArgs e)
        {
            if (MyTimer.GetTime(3) <= 0)
                timer4.Enabled = false;

            MyTimer.SetTime(3, MyTimer.GetTime(3) - 1);

            label12.Text = MyTimer.GetTime(3).ToString();

            if (MyTimer.GetTime(3) == 60)
                CallTimes(3, 60);
            if (MyTimer.GetTime(3) == 30)
                CallTimes(3, 30);
        }

        private void timer5_Tick(object sender, EventArgs e)
        {
            if (MyTimer.GetTime(4) <= 0)
                timer5.Enabled = false;

            MyTimer.SetTime(4, MyTimer.GetTime(4) - 1);

            label13.Text = MyTimer.GetTime(4).ToString();

            if (MyTimer.GetTime(4) == 60)
                CallTimes(4, 60);
            if (MyTimer.GetTime(4) == 30)
                CallTimes(4, 30);
        }

        private void timer6_Tick(object sender, EventArgs e)
        {
            if (MyTimer.GetTime(5) <= 0)
                timer6.Enabled = false;

            MyTimer.SetTime(5, MyTimer.GetTime(5) - 1);

            label14.Text = MyTimer.GetTime(5).ToString();

            if (MyTimer.GetTime(5) == 60)
                CallTimes(5, 60);
            if (MyTimer.GetTime(5) == 30)
                CallTimes(5, 30);
        }

        private void timer7_Tick(object sender, EventArgs e)
        {
            Thread Update = new Thread(UpdateTimes);
            Update.Start();
        }
    }

    [Serializable()]
    public class LoLTimer : ISerializable
    {
        int[] times;

        private static int[] StatTimes;
        private static string[] StatObjectives;

        long timestamp;

        static LoLTimer()
        {
            StatTimes = new int[6];
            StatTimes[0] = 420;
            StatTimes[1] = 360;
            StatTimes[2] = 300;
            StatTimes[3] = 300;
            StatTimes[4] = 300;
            StatTimes[5] = 300;

            StatObjectives = new string[6];

            StatObjectives[0] = "Baron";
            StatObjectives[1] = "Drake";
            StatObjectives[2] = "Blue";
            StatObjectives[3] = "Red";
            StatObjectives[4] = "Enemy Blue";
            StatObjectives[5] = "Enemy Red";
        }

        public static int GetStatTime(int id) 
        {
            return StatTimes[id];
        }

        public static string GetStatObjective(int id)
        {
            return StatObjectives[id];
        }

        public LoLTimer()
        {
            times = new int[6];
            for (int i = 0; i <= 5; i++)
            {
                times[i] = -1;
            }
        }

        public LoLTimer(SerializationInfo info, StreamingContext ctxt)
        {
            this.times = (int[])info.GetValue("times", typeof(int[]));
            this.timestamp = (long)info.GetValue("timestamp", typeof(long));
        }

        public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
        {
            info.AddValue("times", times);
            info.AddValue("timestamp", Form1.GetGlobalTime());
        }

        public long GetStamp()
        {
            return timestamp;
        }

        public void SetTime(int id, int value)
        {
            times[id] = value;
        }

        public int GetTime(int id)
        {
            return times[id];
        }

        public bool Merge(LoLTimer other)
        {
            bool Changed = false;
            for (int i = 0; i <= 5; i++)
            {
                int x = other.GetTime(i);
                if (x == -1 && times[i] == -1)
                    continue;
                other.SetTime(i, (int)(other.GetTime(i) - (Form1.GetGlobalTime() - other.GetStamp())));

                if (other.GetTime(i) > times[i])
                    times[i] = other.GetTime(i);
                else if (other.GetTime(i) + 5 < times[i])
                    Changed = true;
            }
            return Changed;
        }
    }

    public class KeyHook
    {
        public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);

        //Declare hook handle as int.
        static int hHook = 0;

        // public static List<Keys> KeyCodes = new List<Keys>();

        //Declare keyboard hook constant.
        //For other hook types, you can obtain these values from Winuser.h in Microsoft SDK.
        const int WH_KEYBOARD_LL = 13;

        

        [StructLayout(LayoutKind.Sequential)]
        private class keyboardHookStruct
        {
            public int vkCode;
            public int scanCode;
            public int flags;
            public int time;
            public int dwExtraInfo;
        }

        //Import for SetWindowsHookEx function.
        //Use this function to install thread-specific hook.
        [DllImport("user32.dll", CharSet = CharSet.Auto,
         CallingConvention = CallingConvention.StdCall)]
        private static extern int SetWindowsHookEx(int idHook, HookProc lpfn,
        IntPtr hInstance, int threadId);

        //Import for UnhookWindowsHookEx.
        //Call this function to uninstall the hook.
        [DllImport("user32.dll", CharSet = CharSet.Auto,
         CallingConvention = CallingConvention.StdCall)]
        private static extern bool UnhookWindowsHookEx(int idHook);

        //Import for CallNextHookEx.
        //Use this function to pass the hook information to next hook procedure in chain.
        [DllImport("user32.dll", CharSet = CharSet.Auto,
         CallingConvention = CallingConvention.StdCall)]
        private static extern int CallNextHookEx(int idHook, int nCode,
        IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll")]
        static extern IntPtr LoadLibrary(string lpFileName);

        static Form1 View;

        const int MOD_SHIFT = 0x0004;

        IntPtr LL = (IntPtr)LoadLibrary("User32");

        public KeyHook(Form1 form, HookProc proc)
        {
            View = form;
            Hook(proc);

        }

        ~KeyHook()
        {
            UnHook();
        }

        public int Hook(HookProc proc)
        {
            hHook = SetWindowsHookEx(WH_KEYBOARD_LL, proc, LL, 0);
            return hHook;
        }

        public bool UnHook()
        {
            bool ret = UnhookWindowsHookEx(hHook);
            if (ret)
                hHook = 0;
            return ret;
        }

        public static int KeyboardHookProc(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode < 0)
            {
                return CallNextHookEx(hHook, nCode, wParam, lParam);
            }
            else
            {
                keyboardHookStruct MyKeyboardHookStruct = (keyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(keyboardHookStruct));
                switch (MyKeyboardHookStruct.vkCode)
                {
                    case (int)Keys.NumPad0:
                    case (int)Keys.NumPad1:
                    case (int)Keys.NumPad2:
                    case (int)Keys.NumPad3:
                    case (int)Keys.NumPad4:
                    case (int)Keys.NumPad5:
                        View.Activate(MyKeyboardHookStruct.vkCode - 95);
                        return 1;
                    case (int)Keys.NumPad9:
                        View.CallAlltimes();
                        return 1;
                    case (int)Keys.F2:
                            View.ShowFront();
                            return 1;
                    case (int)Keys.F9:
                        View.ChangeChat();
                        return 1;
                    case (int)Keys.F10:
                        View.StartGame();
                        return 1;
                    default:
                        return CallNextHookEx(hHook, nCode, wParam, lParam);
                }
                return 1;
            }
        }

    }

}

Form1.Designer.cs:
namespace WindowsFormsApplication1
{
    partial class Form1
    {
        /// <summary>
       /// Erforderliche Designervariable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
       /// Verwendete Ressourcen bereinigen.
        /// </summary>
        /// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Vom Windows Form-Designer generierter Code

        /// <summary>
       /// Erforderliche Methode für die Designerunterstützung.
       /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.timer2 = new System.Windows.Forms.Timer(this.components);
            this.timer3 = new System.Windows.Forms.Timer(this.components);
            this.timer4 = new System.Windows.Forms.Timer(this.components);
            this.timer5 = new System.Windows.Forms.Timer(this.components);
            this.timer6 = new System.Windows.Forms.Timer(this.components);
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.label6 = new System.Windows.Forms.Label();
            this.label9 = new System.Windows.Forms.Label();
            this.label10 = new System.Windows.Forms.Label();
            this.label11 = new System.Windows.Forms.Label();
            this.label12 = new System.Windows.Forms.Label();
            this.label13 = new System.Windows.Forms.Label();
            this.label14 = new System.Windows.Forms.Label();
            this.timer7 = new System.Windows.Forms.Timer(this.components);
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.pictureBox2 = new System.Windows.Forms.PictureBox();
            this.label7 = new System.Windows.Forms.Label();
            this.label8 = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
            this.SuspendLayout();
            // 
            // timer1
            // 
            this.timer1.Interval = 1000;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            // 
            // timer2
            // 
            this.timer2.Interval = 1000;
            this.timer2.Tick += new System.EventHandler(this.timer2_Tick);
            // 
            // timer3
            // 
            this.timer3.Interval = 1000;
            this.timer3.Tick += new System.EventHandler(this.timer3_Tick);
            // 
            // timer4
            // 
            this.timer4.Interval = 1000;
            this.timer4.Tick += new System.EventHandler(this.timer4_Tick);
            // 
            // timer5
            // 
            this.timer5.Interval = 1000;
            this.timer5.Tick += new System.EventHandler(this.timer5_Tick);
            // 
            // timer6
            // 
            this.timer6.Interval = 1000;
            this.timer6.Tick += new System.EventHandler(this.timer6_Tick);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(13, 16);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(40, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "Baron";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label2.Location = new System.Drawing.Point(111, 16);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(48, 13);
            this.label2.TabIndex = 1;
            this.label2.Text = "Dragon";
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label3.Location = new System.Drawing.Point(14, 54);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(32, 13);
            this.label3.TabIndex = 2;
            this.label3.Text = "Blue";
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label4.Location = new System.Drawing.Point(111, 54);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(30, 13);
            this.label4.TabIndex = 3;
            this.label4.Text = "Red";
            // 
            // label5
            // 
            this.label5.AutoSize = true;
            this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label5.Location = new System.Drawing.Point(14, 92);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(44, 13);
            this.label5.TabIndex = 4;
            this.label5.Text = "E Blue";
            // 
            // label6
            // 
            this.label6.AutoSize = true;
            this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label6.Location = new System.Drawing.Point(111, 92);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(42, 13);
            this.label6.TabIndex = 5;
            this.label6.Text = "E Red";
            // 
            // label9
            // 
            this.label9.AutoSize = true;
            this.label9.Location = new System.Drawing.Point(59, 16);
            this.label9.Name = "label9";
            this.label9.Size = new System.Drawing.Size(16, 13);
            this.label9.TabIndex = 8;
            this.label9.Text = "-1";
            // 
            // label10
            // 
            this.label10.AutoSize = true;
            this.label10.Location = new System.Drawing.Point(165, 16);
            this.label10.Name = "label10";
            this.label10.Size = new System.Drawing.Size(16, 13);
            this.label10.TabIndex = 9;
            this.label10.Text = "-1";
            // 
            // label11
            // 
            this.label11.AutoSize = true;
            this.label11.Location = new System.Drawing.Point(59, 54);
            this.label11.Name = "label11";
            this.label11.Size = new System.Drawing.Size(16, 13);
            this.label11.TabIndex = 10;
            this.label11.Text = "-1";
            // 
            // label12
            // 
            this.label12.AutoSize = true;
            this.label12.Location = new System.Drawing.Point(165, 54);
            this.label12.Name = "label12";
            this.label12.Size = new System.Drawing.Size(16, 13);
            this.label12.TabIndex = 11;
            this.label12.Text = "-1";
            // 
            // label13
            // 
            this.label13.AutoSize = true;
            this.label13.Location = new System.Drawing.Point(59, 92);
            this.label13.Name = "label13";
            this.label13.Size = new System.Drawing.Size(16, 13);
            this.label13.TabIndex = 12;
            this.label13.Text = "-1";
            // 
            // label14
            // 
            this.label14.AutoSize = true;
            this.label14.Location = new System.Drawing.Point(165, 92);
            this.label14.Name = "label14";
            this.label14.Size = new System.Drawing.Size(16, 13);
            this.label14.TabIndex = 13;
            this.label14.Text = "-1";
            // 
            // timer7
            // 
            this.timer7.Enabled = true;
            this.timer7.Interval = 30000;
            this.timer7.Tick += new System.EventHandler(this.timer7_Tick);
            // 
            // pictureBox1
            // 
            this.pictureBox1.BackColor = System.Drawing.Color.Lime;
            this.pictureBox1.Location = new System.Drawing.Point(191, 113);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(18, 13);
            this.pictureBox1.TabIndex = 14;
            this.pictureBox1.TabStop = false;
            // 
            // pictureBox2
            // 
            this.pictureBox2.BackColor = System.Drawing.Color.Red;
            this.pictureBox2.Location = new System.Drawing.Point(191, 94);
            this.pictureBox2.Name = "pictureBox2";
            this.pictureBox2.Size = new System.Drawing.Size(18, 13);
            this.pictureBox2.TabIndex = 15;
            this.pictureBox2.TabStop = false;
            // 
            // label7
            // 
            this.label7.AutoSize = true;
            this.label7.Location = new System.Drawing.Point(0, 111);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(0, 13);
            this.label7.TabIndex = 16;
            // 
            // label8
            // 
            this.label8.AutoSize = true;
            this.label8.Location = new System.Drawing.Point(41, 111);
            this.label8.Name = "label8";
            this.label8.Size = new System.Drawing.Size(0, 13);
            this.label8.TabIndex = 17;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(205, 124);
            this.Controls.Add(this.label8);
            this.Controls.Add(this.label7);
            this.Controls.Add(this.pictureBox2);
            this.Controls.Add(this.pictureBox1);
            this.Controls.Add(this.label14);
            this.Controls.Add(this.label13);
            this.Controls.Add(this.label12);
            this.Controls.Add(this.label11);
            this.Controls.Add(this.label10);
            this.Controls.Add(this.label9);
            this.Controls.Add(this.label6);
            this.Controls.Add(this.label5);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Name = "Form1";
            this.Text = "LoL Timer";
            this.TopMost = true;
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Timer timer1;
        private System.Windows.Forms.Timer timer2;
        private System.Windows.Forms.Timer timer3;
        private System.Windows.Forms.Timer timer4;
        private System.Windows.Forms.Timer timer5;
        private System.Windows.Forms.Timer timer6;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.Label label5;
        private System.Windows.Forms.Label label6;
        private System.Windows.Forms.Label label9;
        private System.Windows.Forms.Label label10;
        private System.Windows.Forms.Label label11;
        private System.Windows.Forms.Label label12;
        private System.Windows.Forms.Label label13;
        private System.Windows.Forms.Label label14;
        private System.Windows.Forms.Timer timer7;
        private System.Windows.Forms.PictureBox pictureBox1;
        private System.Windows.Forms.PictureBox pictureBox2;
        private System.Windows.Forms.Label label7;
        private System.Windows.Forms.Label label8;

    }
}