/// <summary>
 /// Start/stop a task, wait for its completion (but don't block events)
 /// </summary>
 /// <param name="startStop"></param>
 /// <param name="act"></param>
 /// <param name="token"></param>
 private void TaskWithCancellation(bool startStop, Func <CancellationTokenSource, int> act,
                                   CancellationTokenSource token)
 {
     if (!startStop)
     {
         if (token != null)
         {
             token.Cancel();
         }
         return;
     }
     Hide();
     try
     {
         token = new CancellationTokenSource();
         Task <int> exec = new Task <int>(delegate() { return(act(token)); });
         exec.Start();
         while (!exec.IsCompleted)
         {
             Thread.Sleep(100);
             Application.DoEvents();
         }
     }
     catch (Exception ex)
     {
         ErrorListener.Add(ex);
         txtOutput.AppendText(ex.Message);
     }
     txtOutput.AppendText(Environment.NewLine);
     Show();
 }
 private void showExampleDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
 {
     try
     {
         string path = Path.Combine(Environment.CurrentDirectory, Program.ExampleDatabaseName);
         Serialization.WriteDatabase(Program.ExampleDatabase, path);
         Process.Start(path);
     }
     catch (Exception ex)
     {
         ErrorListener.Add(ex);
     }
 }
Example #3
0
        /// <summary>
        /// Get human-readable report on colors of the points
        /// </summary>
        /// <returns>Formatted string, with an extra line appended at the end</returns>
        public string GetReport()
        {
            IntPtr hWnd = IntPtr.Zero;

            try
            {
                hWnd = Native.FindWindowByCaption(Program.WindowTitleString);
            }
            catch (Exception ex)
            {
                ErrorListener.Add(ex);
            }
            if (hWnd == IntPtr.Zero)
            {
                return("Window not found!");
            }
            Rectangle window = new Rectangle();

            try
            {
                window = Native.GetWindowRectangle(hWnd);
            }
            catch (Exception ex)
            {
                ErrorListener.Add(ex);
            }
            if (window.IsEmpty)
            {
                return("The client rectangle is empty!");
            }
            StringBuilder res = new StringBuilder();

            for (int i = 0; i < Points.Length; i++)
            {
                try
                {
                    Color c = Native.GetPixelColor(Points[i].GetPoint(PointReference.TopLeft, window));
                    res.AppendFormat("{0} = {1} ({2})", Points[i].Name, c.ToString(), (uint)c.ToArgb());
                }
                catch (Exception ex)
                {
                    ErrorListener.Add(ex);
                    res.AppendFormat("{0} = Error: {1}", Points[i].Name, ex.Message);
                }
                res.AppendLine();
            }
            return(res.ToString());
        }
 private static void Write(string path, object data, Type type, params Type[] knownTypes)
 {
     //Backup data just in case
     try
     {
         if (File.Exists(path))
         {
             File.Copy(path, Path.ChangeExtension(path, "bak"), true);
         }
     }
     catch (Exception ex)
     {
         ErrorListener.Add(ex);
         if (MessageBox.Show("Failed to backup current database/scenario. Continue anyway?",
                             Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
         {
             return;
         }
     }
     //Serialize
     try
     {
         using (var fs = new FileStream(path, FileMode.Create))
             using (var writer = XmlWriter.Create(fs, new XmlWriterSettings()
             {
                 Indent = true, IndentChars = "\t"
             }))
             {
                 DataContractSerializer ser = new DataContractSerializer(type, knownTypes);
                 try
                 {
                     ser.WriteObject(writer, data);
                 }
                 catch (Exception ex)
                 {
                     ErrorListener.Add(ex);
                 }
             }
     }
     catch (Exception ex)
     {
         ErrorListener.Add(ex);
     }
 }
Example #5
0
 private static void InstanceMain(bool prevExitOk = true)
 {
     if (!prevExitOk)
     {
         ErrorListener.EnableMessages = false;
         ErrorListener.Add(new Exception("Previous instance exited abnormally!"));
     }
     LoadSettings();
     //Prepare serialized objects
     Database          = Serialization.ReadDatabase(Database);
     Scenario          = Serialization.ReadScenario(Scenario);
     WindowTitleString = Serialization.ReadWindowTitle(WindowTitleString);
     //Init pipeline
     pipeClient = new NamedPipeClient <string>(PipeName);
     //Start WinForms
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new MainForm());
 }
 private static object Read(string path, object defaultValue, Type type, params Type[] knownTypes)
 {
     try
     {
         if (!File.Exists(path))
         {
             MessageBox.Show("No database/scenario file present! Using default settings.", Application.ProductName,
                             MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
             Write(path, defaultValue, type, knownTypes);
             return(defaultValue);
         }
         using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
             using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()))
             {
                 DataContractSerializer ser = new DataContractSerializer(type, knownTypes);
                 try
                 {
                     return(ser.ReadObject(reader));
                 }
                 catch (Exception ex)
                 {
                     ErrorListener.Add(ex);
                     MessageBox.Show("Failed to deserialize the database/scenario. The application will now terminate.",
                                     Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                     throw new SerializationException(); //This is fatal, terminate
                 }
             }
     }
     catch (Exception ex)
     {
         ErrorListener.Add(ex);
         MessageBox.Show("Failed to open the database/scenario file. The application will now terminate.",
                         Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
         throw new IOException(); //This is fatal, terminate
     }
 }
Example #7
0
        private int ExecutionEngine(CancellationTokenSource cancel = null)
        {
            Rectangle window = new Rectangle();

            if (Properties.Settings.Default.DisableWindowFilter)
            {
                window = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
            }
            else
            {
                //First, look for the window needed
                IntPtr hWnd = IntPtr.Zero;
                try
                {
                    if (Program.WindowTitleString.StartsWith(Serialization.HandlePrefix))
                    {
                        hWnd = (IntPtr)int.Parse(Program.WindowTitleString.Remove(0, Serialization.HandlePrefix.Length),
                                                 System.Globalization.NumberStyles.HexNumber);
                    }
                    else
                    {
                        hWnd = Native.FindWindowByCaption(Program.WindowTitleString);
                    }
                }
                catch (Exception ex)
                {
                    ErrorListener.Add(ex);
                }
                if (hWnd == IntPtr.Zero)
                {
                    return((int)ScenarioExitCodes.WindowNotFound);
                }
                //TODO: Next, try to bring it to front and make active

                //Next, see if it's a 0x0 rectangle (still minimized or smth)
                try
                {
                    window = Native.GetWindowRectangle(hWnd);
                }
                catch (Exception ex)
                {
                    ErrorListener.Add(ex);
                }
                if (window.IsEmpty)
                {
                    return((int)ScenarioExitCodes.EmptyWindow);
                }
            }
            //Finally, execute the scenario
            try
            {
                var dic = Program.Database.ToDictionary(x => x.Name);
                for (int i = 0; i < Actions.Length; i++)
                {
                    if (cancel != null)
                    {
                        if (cancel.IsCancellationRequested)
                        {
                            return((int)ScenarioExitCodes.Aborted);
                        }
                    }
                    if (CheckKeyPressed(LoopBreakKey))
                    {
                        return((int)ScenarioExitCodes.Aborted);
                    }
                    switch (Actions[i].Type)
                    {
                    case ActionTypes.MouseClick:
                        MouseClick(dic[(string)Actions[i].Arguments[0]], window);
                        break;

                    case ActionTypes.RightMouseClick:
                        RightMouseClick(dic[(string)Actions[i].Arguments[0]], window);
                        break;

                    case ActionTypes.LeftMouseDoubleClick:
                        LeftMouseDoubleClick(dic[(string)Actions[i].Arguments[0]], window);
                        break;

                    case ActionTypes.PressKey:
                        PressKey((WindowsInput.Native.VirtualKeyCode)Actions[i].Arguments[0]);
                        break;

                    case ActionTypes.WaitForPixel:
                    {
                        bool r = WaitForPixel(dic[(string)Actions[i].Arguments[0]], window, (Color)Actions[i].Arguments[1],
                                              cancel, (Actions[i].Arguments.Length > 2) ? (int)Actions[i].Arguments[2] : 0);
                        if (FailOnTimeout && !r)
                        {
                            throw new TimeoutException();
                        }
                        break;
                    }

                    case ActionTypes.Sleep:
                        Sleep((int)Actions[i].Arguments[0]);
                        break;

                    default:
                        break;
                    }
                }
            }
            catch (InvalidCastException ex)
            {
                ErrorListener.AddFormat(ex, "Wrong arguments specified for an action!");
                return((int)ScenarioExitCodes.WrongArguments);
            }
            catch (TimeoutException)
            {
                ErrorListener.Add(new Exception("Timed out during waiting for pixel color (FailOnTimeout is set to True)."));
                return((int)ScenarioExitCodes.Timeout);
            }
            catch (Exception ex)
            {
                ErrorListener.Add(ex);
                return((int)ScenarioExitCodes.UnexpectedError);
            }
            return((int)ScenarioExitCodes.OK);
        }