Pular para o conteúdo principal

Exemplos

Scripts funcionais que cobrem a sintaxe e as áreas de funções internas. Filtre por tópico ou pesquise no código e no texto deles. Scripts que usam funções internas Context* precisam do gatilho que elas descrevem, como um gesto, uma tecla de atalho ou um evento global. No console de diagnóstico, essas funções internas retornam os seus valores padrão vazios.

Olá, console​

O menor script. UtilityPrint escreve no console de diagnóstico: na guia Script quando o script é executado nela e, caso contrário, na guia Usuário.

UtilityPrint("Hello from Input.Observer");

Os cinco tipos de valor​

Uma variável de cada tipo, impressa por meio de StringFormat, que é a única forma de converter um valor que não é Text em Text.

count = 3; // Integer
ratio = 0.75; // Real
name = "Notepad"; // Text
enabled = true; // Bool
w = WindowGetActive(); // Window

UtilityPrint(StringFormat("count={0} ratio={1}", count, ratio)); // count=3 ratio=0.750000
UtilityPrint(StringFormat("name={0} enabled={1}", name, enabled)); // name=Notepad enabled=true
UtilityPrint(StringFormat("window handle={0}", w, ""));

Valor verdadeiro de cada tipo​

O que if considera verdadeiro em cada tipo: números diferentes de zero, Text não vazio, identificadores não nulos.

if (0) UtilityPrint("never");
if (-1) UtilityPrint("-1 is true");
if (0.0) UtilityPrint("never");
if ("") UtilityPrint("never");
if (" ") UtilityPrint("a single space is true");
if ("false") UtilityPrint("the text \"false\" is true -- it's not empty");
if (!WindowFindByTitle("no window has this title zzz")) UtilityPrint("null handle is false");

Encadeamento else-if​

Classifica a posição horizontal do cursor em terços do monitor sob ele.

x = MouseGetCursorX();
y = MouseGetCursorY();
left = DisplayMonitorGetRectXFromPoint(x, y, false);
width = DisplayMonitorGetRectWidthFromPoint(x, y, false);

offset = x - left;
if (offset < width / 3) {
zone = "left";
} else if (offset < width * 2 / 3) {
zone = "center";
} else {
zone = "right";
}
UtilityPrint("Cursor is in the " + zone + " third");

Loops de contagem: crescente, decrescente e em saltos​

As três partes de for são atribuições ou expressões à sua escolha.

sum = 0;
for (i = 1; i <= 100; i = i + 1) sum = sum + i;
UtilityPrint(StringFormat("1..100 = {0}", sum, "")); // 5050

for (i = 5; i > 0; i = i - 1) UtilityPrint(StringFormat("{0}...", i, ""));

for (p = 1; p <= 1024; p = p * 2) UtilityPrint(StringFormat("{0}", p, "")); // powers of two

Loops aninhados: uma tabuada​

Loops for aninhados que montam uma linha de Text por fileira.

for (r = 1; r <= 5; r = r + 1) {
line = "";
for (c = 1; c <= 5; c = c + 1) {
line = line + StringFormat("{0}\t", r * c, "");
}
UtilityPrint(line);
}

Loop while: aguardar uma janela, com tempo limite​

A condição faz o papel do "while", e o contador limita a espera a 5 segundos.

ShellRun("notepad.exe");
w = WindowFindByTitle("Notepad");
for (tries = 0; !w && tries < 50; tries = tries + 1) {
UtilityWait(100);
w = WindowFindByTitle("Notepad");
}
if (w) {
WindowCenterToScreen(w);
} else {
UtilityPrint("Notepad didn't appear within 5 seconds");
}

while (true) com um sinalizador de saída​

Um passo que atribui uma variável a ela mesma (go = go) cria um loop que só termina quando o seu corpo limpa o sinalizador. A tecla de atalho de parar tudo também sempre o encerra.

rolls = 0;
for (go = true; go; go = go) {
rolls = rolls + 1;
if (MathRandom(1, 6) == 6) go = false;
}
UtilityPrint(StringFormat("Rolled a six after {0} tries", rolls, ""));

break e continue​

Coloque o contador além do limite para fazer um break. Coloque o restante do corpo dentro de um if para fazer um continue.

n = StringSplit("keep,,skip-me,keep too,STOP,never reached", ",");
for (i = 0; i < n; i = i + 1) {
part = StringGetSplitPartAt(i);
if (part == "STOP") {
i = n; // break
} else if (part && !StringStartsWith(part, "skip")) { // continue for empty / skip-*
UtilityPrint(part);
}
}

Surpresas de precedência​

Duas armadilhas de precedência de C e os parênteses explícitos que as corrigem.

flags = 6;
a = flags & 4 == 4; // flags & (4 == 4) -> 6 & true -> 0 (Bool operand)
b = (flags & 4) == 4; // true

x = 5;
c = 0 < x < 10; // (0 < x) < 10 -> true < 10 -> false (Bool vs Integer)
d = x > 0 && x < 10; // true

UtilityPrint(StringFormat("a={0} b={1}", a, b));
UtilityPrint(StringFormat("c={0} d={1}", c, d));

&& e || avaliam os dois lados​

Os dois operandos são sempre executados, o que importa quando o lado direito tem um efeito ou pode falhar.

StorageSetValue("calls", 0);

// Both sides run even though the left is false; the right side's
// StorageSetValue still happens.
if (false && StorageSetValue("calls", 1)) { }
UtilityPrint(StringFormat("calls = {0}", StorageGetValue("calls"), "")); // calls = 1

// Guard a call that could fail with a nested if, not &&:
text = "no colon here";
idx = StringGetIndexOf(text, ":");
if (idx >= 0) {
UtilityPrint(StringGetSubstring(text, idx + 1, 100));
}

Igualdade entre tipos​

Integer e Real são comparados numericamente. Qualquer outro par de tipos diferentes é simplesmente diferente.

UtilityPrint(StringFormat("5 == 5.0 -> {0}", 5 == 5.0, "")); // true
UtilityPrint(StringFormat("1 == true -> {0}", 1 == true, "")); // false
UtilityPrint(StringFormat("\"5\" == 5 -> {0}", "5" == 5, "")); // false
UtilityPrint(StringFormat("\"a\" == \"A\" -> {0}", "a" == "A", "")); // false (case-sensitive)
w = WindowFindByTitle("zzz no such window");
UtilityPrint(StringFormat("w == 0 -> {0}, !w -> {1}", w == 0, !w)); // false, true

Aritmética com tipos mistos resulta em 0​

Combinações que um operador não entende produzem Integer 0 sem erro. Imprima um valor quando um resultado parecer errado.

a = "Total: " + 5; // 0 -- not "Total: 5"
b = true + 1; // 0
c = -"text"; // 0
d = 2.5 & 1; // 0 -- bitwise needs Integers
e = "Total: " + StringFormat("{0}", 5, ""); // "Total: 5"
UtilityPrint(StringFormat("{0} {1}", a, b) + StringFormat(" {0} {1} ", c, d) + e);

Comentários, instruções vazias e blocos​

Comentários de linha e de bloco, um ponto e vírgula solto e um bloco no nível superior (que não cria um escopo).

// line comment
/* block comment
spanning lines */
x = 1;; // the extra ';' is an empty statement
{
y = x + 1; /* blocks group statements... */
}
UtilityPrint(StringFormat("y = {0}", y, "")); // ...but y is still visible here

Divisão de Integer e de Real, e divisão por zero​

A divisão de inteiros trunca em direção a zero, um operando Real produz um resultado Real, e a divisão por zero produz 0.

a = 7 / 2; // 3
b = 7 / 2.0; // 3.5
c = 7 * 1.0 / 2; // 3.5 -- convert first, then divide
d = -7 / 2; // -3 (toward zero)
e = 5 / 0; // 0, no error
UtilityPrint(StringFormat("{0} {1}", a, b) + StringFormat(" {0} {1}", c, d) + StringFormat(" {0}", e, ""));

Resto sem %​

n - (n / d) * d é o % de C. Com um divisor que é potência de dois, uma máscara faz o mesmo para números não negativos.

n = 17;
d = 5;
rem = n - (n / d) * d; // 2
isEven = (n & 1) == 0; // false
low3 = n & 7; // 17 % 8 == 1
UtilityPrint(StringFormat("17 % 5 = {0}, even = {1}", rem, isEven));
UtilityPrint(StringFormat("17 % 8 = {0}", low3, ""));

Arredondamento e funções internas de matemática com Real​

Um Integer passado onde uma função interna declara Real vira um Real. O arredondamento leva as metades para longe do zero.

n = 16;
root = MathSqrt(n); // 4.0 -- n is widened to 16.0

UtilityPrint(StringFormat("round 2.5 -> {0}", MathRound(2.5), "")); // 3
UtilityPrint(StringFormat("round -2.5 -> {0}", MathRound(-2.5), "")); // -3
UtilityPrint(StringFormat("floor -1.5 -> {0}", MathFloor(-1.5), "")); // -2
UtilityPrint(StringFormat("ceil 1.01 -> {0}", MathCeil(1.01), "")); // 2
UtilityPrint(StringFormat("sqrt 16 -> {0}", MathRound(root), "")); // 4

Limitar um valor a um intervalo​

MathClamp (como MathMin/MathMax) aceita os dois tipos numéricos e retorna o vencedor como ele era.

v = 300;
v = MathClamp(v, 0, 255); // 255
dist = MathAbs(-42); // 42 (Integer stays Integer)
UtilityPrint(StringFormat("clamped={0} abs={1}", v, dist));

Números aleatórios e cara ou coroa​

MathRandom inclui as duas extremidades do intervalo.

die = MathRandom(1, 6);
if (MathRandom(0, 1) == 1) side = "heads"; else side = "tails";
UtilityPrint(StringFormat("die={0}, coin={1}", die, side));

Comprimento do traço de um gesto​

Soma a distância em linha reta entre pontos consecutivos do gesto. A soma dos quadrados, um Integer, vira Real ao entrar em MathSqrt.

n = ContextGetPointCount();
total = 0.0;
for (i = 1; i < n; i = i + 1) {
dx = ContextGetPointX(i) - ContextGetPointX(i - 1);
dy = ContextGetPointY(i) - ContextGetPointY(i - 1);
total = total + MathSqrt(dx * dx + dy * dy);
}
UtilityPrint(StringFormat("{0} points, {1} px long", n, MathRound(total)));

Mover o mouse em círculo​

Graus para radianos, trigonometria com Reals e MathRound de volta para coordenadas de pixel Integer.

cx = MouseGetCursorX();
cy = MouseGetCursorY();
radius = 80.0;
for (deg = 0; deg <= 360; deg = deg + 10) {
rad = deg * MathGetPi() / 180;
MouseMoveTo(cx + MathRound(radius * MathCos(rad)), cy + MathRound(radius * MathSin(rad)));
UtilityWait(15);
}
MouseMoveTo(cx, cy);

Formatar um Real sem seis casas decimais​

Multiplique por uma escala e arredonde para obter uma porcentagem, ou para separar um valor em parte inteira e centésimos e ter duas casas decimais. Funciona com valores não negativos.

ratio = 2.0 / 3.0;
pct = MathRound(ratio * 100); // 67

value = 3.14159;
cents = MathRound(value * 100); // 314
whole = cents / 100; // 3
frac = cents - whole * 100; // 14
if (frac < 10) fracText = StringFormat("0{0}", frac, ""); else fracText = StringFormat("{0}", frac, "");
UtilityPrint(StringFormat("{0}% and {1}", pct, StringFormat("{0}.", whole, "") + fracText)); // 67% and 3.14

Máscaras de sinalizadores: ativar, desativar, inverter, testar​

As quatro operações de máscara habituais sobre os seus próprios valores de sinalizadores.

BOLD = 0x1;
ITALIC = 0x2;
UNDERLINE = 0x4;

style = BOLD | UNDERLINE; // 0b101 = 5
style = style | ITALIC; // set -> 7
style = style & ~BOLD; // clear -> 6
style = style ^ UNDERLINE; // toggle -> 2

if ((style & ITALIC) != 0) UtilityPrint("italic is on");
if ((style & BOLD) == 0) UtilityPrint("bold is off");
UtilityPrint(StringFormat("style = {0}", style, ""));

Ler a cor do pixel sob o cursor​

Desempacote o Integer 0xRRGGBB com deslocamentos e máscaras.

c = DisplayGetPixelColorFromPoint(MouseGetCursorX(), MouseGetCursorY());
if (c < 0) {
UtilityPrint("The cursor isn't over any monitor");
} else {
r = (c >> 16) & 0xFF;
g = (c >> 8) & 0xFF;
b = c & 0xFF;
UtilityPrint(StringFormat("R={0} G={1}", r, g) + StringFormat(" B={0}", b, ""));
if (r > 200 && g < 80 && b < 80) UtilityPrint("That's red");
}

Integer para texto hexadecimal​

Nenhuma função interna formata em hexadecimal, então retire quatro bits por vez e procure cada dígito em um Text.

digits = "0123456789ABCDEF";
value = 48879;
hex = "";
for (v = value; v > 0; v = v >> 4) {
hex = StringGetSubstring(digits, v & 0xF, 1) + hex;
}
if (!hex) hex = "0";
UtilityPrint("0x" + hex); // 0xBEEF

Contar os bits ativos​

Desloque por todos os 64 bits e some cada bit menos significativo.

v = 0xB6; // 1011 0110
bits = 0;
for (i = 0; i < 64; i = i + 1) {
bits = bits + ((v >> i) & 1);
}
UtilityPrint(StringFormat("0xB6 has {0} bits set", bits, "")); // 5

Casos extremos de deslocamento​

>> preserva o sinal, e um deslocamento fora de 0–63 produz 0.

UtilityPrint(StringFormat("1 << 10 = {0}", 1 << 10, "")); // 1024
UtilityPrint(StringFormat("-16 >> 2 = {0}", -16 >> 2, "")); // -4
UtilityPrint(StringFormat("1 << 64 = {0}", 1 << 64, "")); // 0
UtilityPrint(StringFormat("~0 = {0}", ~0, "")); // -1

Trocar dois Integers​

A forma comum precisa de uma variável temporária. O XOR troca sem ela.

a = 12; b = 34;
t = a; a = b; b = t; // with a temporary
a = a ^ b; b = a ^ b; a = a ^ b; // XOR swap back
UtilityPrint(StringFormat("a={0} b={1}", a, b)); // a=12 b=34

Bits de estado de tecla​

KeyboardGetKeyState retorna o valor bruto do Win32: o bit alto significa que a tecla está pressionada, o bit baixo significa que ela está alternada. As funções internas Is* fazem o mesmo teste para você.

caps = KeyboardGetKeyState(VirtualKey.CapsLock);
shift = KeyboardGetKeyState(VirtualKey.ShiftKey);
UtilityPrint(StringFormat("Caps Lock on: {0}, Shift held: {1}", (caps & 1) != 0, (shift & 0x8000) != 0));
UtilityPrint(StringFormat("same via builtins: {0}, {1}",
KeyboardIsKeyToggled(VirtualKey.CapsLock), KeyboardIsKeyDown(VirtualKey.ShiftKey)));

Sequências de escape e caminhos do Windows​

Duplique cada barra invertida em um caminho. \t, \n e \r são sequências de escape, e qualquer outra barra invertida é descartada.

good = "C:\\Temp\\report.txt"; // C:\Temp\report.txt
bad = "C:\Temp\new.txt"; // C:<no backslash>Temp<line break>ew.txt
quote = "He said \"stop\"";
tabs = "Name\tValue";
cont = "one logical line, \
written on two";
UtilityPrint(good);
UtilityPrint(bad);
UtilityPrint(quote);
UtilityPrint(tabs);
UtilityPrint(cont);

Formatar mais de dois valores​

StringFormat preenche somente {0} e {1}. Aninhe uma chamada ou junte várias com +.

w = WindowGetActive();
x = WindowGetX(w); y = WindowGetY(w);
width = WindowGetWidth(w); height = WindowGetHeight(w);

// nest: the inner call leaves "{0},{1}" for the outer call to fill
a = StringFormat(StringFormat("{0}x{1} at ", width, height) + "{0},{1}", x, y);
// concatenate: each call formats its own piece
b = StringFormat("pos {0},{1}", x, y) + StringFormat(" size {0}x{1}", width, height);
UtilityPrint(a);
UtilityPrint(b);

Dividir e percorrer​

StringSplit retorna a contagem, e StringGetSplitPartAt lê cada parte. As partes entre dois delimitadores adjacentes são vazias.

n = StringSplit("red,green,,blue", ",");
for (i = 0; i < n; i = i + 1) {
UtilityPrint(StringFormat("{0}: [{1}]", i, StringGetSplitPartAt(i)));
}
// 0: [red] 1: [green] 2: [] 3: [blue]

Divisões aninhadas: pares chave=valor​

A divisão interna substitui as partes da divisão externa, então divida a lista externa de novo no início de cada passagem.

config = "width=800;height=600;title=Main";
n = StringSplit(config, ";");
for (i = 0; i < n; i = i + 1) {
StringSplit(config, ";"); // restore the outer parts...
pair = StringGetSplitPartAt(i); // ...and copy this one out
StringSplit(pair, "="); // now the cache holds key, value
UtilityPrint(StringFormat("{0} -> {1}", StringGetSplitPartAt(0), StringGetSplitPartAt(1)));
}

Último índice de: uma extensão de arquivo​

Não há LastIndexOf, então verifique cada posição e guarde a última correspondência.

file = "report.final.v2.pdf";
last = -1;
len = StringGetLength(file);
for (i = 0; i < len; i = i + 1) {
if (StringGetSubstring(file, i, 1) == ".") last = i;
}
if (last >= 0) {
ext = StringGetSubstring(file, last + 1, len - last - 1);
base = StringGetSubstring(file, 0, last);
UtilityPrint(StringFormat("base={0} ext={1}", base, ext)); // base=report.final.v2 ext=pdf
}

Ler um número que alguém digitou​

false o lê no formato regional do usuário (um usuário alemão digita 1.234,5). Os grupos de dígitos devem então seguir esse formato: para um usuário de português (Brasil), 1.234,5 é um número e 1.5 não. StringIsNumber detecta um texto que não é número, que StringToNumber sozinha transformaria em 0.

text = UIShowInputBox("Width in pixels:", "Resize", "800");
if (!StringIsNumber(text, false)) {
UIShowMessageBox("Not a number: " + text, "Resize", "OK", "Warning");
} else {
width = StringToNumber(text, false); // Integer 800, or a Real if they typed a fraction
shown = StringFromNumber(width * 1.5, 1, false); // "1,200.0" in en-US, "1.200,0" in de-DE
UtilityPrint("one and a half times that: " + shown);
}

Iniciar um programa, aguardar a janela dele e agir sobre ela​

WindowWaitFor verifica repetidamente até o tempo limite (no máximo 60 segundos) e retorna uma janela nula se nada corresponder. O padrão é uma expressão regular sobre o título, sem diferenciar maiúsculas de minúsculas; o título de um programa segue o idioma de exibição do Windows, então busque a parte que não muda.

ShellRun("notepad.exe");
w = WindowWaitFor("notepad$", 10000);
if (w) {
WindowSetActive(w);
KeyboardTypeText("Notes for today:\n");
WindowWaitClose(w, 60000); // carries on once the user closes it, or after a minute
UtilityPrint("Notepad is gone");
} else {
UtilityPrint("Notepad didn't open in 10 seconds");
}

Extrair um valor de um texto copiado com uma expressão regular​

Sintaxe PCRE2, diferenciando maiúsculas de minúsculas, a menos que o padrão comece com (?i), e com suporte a Unicode (\w corresponde a letras acentuadas). O grupo 0 é a correspondência inteira; uma barra invertida no padrão é escrita \\ dentro de uma cadeia do script. $1 em uma substituição é o grupo 1. As funções internas Window*Regex/Shell*Regex usam o mesmo mecanismo, sempre sem diferenciar maiúsculas de minúsculas.

text = ClipboardGetText();
if (StringRegexMatch(text, "(?i)order\\s*#?(\\d+)")) {
UtilityPrint("order number: " + StringRegexGetGroupAt(1));
} else {
UtilityPrint("no order number on the clipboard");
}
// every run of spaces, tabs and line breaks becomes one space; "#1234" becomes "order 1234"
text = StringRegexReplace(text, "\\s+", " ");
ClipboardSetText(StringRegexReplace(text, "#(\\d+)", "order $1"));

Preencher um número com zeros à esquerda​

Acrescente caracteres no início até que o Text tenha o comprimento desejado.

n = 7;
s = StringFormat("{0}", n, "");
for (s = s; StringGetLength(s) < 3; s = s) {
s = "0" + s;
}
UtilityPrint(s); // 007

Inverter um Text​

Percorra o Text de trás para frente, uma unidade UTF-16 por vez. Os caracteres fora do Plano Multilíngue Básico (a maioria dos emojis) ocupam duas unidades e sairiam divididos.

text = "Input.Observer";
rev = "";
for (i = StringGetLength(text) - 1; i >= 0; i = i - 1) {
rev = rev + StringGetSubstring(text, i, 1);
}
UtilityPrint(rev); // revresbO.tupnI

Contar as palavras da área de transferência​

Transforme tabulações e quebras de linha em espaços, divida nos espaços e conte as partes que não estão vazias.

text = ClipboardGetText();
text = StringReplace(text, "\n", " ");
text = StringReplace(text, "\t", " ");
n = StringSplit(text, " ");
words = 0;
for (i = 0; i < n; i = i + 1) {
if (StringTrim(StringGetSplitPartAt(i))) words = words + 1;
}
UtilityPrint(StringFormat("{0} words", words, ""));

Comparações sem diferenciar maiúsculas de minúsculas​

Converta os dois lados para minúsculas, porque todo operador e toda função interna de Text diferenciam maiúsculas de minúsculas.

title = WindowGetTitle(WindowGetActive());
if (StringContains(StringToLower(title), "visual studio")) {
UtilityPrint("In Visual Studio");
}
exe = WindowGetExecutableName(WindowGetActive());
if (StringToLower(exe) == "notepad.exe") UtilityPrint("In Notepad");

A ordenação de Text é ordinal​

< compara unidades de código UTF-16: toda letra ASCII maiúscula vem antes de toda minúscula.

UtilityPrint(StringFormat("\"apple\" < \"banana\" : {0}", "apple" < "banana", "")); // true
UtilityPrint(StringFormat("\"Zebra\" < \"apple\" : {0}", "Zebra" < "apple", "")); // true
UtilityPrint(StringFormat("\"apple\" < \"Banana\" : {0}", "apple" < "Banana", "")); // false
a = "apple"; b = "Banana";
UtilityPrint(StringFormat("case-folded : {0}", StringToLower(a) < StringToLower(b), "")); // true

Preencher um modelo e colá-lo​

StringReplace preenche os espaços reservados %NAME%. A área de transferência é salva e restaurada em volta da colagem.

template = "Hi %NAME%,\n\nThanks for the report on %APP%.\n";
text = StringReplace(template, "%NAME%", "Sam");
text = StringReplace(text, "%APP%", ContextGetApplicationName());
ClipboardSave();
ClipboardPasteReplacementText(text);
UtilityWait(150); // let the target app read the clipboard first
ClipboardRestore();

Juntar as linhas da área de transferência em uma só​

Divida em \n. StringTrim também remove o \r das quebras de linha do Windows, então isso funciona tanto com linhas que terminam em \r\n quanto só em \n.

n = StringSplit(ClipboardGetText(), "\n");
out = "";
for (i = 0; i < n; i = i + 1) {
part = StringTrim(StringGetSplitPartAt(i));
if (part) {
if (out) out = out + " ";
out = out + part;
}
}
ClipboardSetText(out);

Pesquisar na Web o texto selecionado​

ClipboardCopySelection aguarda a cópia chegar em vez de adivinhar. StringUrlEncode impede que &, #, espaços e letras acentuadas quebrem o endereço. Codifique somente o termo de pesquisa, nunca a URL inteira.

ClipboardSave();
term = StringTrim(ClipboardCopySelection(1000));
ClipboardRestore();
if (term) ShellRun("https://www.bing.com/search?q=" + StringUrlEncode(term));

Um gesto, várias opções​

UIShowMenu recebe um item por linha (- sozinho é um separador) e retorna o índice do item escolhido, contando a partir de 0 e ignorando os separadores, ou -1 quando o menu é fechado sem escolha. UIShowInputBox retorna "" em Cancelar.

choice = UIShowMenu("Maximize\nMinimize\n-\nRename window...");
w = ContextGetWindow();
if (choice == 0) WindowMaximize(w);
else if (choice == 1) WindowMinimize(w);
else if (choice == 2) {
title = UIShowInputBox("New title for this window:", "Rename", WindowGetTitle(w));
if (title) WindowSetTitle(w, title);
}

A data de hoje e um nome de arquivo com carimbo de data e hora​

DateTimeGetNow retorna texto ISO 8601. DateTimeFormat o escreve do jeito do usuário, ou como um FileStamp que ordena por data e hora e é seguro em um nome de arquivo.

now = DateTimeGetNow();
KeyboardTypeText(DateTimeFormat(now, DateTimeStyle.LongDate));
path = ShellExpandEnvironmentVariables("%USERPROFILE%\\Desktop\\note-") + DateTimeFormat(now, DateTimeStyle.FileStamp) + ".txt";
FileCreate(path, ClipboardGetText());
if (DateTimeGetPart(now, DateTimePart.Hour) >= 17) UtilityPrint("after hours");

Constantes nomeadas vs. números brutos​

Uma constante é compilada para o seu número, então estas chamadas são idênticas. O hexadecimal corresponde à documentação do Win32.

KeyboardPressKey(VirtualKey.VolumeMute);
KeyboardPressKey(0xAD); // the same key, as a hex VK code
KeyboardPressKey(173); // and in decimal
UtilityPrint(StringFormat("VirtualKey.A = {0}, MouseButton.Right = {1}", VirtualKey.A, MouseButton.Right));

Alternar a maximização da janela do gesto​

A ação de gesto mais comum. ContextGetWindow é a janela sobre a qual o gesto começou.

w = ContextGetWindow();
if (WindowIsMaximized(w)) WindowRestore(w); else WindowMaximize(w);

Fixar uma janela por cima​

WindowSetTopmost define explicitamente o "sempre visível", e WindowToggleTopmost o inverte. Uma propriedade de janela lembra qual estado este script escolheu.

w = ContextGetWindow();
pinned = WindowGetPropertyInteger(w, "io.pinned") == 1;
WindowSetTopmost(w, !pinned);
if (pinned) {
WindowRemoveProperty(w, "io.pinned");
} else {
WindowSetPropertyInteger(w, "io.pinned", 1);
ShellShowToast("Pinned on top", WindowGetTitle(w));
}

Alternar a transparência da janela em ciclo​

Varia a opacidade de 255 até 105 e de volta a 255. Uma janela que não é em camadas informa 255.

w = ContextGetWindow();
a = WindowGetAlpha(w) - 50;
if (a < 100) a = 255;
WindowSetAlpha(w, a);

Encaixar a janela ativa na metade esquerda do seu monitor​

Usa a área de trabalho (true) para que a janela não cubra a barra de tarefas.

w = WindowGetActive();
cx = WindowGetX(w) + WindowGetWidth(w) / 2;
cy = WindowGetY(w) + WindowGetHeight(w) / 2;
x = DisplayMonitorGetRectXFromPoint(cx, cy, true);
y = DisplayMonitorGetRectYFromPoint(cx, cy, true);
width = DisplayMonitorGetRectWidthFromPoint(cx, cy, true);
height = DisplayMonitorGetRectHeightFromPoint(cx, cy, true);
WindowRestore(w);
WindowMoveTo(w, x, y);
WindowResizeTo(w, width / 2, height);

Encaixar uma janela na célula de uma grade 3×2 sob o cursor​

As funções internas Region* dividem um retângulo em células, encontram a célula que contém um ponto e fornecem os seus limites.

mx = MouseGetCursorX();
my = MouseGetCursorY();
x = DisplayMonitorGetRectXFromPoint(mx, my, true);
y = DisplayMonitorGetRectYFromPoint(mx, my, true);
w = DisplayMonitorGetRectWidthFromPoint(mx, my, true);
h = DisplayMonitorGetRectHeightFromPoint(mx, my, true);

cell = RegionGetCellIndexAt(x, y, w, h, 3, 2, mx, my);
win = ContextGetWindow();
if (cell >= 0 && win) {
WindowRestore(win);
WindowMoveTo(win, RegionGetX(x, y, w, h, 3, 2, cell), RegionGetY(x, y, w, h, 3, 2, cell));
WindowResizeTo(win, RegionGetWidth(x, y, w, h, 3, 2, cell), RegionGetHeight(x, y, w, h, 3, 2, cell));
}

Jogar uma janela para o próximo monitor​

O segundo argumento move o mouse junto com a janela.

WindowSendToNextMonitor(ContextGetWindow(), true);

Listar as janelas de nível superior visíveis​

Enumerar e depois indexar, ignorando janelas ocultas, encobertas (cloaked) e sem título.

n = WindowGetAllTopLevel();
shown = 0;
for (i = 0; i < n; i = i + 1) {
w = WindowGetEnumeratedAt(i);
if (WindowIsVisible(w)) {
if (!WindowIsCloaked(w)) {
title = WindowGetTitle(w);
if (title) {
UtilityPrint(StringFormat("{0} [{1}]", title, WindowGetExecutableName(w)));
shown = shown + 1;
}
}
}
}
UtilityPrint(StringFormat("{0} of {1} windows", shown, n));

Minimizar todas as janelas de um aplicativo​

Compara o executável com uma expressão regular que não diferencia maiúsculas de minúsculas. Observe o \\.: um \. de expressão regular escrito dentro de uma cadeia do script.

n = WindowFindAllByExecutableRegex("notepad\\.exe$");
for (i = 0; i < n; i = i + 1) {
WindowMinimize(WindowGetEnumeratedAt(i));
}
UtilityPrint(StringFormat("Minimized {0} Notepad windows", n, ""));

Fechar janelas por padrão de título, após confirmação​

Uma expressão regular sobre os títulos, uma contagem na mensagem e a verificação de qual botão foi clicado.

n = WindowFindAllByTitleRegex("^Untitled - ");
if (n > 0) {
answer = UIShowMessageBox(StringFormat("Close {0} untitled window(s)?", n, ""),
"Tidy up", "YesNo", "Question");
if (answer == "Yes") {
for (i = 0; i < n; i = i + 1) WindowClose(WindowGetEnumeratedAt(i));
}
}

Lembrar e restaurar a posição de uma janela​

As propriedades de janela guardam Integers na própria janela, entre execuções, até que ela seja fechada ou o Input.Observer saia. Uma propriedade que nunca foi definida é lida como 0.

w = ContextGetWindow();
if (WindowGetPropertyInteger(w, "io.saved") == 1) {
WindowMoveTo(w, WindowGetPropertyInteger(w, "io.x"), WindowGetPropertyInteger(w, "io.y"));
WindowRemoveProperty(w, "io.saved");
WindowRemoveProperty(w, "io.x");
WindowRemoveProperty(w, "io.y");
} else {
WindowSetPropertyInteger(w, "io.x", WindowGetX(w));
WindowSetPropertyInteger(w, "io.y", WindowGetY(w));
WindowSetPropertyInteger(w, "io.saved", 1);
WindowCenterToScreen(w);
}

Inspecionar os controles filhos de uma janela​

Os filhos usam o mesmo cache de janelas que a enumeração de nível superior.

w = ContextGetWindow();
n = WindowGetAllChildren(w, true);
for (i = 0; i < n; i = i + 1) {
c = WindowGetEnumeratedAt(i);
UtilityPrint(StringFormat("{0}: {1}", WindowGetClassName(c), WindowGetTitle(c)));
}

Do processo à janela​

Enumere os ids de processo pelo nome do executável e depois encontre a janela de cada um.

n = ShellEnumerateProcessIdsByExecutableRegex("^explorer\\.exe$");
for (i = 0; i < n; i = i + 1) {
pid = ShellGetEnumeratedProcessIdAt(i);
w = WindowFromProcessId(pid);
UtilityPrint(StringFormat("pid {0}: {1}", pid, WindowGetTitle(w)));
}

Descrever o que está sob o cursor​

O controle sob um ponto, a sua janela de nível superior e o ponto convertido em coordenadas de cliente.

x = MouseGetCursorX();
y = MouseGetCursorY();
control = WindowControlFromPoint(x, y);
top = WindowGetRoot(control);
UtilityPrint(StringFormat("control class: {0}; window: {1}", WindowGetClassName(control), WindowGetTitle(top)));
UtilityPrint(StringFormat("client point: {0},{1}",
WindowMapScreenPointToClientX(top, x, y), WindowMapScreenPointToClientY(top, x, y)));

Esconder uma janela na bandeja​

Minimiza para a área de notificação. TrayRestoreAllWindows() traz todas de volta.

TrayMinimizeWindow(ContextGetWindow());

Tudo o que o contexto do gatilho sabe​

Associe isto a um gesto para ver o que o script dele pode ler.

UtilityPrint(StringFormat("action={0} gesture={1}", ContextGetActionName(), ContextGetGestureName()));
UtilityPrint(StringFormat("app={0} window={1}", ContextGetApplicationName(), WindowGetTitle(ContextGetWindow())));
UtilityPrint(StringFormat("box x={0} y={1}", ContextGetBoundingBoxX(), ContextGetBoundingBoxY())
+ StringFormat(" w={0} h={1}", ContextGetBoundingBoxWidth(), ContextGetBoundingBoxHeight()));
UtilityPrint(StringFormat("points={0} button={1}", ContextGetPointCount(), ContextGetStrokeButton()));

Para que lado o traço foi?​

Compare o primeiro e o último ponto e escolha o eixo predominante.

n = ContextGetPointCount();
if (n > 1) {
dx = ContextGetPointX(n - 1) - ContextGetPointX(0);
dy = ContextGetPointY(n - 1) - ContextGetPointY(0);
if (MathAbs(dx) > MathAbs(dy)) {
if (dx > 0) dir = "right"; else dir = "left";
} else {
if (dy > 0) dir = "down"; else dir = "up";
}
UtilityPrint("The stroke went " + dir);
}

Ramificar conforme o botão do traço​

ContextGetStrokeButton retorna um valor MouseButton.*, ou -1 fora de um gatilho de gesto ou de botão do mouse e para um gesto desenhado com a tecla de desenho.

b = ContextGetStrokeButton();
if (b == MouseButton.Secondary) {
WindowMinimize(ContextGetWindow());
} else if (b == MouseButton.Middle) {
WindowClose(ContextGetWindow());
} else if (b == -1) {
UtilityPrint("Not triggered by a mouse button");
}

Rolar sobre a barra de tarefas para mudar o volume​

Para o evento global Roda — vertical. ContextGetWheelDelta fica acima de 0 quando a roda gira para longe de você, e a classe de janela da barra de tarefas indica onde está o ponteiro.

// For the Wheel - vertical global event: over a taskbar, the wheel changes the volume.
cls = WindowGetClassName(ContextGetWindow());
if (cls == "Shell_TrayWnd" || cls == "Shell_SecondaryTrayWnd") {
if (ContextGetWheelDelta() > 0) {
KeyboardPressKey(VirtualKey.VolumeUp);
} else {
KeyboardPressKey(VirtualKey.VolumeDown);
}
}

Capturar a área que você circulou​

Salva o retângulo delimitador do gesto como PNG em Imagens.

path = ShellExpandEnvironmentVariables("%USERPROFILE%\\Pictures\\gesture-capture.png");
ok = CaptureSaveRegion(path, ContextGetBoundingBoxX(), ContextGetBoundingBoxY(),
ContextGetBoundingBoxWidth(), ContextGetBoundingBoxHeight());
if (ok) ShellShowToast("Captured", path);

Deixar passar um desenho não reconhecido​

Se um gesto foi desenhado sobre um aplicativo de desenho, reproduz o traço no aplicativo como um arrastar comum.

if (StringToLower(ContextGetApplicationName()) == "mspaint.exe") {
ContextRelayGesture();
}

Clicar em algum lugar e devolver o cursor​

Salve a posição do cursor em variáveis, clique e volte.

x = MouseGetCursorX();
y = MouseGetCursorY();
MouseClick(20, 20, MouseButton.Primary);
UtilityWait(50);
MouseMoveTo(x, y);

Clicar em um ponto dentro de uma janela​

As coordenadas de cliente continuam corretas onde quer que a janela tenha sido movida.

w = WindowFindByTitle("Calculator");
if (w) {
WindowSetActive(w);
MouseClickAtClientPoint(w, 40, 60, MouseButton.Primary);
}

Um arrastar por script​

Pressione, mova em etapas, solte. As funções internas separadas de pressionar, mover e soltar existem para isso.

x = MouseGetCursorX();
y = MouseGetCursorY();
MouseButtonDown(MouseButton.Primary);
for (i = 1; i <= 20; i = i + 1) {
MouseMoveTo(x + i * 10, y);
UtilityWait(10);
}
MouseButtonUp(MouseButton.Primary);

Rolar por entalhes​

Um entalhe da roda vale 120. Valores negativos rolam para baixo ou para a esquerda.

MouseScrollVertical(-3 * 120); // three notches down
MouseScrollHorizontal(120); // one notch right

Confinar o cursor a uma janela por 5 segundos​

MouseLockToRect vale para todo o sistema até MouseUnlock, então sempre use os dois em par.

w = ContextGetWindow();
MouseLockToRect(WindowGetX(w), WindowGetY(w), WindowGetWidth(w), WindowGetHeight(w));
UtilityWait(5000);
MouseUnlock();

Combinações de teclas​

Prefixos de modificadores ^ Ctrl, + Shift, % Alt e @ Win, depois uma tecla.

KeyboardPressKeyCombo("^c"); // Ctrl+C
KeyboardPressKeyCombo("^+{ESC}"); // Ctrl+Shift+Esc
KeyboardPressKeyCombo("@{LEFT}"); // Win+Left
KeyboardPressKeyCombo("%{F4}"); // Alt+F4

Digitar uma assinatura​

KeyboardTypeText digita caracteres e envia cada quebra de linha do texto como um pressionamento real da tecla Enter. Entre duas chamadas, pressione Enter sozinho com KeyboardPressKeyCombo.

KeyboardTypeText("Best regards,");
KeyboardPressKeyCombo("{ENTER}");
KeyboardTypeText("Sam");

Shift+clique​

Mantenha uma tecla pressionada em volta de uma ação do mouse e solte-a no mesmo script. Uma tecla deixada pressionada continua pressionada.

KeyboardKeyDown(VirtualKey.ShiftKey);
MouseClick(MouseGetCursorX(), MouseGetCursorY(), MouseButton.Primary);
KeyboardKeyUp(VirtualKey.ShiftKey);

Teclas de mídia​

Envie teclas de mídia e de volume pelos seus nomes em VirtualKey.

KeyboardPressKey(VirtualKey.MediaPlayPause);
UtilityWait(200);
KeyboardPressKey(VirtualKey.MediaNextTrack);

Mudar o comportamento enquanto Ctrl está pressionada​

Verifique o estado atual de uma tecla para dar dois significados a um mesmo gesto.

w = ContextGetWindow();
if (KeyboardIsKeyDown(VirtualKey.ControlKey)) {
WindowClose(w);
} else {
WindowMinimize(w);
}

Qual layout de teclado está ativo​

KeyboardGetLayout dá o id de idioma do layout, e KeyboardGetLayoutName, o mesmo idioma como nome de cultura. Consulte a janela ativa: o layout pertence à janela, não à área de trabalho inteira. Em uma janela de console, a resposta pode ser o layout padrão em vez do que você escolheu.

w = WindowGetActive();
UtilityPrint(StringFormat("Typing goes to a {0} layout (language id {1})",
KeyboardGetLayoutName(w), KeyboardGetLayout(w)));
if (KeyboardGetLayout(w) == 0x0804) {
UtilityPrint("Chinese (Simplified) is active");
}

Mostrar o Caps Lock e o layout de teclado na tela​

Um temporizador verifica quatro vezes por segundo e mantém uma mensagem na tela aberta enquanto o Caps Lock está ativado ou um layout de chinês (simplificado) está ativo. O id da mensagem fica no Storage entre as execuções do temporizador, e a mensagem só muda quando o texto dela muda.

// The body of a snippet named "Indicator", run by a timer that the Config loaded
// global event starts:
// TimerCreate("indicator", 0, 250, 0, SnippetGetScript("Indicator"));
msg = "";
if (KeyboardIsKeyToggled(VirtualKey.CapsLock)) msg = "Caps Lock";
if (KeyboardGetLayoutName(WindowGetActive()) == "zh-CN") {
if (msg != "") msg = msg + " - ";
msg = msg + "Chinese (Simplified)";
}

// A timer run has fresh variables, so the open panel's id lives in Storage.
id = StorageGetValue("indicator.id");
shown = StorageGetValue("indicator.text");
if (msg == "") {
if (id != 0) {
UICloseDisplayMessage(id);
StorageSetValue("indicator.id", 0);
StorageSetValue("indicator.text", "");
}
} else {
if (id == 0) {
// Duration 0: the panel stays until UICloseDisplayMessage closes it.
id = UIShowDisplayMessage("", msg, 0, 1.0, Location.BottomCenter,
"Segoe UI", 12, true, false, "Segoe UI", 20, false, false,
"black", "#EEEEEE", 10, false, TextAlign.Center, TextAlign.Center);
StorageSetValue("indicator.id", id);
StorageSetValue("indicator.text", msg);
} else {
if (msg != shown) {
UIUpdateDisplayMessage(id, "", msg, 0, 1.0, Location.BottomCenter,
"Segoe UI", 12, true, false, "Segoe UI", 20, false, false,
"black", "#EEEEEE", 10, false, TextAlign.Center, TextAlign.Center);
StorageSetValue("indicator.text", msg);
}
}
}

Converter o texto selecionado em maiúsculas​

Copie a seleção, altere-a, cole-a de volta e restaure o que havia antes na área de transferência.

ClipboardSave();
ClipboardClear();
KeyboardPressKeyCombo("^c");
UtilityWait(100);
text = ClipboardGetText();
if (text) {
ClipboardPasteReplacementText(StringToUpper(text));
UtilityWait(100);
}
ClipboardRestore();

Copie a seleção e abra uma URL de pesquisa. Os espaços viram +. Para codificar também todos os outros caracteres, use StringUrlEncode, como faz Pesquisar na Web o texto selecionado.

ClipboardSave();
KeyboardPressKeyCombo("^c");
UtilityWait(100);
q = StringTrim(ClipboardGetText());
ClipboardRestore();
if (q) {
ShellRun("https://www.bing.com/search?q=" + StringReplace(q, " ", "+"));
}

Salvar uma imagem copiada em um arquivo​

Grava a imagem da área de transferência em disco e informa o resultado.

path = ShellExpandEnvironmentVariables("%USERPROFILE%\\Desktop\\clipboard.png");
if (ClipboardSaveImage(path)) ShellShowToast("Saved", path);
else UtilityPrint("No image on the clipboard");

Acrescentar a um arquivo de log​

Cria o arquivo com um cabeçalho na primeira vez e depois acrescenta uma linha por execução.

log = ShellExpandEnvironmentVariables("%TEMP%\\input-observer-gestures.log");
if (!FileExists(log)) FileCreate(log, "gesture\tapplication\n");
FileAppendText(log, StringFormat("{0}\t{1}\n", ContextGetGestureName(), ContextGetApplicationName()));

Ler um arquivo e contar as suas linhas​

FileReadText retorna o arquivo inteiro como Text, que depois é dividido em \n.

path = "C:\\Windows\\System32\\drivers\\etc\\hosts";
text = FileReadText(path);
n = StringSplit(text, "\n");
comments = 0;
for (i = 0; i < n; i = i + 1) {
if (StringStartsWith(StringTrim(StringGetSplitPartAt(i)), "#")) comments = comments + 1;
}
UtilityPrint(StringFormat("{0} lines, {1} comments", n, comments));
UtilityPrint(StringFormat("{0} bytes, modified {1}", FileGetSize(path), FileGetModifiedDate(path)));

Contar os tipos de arquivo em uma pasta​

Enumera uma pasta sem recursão e conta as correspondências sem diferenciar maiúsculas de minúsculas.

folder = ShellExpandEnvironmentVariables("%USERPROFILE%\\Downloads");
n = FolderEnumerateAll(folder, false);
pdf = 0; zip = 0;
for (i = 0; i < n; i = i + 1) {
p = StringToLower(FolderGetEnumeratedPathAt(i));
if (StringEndsWith(p, ".pdf")) pdf = pdf + 1;
else if (StringEndsWith(p, ".zip")) zip = zip + 1;
}
UtilityPrint(StringFormat("{0} PDFs, {1} ZIPs", pdf, zip) + StringFormat(" of {0} entries", n, ""));

Fazer backup de um arquivo antes de editá-lo​

Copia com substituição e depois troca o conteúdo.

path = ShellExpandEnvironmentVariables("%USERPROFILE%\\notes.txt");
if (FileExists(path)) {
FileCopy(path, path + ".bak", true);
FileEditText(path, StringToUpper(FileReadText(path)));
}

Monitorar uma pasta​

Combine sinalizadores FileNotify com |. O script do monitoramento é Text, então as aspas internas são escapadas. Ele lê o que aconteceu por meio de ContextGetWatch*.

FolderWatchCreate("downloads",
ShellExpandEnvironmentVariables("%USERPROFILE%\\Downloads"),
false,
FileNotify.FileName | FileNotify.LastWrite,
"UtilityPrint(ContextGetWatchAction() + \": \" + ContextGetWatchPath());");
// later: FolderWatchDelete("downloads");

Um temporizador repetitivo que conta​

O script de um temporizador tem as suas próprias variáveis, então o Storage leva a contagem de um disparo para o outro. Dispara 5 vezes, com um segundo de intervalo.

StorageSetValue("ticks", 0);
TimerCreate("counter", 1000, 1000, 5,
"t = StorageGetValue(\"ticks\") + 1; StorageSetValue(\"ticks\", t); UtilityPrint(StringFormat(\"tick {0}\", t, \"\"));");

Script de temporizador a partir de um snippet, sem escapes​

Mantenha um script de temporizador longo em um snippet e passe o texto dele, para que não haja aspas aninhadas para escapar.

// Fires once, 10 minutes from now (repeat count 1).
TimerCreate("stretch-reminder", 600000, 1000, 1, SnippetGetScript("Stretch reminder"));

Listar e parar temporizadores​

Enumere os temporizadores nomeados e exclua um ou todos eles.

n = TimerEnumerateAll();
for (i = 0; i < n; i = i + 1) UtilityPrint(TimerGetEnumeratedNameAt(i));
TimerDelete("counter");
// TimerDeleteAll();

Uma alternância que sobrevive entre execuções​

StorageGetValue de uma chave que nunca foi definida é Integer 0, que é falso, então a primeira execução ativa o modo. O valor dura até o Input.Observer ser encerrado; as funções internas Persistent mantêm um valor entre reinicializações.

on = !StorageGetValue("quietMode");
StorageSetValue("quietMode", on);
MultimediaSetMute(AudioEndpoint.Playback, on);
if (on) ShellShowToast("Quiet mode", "On"); else ShellShowToast("Quiet mode", "Off");

Um contador que sobrevive a uma reinicialização​

As funções internas Storage*Persistent* guardam os valores em storage.toml, ao lado da configuração, então eles continuam lá depois que o Input.Observer é reiniciado. É texto simples, nunca criptografado: não guarde senhas ali. Windows não podem ser guardados; um identificador não significa nada depois de uma reinicialização. Se storage.toml existir mas não puder ser lido quando o Input.Observer iniciar, StorageSetPersistentValue retorna false: o valor é mantido só até o Input.Observer sair, e nada é salvo até a próxima inicialização.

n = StorageGetPersistentValue("gestures.used") + 1; // 0 the first time ever
StorageSetPersistentValue("gestures.used", n);
UtilityPrint(StringFormat("{0} gestures since this counter started", n, ""));

Uma lista guardada no Storage​

Não há arrays, mas chaves numeradas montadas com StringFormat funcionam como um.

count = StorageGetValue("recent.count");
StorageSetValue(StringFormat("recent.{0}", count, ""), WindowGetTitle(ContextGetWindow()));
StorageSetValue("recent.count", count + 1);

for (i = 0; i <= count; i = i + 1) {
UtilityPrint(StorageGetValue(StringFormat("recent.{0}", i, "")));
}

Deixar só uma ação executar um trecho por vez​

Um bloqueio nomeado impede que duas execuções sobrepostas se intercalem. Verifique o resultado com LockResult e libere o bloqueio quando terminar.

r = UtilityLockAcquire("clipboard-work", 5000);
if (r == LockResult.Acquired) {
ClipboardSave();
// ...work that must not overlap another run...
ClipboardRestore();
UtilityLockRelease("clipboard-work");
} else {
UtilityPrint("Another action is busy with the clipboard");
}

Fazer uma pergunta​

Os botões e o ícone são nomes em Text. O resultado é o nome do botão clicado.

answer = UIShowMessageBox("Save the layout before closing?", "Input.Observer", "YesNoCancel", "Question");
if (answer == "Yes") {
UtilityPrint("saving");
} else if (answer == "No") {
UtilityPrint("discarding");
} else {
UtilityPrint("cancelled");
}

Aumentar o volume com uma indicação na tela​

O volume é um Real de 0.0 a 1.0. UIShowDisplayMessage recebe 19 argumentos posicionais.

v = MathMin(MultimediaGetVolume(AudioEndpoint.Playback) + 0.05, 1.0);
MultimediaSetVolume(AudioEndpoint.Playback, v);
UIShowDisplayMessage(
"Volume", StringFormat("{0}%", MathRound(v * 100), ""),
1200, // durationMs
0.9, // opacity (Real)
Location.BottomCenter, // or a "x,y" Text point
"Segoe UI", 14, true, false, // title font, size, bold, italic
"Segoe UI", 12, false, false, // message font, size, bold, italic
"#1F1F1F", "#F7F7F5", // fore / back color: name, #RRGGBB or "R,G,B"
12, // padding
false, // usePrimaryScreen
TextAlign.Center, TextAlign.Center);

Uma mensagem na tela atualizada ao vivo​

Guarde o id da sessão e passe-o para UIUpdateDisplayMessage com os mesmos 19 argumentos.

id = UIShowDisplayMessage("Working", "0%", 10000, 0.95, Location.TopRight,
"Segoe UI", 12, true, false, "Segoe UI", 11, false, false,
"black", "255,255,255", 10, true, TextAlign.Left, TextAlign.Left);
for (p = 0; p <= 100; p = p + 20) {
UIUpdateDisplayMessage(id, "Working", StringFormat("{0}%", p, ""), 10000, 0.95, Location.TopRight,
"Segoe UI", 12, true, false, "Segoe UI", 11, false, false,
"black", "255,255,255", 10, true, TextAlign.Left, TextAlign.Left);
UtilityWait(400);
}
UICloseDisplayMessage(id);

Uma notificação do Windows​

Um título e uma mensagem, mostrados como notificação do sistema.

ShellShowToast("Input.Observer", StringFormat("Profile: {0}", GestureProfileGetActiveId(), ""));

Alternar o mudo do microfone​

O ponto de extremidade Capture é o dispositivo de gravação padrão.

MultimediaToggleMute(AudioEndpoint.Capture);
if (MultimediaIsMuted(AudioEndpoint.Capture)) ShellShowToast("Microphone", "Muted");
else ShellShowToast("Microphone", "Live");

Tocar um som​

Arquivos WAV e MP3 a partir de um caminho.

MultimediaPlayWavFile("C:\\Windows\\Media\\chimes.wav");

Iniciar um aplicativo ou alternar para ele​

Ativa o aplicativo se ele já estiver em execução; caso contrário, inicia-o.

ShellRunOrActivate("notepad.exe");

Executar um programa com um verbo e um estilo de janela​

O verbo é uma constante ShellVerb ou qualquer verbo como Text. O estilo de janela é uma constante WindowStyle.

ShellRunProgram("notepad.exe", "C:\\Temp\\todo.txt", ShellVerb.Open, WindowStyle.Maximized, false);
ShellRunProgram("C:\\Temp\\report.pdf", "", "print", WindowStyle.Hidden, false); // Text verb

Executar e aguardar o término​

Com waitForExit definido como true, a thread do script fica bloqueada até o programa ser fechado. Enquanto isso, a entrada continua fluindo. Parar todas as ações encerra a espera: o programa continua em execução e a chamada retorna false.

ShellRunProgram("notepad.exe", "", ShellVerb.Open, WindowStyle.Normal, true);
ShellShowToast("Notepad", "was closed");

Expandir variáveis de ambiente​

Monta um caminho que funciona no computador de qualquer usuário.

UtilityPrint(ShellExpandEnvironmentVariables("%APPDATA%\\Input.Observer"));
UtilityPrint(ShellExpandEnvironmentVariables("%COMPUTERNAME% / %USERNAME%"));

Passar o trabalho ao AutoHotkey​

Executa código AutoHotkey fora do processo, aguarda o fim e retorna o código de saída dele, ou -1 se o AutoHotkey não estiver configurado. AutoHotkeyStartScript inicia código que continua em execução, como teclas de atalho, e retorna na hora.

rc = AutoHotkeyExecuteScript("SoundBeep 750, 200");
if (rc == -1) UtilityPrint("AutoHotkey isn't set up");

Listar os monitores​

Nome, limites completos, área de trabalho e DPI de cada monitor, por índice.

n = DisplayMonitorEnumerateAll();
for (i = 0; i < n; i = i + 1) {
UtilityPrint(StringFormat("#{0} {1}", i, DisplayMonitorGetEnumeratedFriendlyNameAt(i)));
UtilityPrint(StringFormat(" bounds {0} x {1}", DisplayMonitorGetEnumeratedWidthAt(i, false), DisplayMonitorGetEnumeratedHeightAt(i, false))
+ StringFormat(", work area {0} x {1}", DisplayMonitorGetEnumeratedWidthAt(i, true), DisplayMonitorGetEnumeratedHeightAt(i, true))
+ StringFormat(", {0} dpi", DisplayMonitorGetEnumeratedDpiAt(i), ""));
}

Enviar uma janela para um monitor específico​

Pelo índice da enumeração, recorrendo à próxima tela quando esse monitor não existe.

w = ContextGetWindow();
if (DisplayMonitorEnumerateAll() > 1) {
WindowSendToMonitorIndex(w, 1, false);
} else {
WindowSendToNextMonitor(w, false);
}

Passar para o próximo perfil de gestos​

Encontre o índice do perfil ativo, some um e volte ao início com o padrão do resto.

n = GestureProfileEnumerateAll();
if (n > 0) {
active = GestureProfileGetActiveId();
next = 0;
for (i = 0; i < n; i = i + 1) {
if (GestureProfileGetEnumeratedIdAt(i) == active) next = i + 1;
}
next = next - (next / n) * n; // next % n
GestureProfileSwitch(GestureProfileGetEnumeratedIdAt(next));
ShellShowToast("Gesture profile", GestureProfileGetEnumeratedNameAt(next));
}

Estado do mecanismo​

Verifique se o mecanismo está desativado ou no Modo de segurança e depois pause-o. Reative-o pelo menu da bandeja.

UtilityPrint(StringFormat("disabled={0} safeMode={1}", EngineIsDisabled(), EngineIsSafeMode()));
if (!EngineIsDisabled()) {
EngineDisable();
ShellShowToast("Input.Observer", "Paused. Re-enable it from the tray menu.");
}

Deixar passar o próximo arrastar com o botão direito​

Ignora a captura de gesto uma vez, para que o próximo arrastar com o botão direito vá para o aplicativo.

EngineDisableNextGesture();

Snippets como funções reutilizáveis​

Passe argumentos e resultados pelo Storage. O snippet é executado até o fim antes da próxima linha.

// Snippet "Tile window" reads tile.index and positions ContextGetWindow() accordingly.
StorageSetValue("tile.index", 2);
SnippetExecuteScript("Tile window");
UtilityPrint(StringFormat("snippet reported: {0}", StorageGetValue("tile.result"), ""));

Comunicar-se com um plug-in​

Envia um comando Text a um plug-in conectado e aguarda a resposta Text dele até o tempo limite.

reply = PluginSendMessage("MyRenderer", "theme dark", 2000);
UtilityPrint("Plugin replied: " + reply);

Fazer uma pergunta a um dispositivo serial​

Abra a porta, escreva uma linha, aguarde a resposta por até 2 segundos e feche a porta. A paridade e os bits de parada são constantes.

if (SerialOpenPort("COM3", 9600, SerialParity.None, 8, SerialStopBits.One, "\n")) {
SerialWriteTextLine("COM3", "PING", 9600);
reply = SerialGetTextLine("COM3", 2000, 9600);
SerialClosePort("COM3");
if (reply) UtilityPrint("Device: " + reply); else UtilityPrint("No reply");
}

Mapear os botões de um dispositivo serial para teclas de mídia​

Um monitor executa o seu script para cada linha recebida. ContextGetSerialTextLine é a linha.

SerialMonitorCreate("pad", "COM3", 115200, SerialParity.None, 8, SerialStopBits.One, "\n",
"line = StringTrim(ContextGetSerialTextLine()); if (line == \"B1\") KeyboardPressKey(VirtualKey.MediaPlayPause); else if (line == \"B2\") KeyboardPressKey(VirtualKey.MediaNextTrack);");

Listar as portas COM​

Quais portas existem agora, como a que um Arduino acabou de receber ao ser conectado. Consulte Dispositivos seriais e Arduino.

n = SerialPortEnumerateAll();
if (n == 0) UtilityPrint("No COM ports. Is the board plugged in?");
for (i = 0; i < n; i = i + 1) {
UtilityPrint(SerialGetEnumeratedPortAt(i));
}

Manter a porta de um Arduino aberta e enviar comandos a ele​

Abra a porta uma vez, para que uma placa que reinicia quando a sua porta é aberta não perca comandos, e depois envie uma linha e leia a resposta.

// Load global event: open the port once, at the sketch's speed. An Uno or Nano
// restarts every time its port opens, so a port opened per command would lose
// the command while the board boots.
if (!SerialOpenPort("COM4", 115200, SerialParity.None, 8, SerialStopBits.One, "")) {
UtilityPrint("COM4 isn't available: unplugged, or open in the Arduino IDE's Serial Monitor?");
}

// Any gesture or hotkey: send a command line and read the board's reply.
// (The sketch reads a line with Serial.readStringUntil('\n') and answers OK.)
if (SerialWriteTextLine("COM4", "LED 255 0 0", 115200)) {
reply = SerialGetTextLine("COM4", 1000, 115200);
if (reply != "OK") UtilityPrint(StringFormat("Board said: {0}", reply, ""));
}

Transformar um botão giratório de Arduino em controle de volume​

Uma leitura de potenciômetro de 0 a 1023 em cada linha vira o volume de reprodução.

// Arduino side: a potentiometer on A0, one reading per line.
// void setup() { Serial.begin(115200); }
// void loop() { Serial.println(analogRead(A0)); delay(50); }
// Empty text as the terminator means CR LF, which Serial.println sends.
SerialMonitorCreate("knob", "COM4", 115200, SerialParity.None, 8, SerialStopBits.One, "",
"line = ContextGetSerialTextLine(); if (StringIsNumber(line, true)) MultimediaSetVolume(AudioEndpoint.Playback, StringToNumber(line, true) / 1023.0);");