Пример #1
0
 public void Show()
 {
     if (_path != null && AFile.ExistsAsFile(_path))
     {
         AExec.TryRun(_path);
     }
 }
Пример #2
0
 /// <summary>
 /// Starts task process.
 /// Returns (processId, processHandle). Throws if failed.
 /// </summary>
 static (int pid, WaitHandle hProcess) _StartProcess(_SpUac uac, string exeFile, string args, string wrPipeName)
 {
     if (wrPipeName != null)
     {
         wrPipeName = "ATask.WriteResult.pipe=" + wrPipeName;
     }
     if (uac == _SpUac.admin)
     {
         if (wrPipeName != null)
         {
             throw new AuException($"*start process '{exeFile}' as admin and enable ATask.WriteResult");                                //cannot pass environment variables. //rare //FUTURE
         }
         var k = AExec.Run(exeFile, args, RFlags.Admin | RFlags.NeedProcessHandle, "");
         return(k.ProcessId, k.ProcessHandle);
         //note: don't try to start task without UAC consent. It is not secure.
         //	Normally Au editor runs as admin in admin user account, and don't need to go through this.
     }
     else
     {
         var ps   = new Au.Util.ProcessStarter_(exeFile, args, "", envVar: wrPipeName, rawExe: true);
         var need = Au.Util.ProcessStarter_.Result.Need.WaitHandle;
         var psr  = uac == _SpUac.userFromAdmin ? ps.StartUserIL(need) : ps.Start(need, inheritUiaccess: uac == _SpUac.uiAccess);
         return(psr.pid, psr.waitHandle);
     }
 }
Пример #3
0
    void _Toolbar_Common1()
    {
        var t = new AToolbar("_Toolbar_Common1");

        if (!t.SettingsModified)
        {
            //first time set initial properties that are in the right-click menu. Later use saved values.
            t.AutoSize = true;
        }
        //set other properties
        t.BorderColor = System.Drawing.Color.Olive;

        //add buttons
        t["A"] = o => {  };
        t["B"] = o => {  };
        t.MenuButton("C", m => { //drop-down menu
            m["X"] = o => {  };
            m["Y"] = o => {  };
        });
        t.Group("Examples"); //horizontal separator, optionally with text
        t.NoText         = true;
        t["Run program"] = o => AExec.Run(AFolders.System + @"notepad.exe");
        t["Run script"]  = o => ATask.Run("Script example1.cs");
        t["Copy-paste"]  = o => {
            string s = AClipboard.Copy();     //note: to test it, at first select some text somewhere, else it will fail
            s = s.Upper();
            AClipboard.Paste(s);
        };

        bool autoHide = false; //or true

        if (autoHide)
        {
            //An "auto-hide" toolbar actually consists of 2 toolbars:
            //	t - toolbar with many buttons. Hidden when mouse pointer isn't in toolbar t2.
            //	t2 - small toolbar with zero or few buttons. It is the owner of toolbar t.
            var t2 = new AToolbar(t.Name + "^")
            {
                Satellite = t
            };
            t2.Show();
        }
        else
        {
            t.Show();
        }
    }
Пример #4
0
    void _html_LinkClicked(object sender, HtmlLinkClickedEventArgs e)
    {
        e.Handled = true;
        var s = e.Link;

        if (s == "?")
        {
            ZSetText(c_aboutHtml);
        }
        else if (s.Starts('#'))            //anchor
        {
            e.Handled = false;
        }
        else
        {
            AExec.TryRun(s);
        }
    }
Пример #5
0
    void HotkeyTriggers()
    {
        var hk = Triggers.Hotkey;

        //examples of hotkey triggers

        hk["Ctrl+Alt+K"]     = o => AOutput.Write(o.Trigger); //it means: when I press Ctrl+Alt+K, execute action "AOutput.Write(o.Trigger)"
        hk["Ctrl+Shift+F11"] = o => {                         //action can have multiple statements
            var w1 = AWnd.FindOrRun("* Notepad", run: () => AExec.Run(AFolders.System + "notepad.exe"));
            AKeys.Text("text");
            500.ms();
            w1.Close();
        };
        hk["Ctrl+Shift+1"] = o => TriggerActionExample();          //action code can be in other function. To find it quickly, Ctrl+click the function name here.
        hk["Ctrl+Shift+2"] = o => TriggerActionExample2(o.Window); //the function can be in any class or partial file of this project folder
        hk["Ctrl+Shift+3"] = o => ATask.Run("Script example1.cs"); //run script in separate process. Then don't need to restart triggers when editing the script.

        //triggers that work only with some windows (when the window is active)

        Triggers.Of.Window("* WordPad", "WordPadClass");

        hk["Ctrl+F5"] = o => AOutput.Write("action 1", o.Trigger, o.Window);
        //hk[""] = o => {  };
        //...

        Triggers.Of.Windows(",,notepad.exe"); //all windows of notepad.exe process

        hk["Ctrl+F5"] = o => AOutput.Write("action 2", o.Trigger, o.Window);
        //hk[""] = o => {  };
        //...

        //...

        //disable/enable triggers
        Triggers.Of.AllWindows();
        hk["Ctrl+Alt+Win+D"]  = o => ActionTriggers.DisabledEverywhere ^= true;
        hk.Last.EnabledAlways = true;

        //To add triggers can be used snippets. Start typing "trig" and you will see snippets in the completion list.
        //For more info click word ActionTriggers above and press F1.
    }
Пример #6
0
partial class Script : AScript { [STAThread] static void Main(string[] a) => new Script(a); Script(string[] args)   //;;;
//Click the ► button on the toolbar to run the script.

                                 {
                                     AOutput.Write("The programming language is C#.");
                                     if (ADialog.ShowYesNo("Run Notepad?", "The script will add some text and close Notepad after 2 s."))
                                     {
                                         AExec.Run(AFolders.System + @"Notepad.exe");
                                         var w = AWnd.Wait(5, active: true, "*- Notepad"); //to create this code can be used the Code menu
                                         50.ms();
                                         AKeys.Text("some text");
                                         2.s();
                                         AKeys.Key("Ctrl+Z"); //Undo
                                         w.Close();
                                     }

                                     string linkText = "Read about code editor features",
                                            linkUrl  = "https://www.quickmacros.com/au/help/editor/Code editor.html";

                                     AOutput.Write($"<><link \"{linkUrl}\">{linkText}</link>");
                                 }
Пример #7
0
    static void Compress(string docDir)
    {
        var sevenZip = @"C:\Program Files\7-Zip\7z.exe";

        AFile.Delete(docDir + @"\_site.tar");
        AFile.Delete(docDir + @"\_site.tar.bz2");

        int r1 = AExec.RunConsole(out var s, sevenZip, $@"a _site.tar .\_site\*", docDir);

        if (r1 != 0)
        {
            AOutput.Write(s); return;
        }
        int r2 = AExec.RunConsole(out s, sevenZip, $@"a _site.tar.bz2 _site.tar", docDir);

        if (r2 != 0)
        {
            AOutput.Write(s); return;
        }

        AFile.Delete(docDir + @"\_site.tar");

        AOutput.Write("Compressed");
    }
Пример #8
0
    async void _ConvertTypeLibrary(object tlDef, object button)
    {
        string comDll = null;

        switch (tlDef)
        {
        case string path:
            comDll = path;
            break;

        case _RegTypelib r:
            //can be several locales
            var aloc  = new List <string>();           //registry keys like "0" or "409"
            var aloc2 = new List <string>();           //locale names for display in the list dialog
            using (var verKey = Registry.ClassesRoot.OpenSubKey($@"TypeLib\{r.guid}\{r.version}")) {
                foreach (var s1 in verKey.GetSubKeyNames())
                {
                    int lcid = s1.ToInt(0, out int iEnd, STIFlags.IsHexWithout0x);
                    if (iEnd != s1.Length)
                    {
                        continue;                                       //"FLAGS" etc; must be hex number without 0x
                    }
                    aloc.Add(s1);
                    var s2 = "Neutral";
                    if (lcid > 0)
                    {
                        try { s2 = new CultureInfo(lcid).DisplayName; } catch { s2 = s1; }
                    }
                    aloc2.Add(s2);
                }
            }
            string locale;
            if (aloc.Count == 1)
            {
                locale = aloc[0];
            }
            else
            {
                int i = ADialog.ShowList(aloc2, "Locale", owner: this);
                if (i == 0)
                {
                    return;
                }
                locale = aloc[i - 1];
            }
            comDll = r.GetPath(locale);
            if (comDll == null || !AFile.ExistsAsFile(comDll))
            {
                ADialog.ShowError(comDll == null ? "Failed to get file path." : "File does not exist.", owner: this);
                return;
            }
            break;
        }

        await Task.Run(() => {
            this.Enabled = false;
            AOutput.Write($"Converting COM type library to .NET assembly.");
            try {
                if (_convertedDir == null)
                {
                    _convertedDir = AFolders.Workspace + @".interop\";
                    AFile.CreateDirectory(_convertedDir);
                }
                List <string> converted  = new List <string>();
                Action <string> callback = s => {
                    AOutput.Write(s);
                    if (s.Starts("Converted: "))
                    {
                        s.RegexMatch(@"""(.+?)"".$", 1, out s);
                        converted.Add(s);
                    }
                };
                int rr = AExec.RunConsole(callback, AFolders.ThisAppBS + "Au.Net45.exe", $"/typelib \"{_convertedDir}|{comDll}\"", encoding: Encoding.UTF8);
                if (rr == 0)
                {
                    foreach (var v in converted)
                    {
                        if (!_meta.com.Contains(v))
                        {
                            _meta.com.Add(v);
                        }
                    }
                    AOutput.Write(@"<>Converted and saved in <link>%AFolders.Workspace%\.interop<>.");
                    _Added(button, _meta.com);
                }
            }
            catch (Exception ex) { ADialog.ShowError("Failed to convert type library", ex.ToStringWithoutStack(), owner: this); }
            this.Enabled = true;
        });
    }
Пример #9
0
        /// <summary>
        /// Toolbar button MouseUp handler. Implements context menu that allows to customize.
        /// </summary>
        private void _OnMouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Right)
            {
                return;
            }
            var  item        = sender as ToolStripItem;
            var  ts          = item.Owner;
            var  dd          = ts as ToolStripDropDownMenu;
            bool isMenu      = dd != null;
            bool isCustom    = ts == _tsCustom1 || ts == _tsCustom2;
            bool isSeparator = item is ToolStripSeparator;
            bool isHidden    = item.Overflow == ToolStripItemOverflow.Always;
            var  x           = item.Tag as XElement;

            var m = new AMenu();

            m["Properties..."] = o => {
                using (var f = new FSMProperties(this, item.Tag as XElement, isMenu)) {
                    if (f.ShowDialog(_form) == DialogResult.OK)
                    {
                        _Strips_Customize(6, item, null, f);
                    }
                }
            };
            if (!isMenu)
            {
                if (!isSeparator)
                {
                    m["Hide"] = o => _Strips_Customize(5, item); if (isHidden)
                    {
                        m.LastMenuItem.Checked = true;
                    }
                }
                if (isCustom || isSeparator)
                {
                    m["Remove"] = o => _Strips_Customize(3, item);
                }
                if (!isHidden)
                {
                    m["Add separator"] = o => _Strips_Customize(4, item, ts);
                }
            }
            if (isCustom)
            {
                if (_tsCustom1 != null && _tsCustom2 != null)
                {
                    if (ts == _tsCustom1)
                    {
                        m["Move to toolbar Custom2"] = o => _Strips_Customize(2, item, _tsCustom2);
                    }
                    else
                    {
                        m["Move to toolbar Custom1"] = o => _Strips_Customize(2, item, _tsCustom1);
                    }
                }
            }
            else
            {
                if (_tsCustom1 != null)
                {
                    m["Copy to toolbar Custom1"] = o => _Strips_Customize(1, item, _tsCustom1);
                }
                if (_tsCustom2 != null)
                {
                    m["Copy to toolbar Custom2"] = o => _Strips_Customize(1, item, _tsCustom2);
                }
            }
            if (!isMenu)
            {
                m.Separator();
                m["How to customize..."] = o => ADialog.ShowInfo("Customizing toolbars and menus",
                                                                 @"There are several standard toolbars and two custom toolbars (initially empty). Standard toolbar buttons cannot be added and removed, but can be hidden and reordered. Menu items cannot be added, removed, hidden and reordered.

You can find most customization options in two context menus. Right-clicking a button or menu item shows its context menu. Right-clicking before the first button shows toolbar's context menu. You can Alt+drag toolbar buttons to reorder them on the same toolbar. You can Alt+drag toolbars to dock them somewhere else. Use splitters to resize. Right click a splitter to change its thickness."
                                                                 );
                string folder = APath.GetDirectoryPath(_xmlFileCustom), link = $"<a href=\"{folder}\">{folder}</a>";
                m["How to backup, restore, reset..."] = o => {
                    ADialog.Show("How to backup, restore or reset customizations",
                                 $@"All customizations are saved in XML files in folder
{link}

To backup:  copy the file.
To restore:  exit this application and replace the file with the backup file.
To reset:  exit this application and delete the file."
                                 , icon: DIcon.Info, onLinkClick: h => { AExec.Run(h.LinkHref); });
                };
            }

            m.Show(ts);
        }
Пример #10
0
 /// <summary>
 /// Opens an Au library help topic onine.
 /// </summary>
 /// <param name="topic">Topic file name, like "Au.AAcc.Find" or "AAcc.Find" or "articles/Wildcard expression".</param>
 public static void AuHelp(string topic)
 {
     AExec.TryRun(AuHelpUrl(topic));
 }
Пример #11
0
 public void Help_Email()
 {
     AExec.TryRun("mailto:[email protected]?subject=" + Program.AppName);
 }
Пример #12
0
    static void _Main()
    {
        bool isConsole = AOutput.IsConsoleProcess;

        if (!isConsole)
        {
            AOutput.QM2.UseQM2 = true;
            AOutput.Clear();
        }

        var docfx   = @"Q:\Programs\DocFx\docfx.exe";
        var objDir  = @"Q:\Temp\Au\DocFX\obj";
        var docDir  = @"Q:\app\Au\Other\DocFX\_doc";
        var siteDir = docDir + @"\_site";
        var apiDir  = docDir + @"\api";

        //ProcessYamlFile(apiDir + @"\Au.AaaDocFX.yml", true); return;
        //ProcessHtmlFiles(siteDir, true); return;
        //ProcessToc(siteDir); return;

        //Compress(docDir); return;
        //Upload(docDir); return;
        //CompressAndUpload(docDir); return;

        foreach (var v in Process.GetProcessesByName("docfx"))
        {
            v.Kill();
        }
        if (isConsole)
        {
            int k = 0;
            foreach (var v in AWnd.FindAll(@"C:\WINDOWS\system32\cmd.exe", "ConsoleWindowClass"))
            {
                if (k++ > 0)
                {
                    v.Close();
                }
            }
        }

        AFile.Delete(siteDir);
        Directory.SetCurrentDirectory(docDir);

        var t1 = ATime.PerfMilliseconds;

        using (var fw = new FileSystemWatcher(apiDir, "*.yml")) {
            fw.Changed += (sen, e) => {
                //AOutput.Write(e.Name);
                if (e.Name.Starts("Au.", true))
                {
                    ProcessYamlFile(e.FullPath, false);
                }
            };
            fw.EnableRaisingEvents = true;
            fw.NotifyFilter        = NotifyFilters.LastWrite;

            bool serving = false;
            try {
                AExec.RunConsole(o => {
                    AOutput.Write(o);
                    if (o.Starts("Serving"))
                    {
                        throw new OperationCanceledException();
                    }
                }, docfx, $@"docfx.json --intermediateFolder ""{objDir}"" --serve");
                // --force
            }
            catch (OperationCanceledException) {
                serving = true;
            }
            //if(!serving) { ADialog.Show("error?"); return; } //need if this process is not hosted
            if (!serving)
            {
                return;
            }
        }

        var t2 = ATime.PerfMilliseconds;

        ProcessHtmlFiles(siteDir, false);

        var t3 = ATime.PerfMilliseconds; AOutput.Write("speed (s):", (t2 - t1) / 1000, (t3 - t2) / 1000);

        //AWnd.Find("* Chrome").Activate();
        //AKeys.Key("F5");

        1.s();
        if (1 == ADialog.Show("Upload?", null, "1 Yes|2 No" /*, secondsTimeout: 5*/))
        {
            CompressAndUpload(docDir);
        }

        //Delete obj folder if big. Each time it grows by 10 MB, and after a day or two can be > 1 GB. After deleting builds slower by ~50%.
        if (AFile.More.CalculateDirectorySize(objDir) / 1024 / 1024 > 500)
        {
            AOutput.Write("Deleting obj folder."); AFile.Delete(objDir);
        }
        //info: if DocFX starts throwing stack overflow exception, delete the obj folder manually. It is likely to happen after many refactorings in the project.
    }
Пример #13
0
partial class Script : AScript { [STAThread] static void Main(string[] a) => new Script(a); Script(string[] args) { //;;;

/*
The programming language is C#.

In scripts you can use classes/functions of the automation library provided by
this program, as well as of .NET Core and everything that can be used in C#.
Also you can create and use new functions, classes, libraries and .exe programs.

Script properties are saved in /*/ /*/ comments at the very start of script.
You can change them in the Properties dialog.

Like all C# programs, a script starts with standard code: using directives,
class and function Main where the program starts. Click the small [+] box at
the top-left to see and edit that code when need. The //. and //; are used to
fold (hide) code.

To avoid 'static' everywhere, function Main creates a class instance. Your script
code is in the constructor function. The function and the class end with } and }.

To run a script, you can click the ► Run button on the toolbar, or use command line,
or call ATask.Run from another scrit, or in Options set to run at startup.

Triggers such as hotkeys, autotext, mouse and window are used to execute functions
in a running script. Also you can create custom toolbars and menus. To start
using them: menu File -> New -> Examples -> @Triggers and toolbars.
*/

//Examples of automation functions.

AOutput.Write("Main script code.");

ADialog.Show("Message box.");

AExec.Run(AFolders.System + "notepad.exe");
var w = AWnd.Wait(0, true, "*- Notepad");
AKeys.Key("F5 Enter*2");
AKeys.Text(w.Name);
2.s();
w.Close();
var w2 = AWnd.Wait(-3, true, "Notepad", "#32770");
if(!w2.Is0) {
	500.ms();
	var c = +w2.Child(null, "Button", skip: 1); // "Don't Save"
	AMouse.Click(c);
	500.ms();
}

//Examples of .NET functions.

string s = "Example";
var b = new System.Text.StringBuilder();
for(int i = 0; i < s.Length; i++) {
	b.Append(s[i]).AppendLine();
}
MessageBox.Show(b.ToString());

//Example of your function and how functions can share variables.

_sharedVariable = 1;
FunctionExample("Example");
AOutput.Write(_sharedVariable);

} //end of main function