Change syntax and add powershell support

This commit is contained in:
Stone_Red
2022-12-22 16:51:09 +01:00
parent 48af2275a7
commit 71451f22b2
3 changed files with 88 additions and 69 deletions
+4 -1
View File
@@ -2,7 +2,7 @@
<PropertyGroup> <PropertyGroup>
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework> <TargetFramework>net7.0-windows</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<UseWPF>true</UseWPF> <UseWPF>true</UseWPF>
<AssemblyVersion>0.0.0.2</AssemblyVersion> <AssemblyVersion>0.0.0.2</AssemblyVersion>
@@ -12,6 +12,9 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="InputSimulator" Version="1.0.4" /> <PackageReference Include="InputSimulator" Version="1.0.4" />
<PackageReference Include="Microsoft.PowerShell.SDK" Version="7.0.0" />
<PackageReference Include="System.Management.Automation" Version="7.0.0" />
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="6.0.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+1 -1
View File
@@ -24,7 +24,7 @@
<DockPanel Grid.Column="0"> <DockPanel Grid.Column="0">
<Label DockPanel.Dock="Top" Content="Static Commands:" /> <Label DockPanel.Dock="Top" Content="Static Commands:" />
<TextBox DockPanel.Dock="Top" x:Name="staticCommandsTextBox" TextChanged="StaticCommandsTextBox_TextChanged" TextWrapping="Wrap" AcceptsReturn="True" VerticalAlignment="Stretch" /> <TextBox DockPanel.Dock="Top" x:Name="commandsTextBox" TextChanged="StaticCommandsTextBox_TextChanged" TextWrapping="Wrap" AcceptsReturn="True" VerticalAlignment="Stretch" />
</DockPanel> </DockPanel>
<DockPanel Grid.Column="1"> <DockPanel Grid.Column="1">
+83 -67
View File
@@ -1,9 +1,10 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Data;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Windows; using System.Windows;
using System.Windows.Media; using System.Windows.Media;
@@ -17,33 +18,38 @@ namespace ClipCMD;
/// </summary> /// </summary>
public partial class MainWindow : Window public partial class MainWindow : Window
{ {
private readonly Dictionary<string, Func<string, string>> stuffToReplace = new() private readonly Dictionary<string, string> commands = new Dictionary<string, string>();
{
{ "time", (_) => DateTime.Now.ToShortTimeString() }, private readonly string cmdPath;
{ "date", (_) => DateTime.Now.ToShortDateString() }, private readonly string fixPath;
{ "calc", (math) => new DataTable().Compute(math.Trim()[4..], null)?.ToString() ?? string.Empty },
};
public MainWindow() public MainWindow()
{ {
InitializeComponent(); InitializeComponent();
string filePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
string workPath = Path.GetDirectoryName(filePath) ?? "/";
cmdPath = Path.Combine(workPath, "cmd.txt");
fixPath = Path.Combine(workPath, "fix.txt");
} }
protected override void OnSourceInitialized(EventArgs e) protected override void OnSourceInitialized(EventArgs e)
{ {
base.OnSourceInitialized(e); base.OnSourceInitialized(e);
// Initialize the clipboard now that we have a window soruce to use // Initialize the clipboard now that we have a window source to use
ClipboardManager windowClipboardManager = new ClipboardManager(this); ClipboardManager windowClipboardManager = new ClipboardManager(this);
windowClipboardManager.ClipboardChanged += ClipboardManager_ClipboardChanged; windowClipboardManager.ClipboardChanged += ClipboardManager_ClipboardChanged;
if (File.Exists("cmd.txt")) if (File.Exists(cmdPath))
{ {
staticCommandsTextBox.Text = File.ReadAllText("cmd.txt"); commandsTextBox.Text = File.ReadAllText(cmdPath);
} }
if (File.Exists("fix.txt"))
if (File.Exists(fixPath))
{ {
string[] lines = File.ReadAllLines("fix.txt"); string[] lines = File.ReadAllLines(fixPath);
if (lines.Length == 2) if (lines.Length == 2)
{ {
prefixTextBox.Text = lines[0]; prefixTextBox.Text = lines[0];
@@ -51,7 +57,7 @@ public partial class MainWindow : Window
} }
else else
{ {
File.Delete("fix.txt"); File.Delete(fixPath);
} }
} }
} }
@@ -60,70 +66,50 @@ public partial class MainWindow : Window
private void ClipboardManager_ClipboardChanged(object? sender, EventArgs e) private void ClipboardManager_ClipboardChanged(object? sender, EventArgs e)
{ {
if (!Clipboard.ContainsText() || oldData is not null && Clipboard.IsCurrent(oldData)) if (!Clipboard.ContainsText() || (oldData is not null && Clipboard.IsCurrent(oldData)))
{ {
return; return;
} }
try try
{ {
bool result = SafeRepeat.Start(() => Clipboard.GetText().Trim(), 100, out string? text); bool result = SafeRepeat.Start(() => Clipboard.GetText().Trim(), 100, out string? clipboardText);
if (!result || text is null) if (!result || clipboardText is null)
{ {
return; return;
} }
if (!text.StartsWith(prefixTextBox.Text) || !text.EndsWith(suffixTextBox.Text)) if (!clipboardText.StartsWith(prefixTextBox.Text) || !clipboardText.EndsWith(suffixTextBox.Text))
{ {
oldData = Clipboard.GetDataObject(); oldData = Clipboard.GetDataObject();
return; return;
} }
text = text[prefixTextBox.Text.Length..^suffixTextBox.Text.Length].Trim(); clipboardText = clipboardText[prefixTextBox.Text.Length..^suffixTextBox.Text.Length].Trim();
Func<string, string>? func = stuffToReplace.FirstOrDefault(v => text.StartsWith(v.Key)).Value; if (!commands.TryGetValue(clipboardText, out string? script))
string logText = text;
string? outText;
if (func is null)
{ {
string[]? parts = staticCommandsTextBox.Text.Split('\n').FirstOrDefault(l => oldData = Clipboard.GetDataObject();
{ return;
if (string.IsNullOrWhiteSpace(l))
{
return false;
}
string? startText = l.Trim().Split('>').FirstOrDefault()?.Trim();
return startText is not null && text == startText;
})?.Split('>');
if (parts?.Length == 2)
{
outText = parts[1];
}
else
{
oldData = Clipboard.GetDataObject();
return;
}
}
else
{
outText = func(text);
} }
outText = outText.Trim(); PowerShell ps = PowerShell.Create().AddScript(script);
logListBox.Items.Insert(0, $"{logText} > {outText}"); StringBuilder outText = new StringBuilder();
Clipboard.SetDataObject(outText); foreach (PSObject commandResult in ps.Invoke())
{
_ = outText.AppendLine(commandResult.ToString());
}
logListBox.Items.Insert(0, $"{clipboardText} > {outText.ToString().TrimEnd()}");
Clipboard.SetText(outText.ToString().TrimEnd());
oldData = Clipboard.GetDataObject(); oldData = Clipboard.GetDataObject();
InputSimulator inputSimulator = new InputSimulator(); InputSimulator inputSimulator = new InputSimulator();
inputSimulator.Keyboard.KeyPress(new[] { VirtualKeyCode.CONTROL, VirtualKeyCode.VK_V }); _ = inputSimulator.Keyboard.ModifiedKeyStroke(new[] { VirtualKeyCode.CONTROL }, new[] { VirtualKeyCode.VK_V });
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -134,25 +120,55 @@ public partial class MainWindow : Window
private void StaticCommandsTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e) private void StaticCommandsTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{ {
bool isError = false; //TODO parse commands
foreach (string line in staticCommandsTextBox.Text.Split('\n'))
string[] lines = commandsTextBox.Text.Split('\n').Append("[#END#]").ToArray();
string commandNames = string.Empty;
StringBuilder script = new StringBuilder();
commandsTextBox.Foreground = Brushes.Black;
commands.Clear();
foreach (string l in lines)
{ {
if (!string.IsNullOrWhiteSpace(line) && line.Count(c => c == '>') != 1) string line = l.Trim('\n', '\r');
if (line.StartsWith('[') && line.EndsWith(']'))
{ {
isError = true; if (!string.IsNullOrEmpty(commandNames))
{
foreach (string commandName in commandNames.Split(','))
{
if (!string.IsNullOrWhiteSpace(commandName) && commands.TryAdd(commandName.Trim(), script.ToString()))
{
commandsTextBox.Foreground = Brushes.Black;
}
else
{
commandsTextBox.Foreground = Brushes.Red;
return;
}
}
}
commandNames = line.Trim()[1..^1].Trim();
script = new StringBuilder();
}
else if (!string.IsNullOrEmpty(commandNames))
{
if (!string.IsNullOrWhiteSpace(line))
{
_ = script.AppendLine(line);
}
}
else
{
commandsTextBox.Foreground = Brushes.Red;
return;
} }
} }
if (isError) File.WriteAllText(cmdPath, commandsTextBox.Text);
{
staticCommandsTextBox.Foreground = Brushes.Red;
}
else
{
staticCommandsTextBox.Foreground = Brushes.Black;
stuffToReplace["list"] = (_) => string.Join(", ", staticCommandsTextBox.Text.Split('\n').Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Split('>').FirstOrDefault()?.Trim()));
File.WriteAllText("cmd.txt", staticCommandsTextBox.Text);
}
} }
private void FixTextBox_TextChanged(object sender, System.Windows.Input.KeyEventArgs e) private void FixTextBox_TextChanged(object sender, System.Windows.Input.KeyEventArgs e)
@@ -162,6 +178,6 @@ public partial class MainWindow : Window
return; return;
} }
File.WriteAllLines("fix.txt", new[] { prefixTextBox.Text, suffixTextBox.Text }); File.WriteAllLines(fixPath, new[] { prefixTextBox.Text, suffixTextBox.Text });
} }
} }