Add AutoType option and rework setting storeage

This commit is contained in:
Stone_Red
2023-06-06 19:08:34 +02:00
parent 6a8414c0a9
commit 4f75699850
5 changed files with 324 additions and 95 deletions
+35
View File
@@ -0,0 +1,35 @@
using System;
using System.Windows;
using System.Windows.Data;
namespace ClipCMD;
public class EnumBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (parameter is not string parameterString)
{
return DependencyProperty.UnsetValue;
}
if (!Enum.IsDefined(value.GetType(), value))
{
return DependencyProperty.UnsetValue;
}
object parameterValue = Enum.Parse(value.GetType(), parameterString);
return parameterValue.Equals(value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (parameter is not string parameterString)
{
return DependencyProperty.UnsetValue;
}
return Enum.Parse(targetType, parameterString);
}
}
+48 -14
View File
@@ -5,18 +5,52 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ClipCMD"
mc:Ignorable="d"
d:DataContext ="{d:DesignInstance {x:Type local:MainWindow}, IsDesignTimeCreatable=True}"
Title="ClipCMD" Height="450" Width="800"
Closing="OnClose" StateChanged="OnStateChanged" Icon="logo.ico">
<DockPanel>
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal">
<Label Content="Prefix:" Width="45" />
<TextBox x:Name="prefixTextBox" KeyUp="FixTextBox_TextChanged" Text="_" />
</StackPanel>
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal">
<Label Content="Suffix:" Width="45" />
<TextBox x:Name="suffixTextBox" KeyUp="FixTextBox_TextChanged" Text="_" />
</StackPanel>
<Window.Resources>
<local:EnumBooleanConverter x:Key="EnumBooleanConverter" />
</Window.Resources>
<DockPanel>
<Grid DockPanel.Dock="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0">
<StackPanel Orientation="Horizontal">
<Label Content="Prefix:" Width="45" />
<TextBox Text="{Binding Settings.Prefix, UpdateSourceTrigger=PropertyChanged}" MinWidth="50" Height="20" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="Suffix:" Width="45" />
<TextBox Text="{Binding Settings.Suffix,UpdateSourceTrigger=PropertyChanged}" MinWidth="50" Height="20" />
</StackPanel>
</StackPanel>
<StackPanel Grid.Column="1" Background="LightBlue" HorizontalAlignment="Right" Margin="10">
<Label Margin="0" Padding="0">Mode:</Label>
<StackPanel Orientation="Horizontal">
<RadioButton Content="ClipBoard" GroupName="Mode" IsChecked="{Binding Settings.Mode, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=ClipBoard}" Margin="0,0,10,0" />
<StackPanel Orientation="Horizontal" IsEnabled="{Binding Settings.Mode, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=ClipBoard}">
<CheckBox Content="AutoPaste" IsChecked="{Binding Settings.AutoPaste}" />
</StackPanel>
</StackPanel>
<Separator />
<StackPanel Orientation="Horizontal">
<RadioButton Content="AutoType" GroupName="Mode" IsChecked="{Binding Settings.Mode, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=AutoType}" Margin="0,0,10,0" />
<StackPanel Orientation="Horizontal" IsEnabled="{Binding Settings.Mode, Converter={StaticResource EnumBooleanConverter}, ConverterParameter=AutoType}">
<Label Padding="0,0,10,0">Delay:</Label>
<TextBox Text="{Binding Settings.AutoTypeDelay, UpdateSourceTrigger=PropertyChanged}" Width="50" Height="20" />
</StackPanel>
</StackPanel>
<Button Content="Cancel AutoType" Click="CancelAutoType_Click" IsEnabled="{Binding RuntimeData.AutoTypeRunning}" />
</StackPanel>
</Grid>
<Grid DockPanel.Dock="Top" VerticalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition />
@@ -25,17 +59,17 @@
<DockPanel Grid.Column="0">
<Label DockPanel.Dock="Top" Content="Commands:" />
<TextBox DockPanel.Dock="Top" x:Name="commandsTextBox" HorizontalScrollBarVisibility="Visible" TextChanged="StaticCommandsTextBox_TextChanged" AcceptsReturn="True" VerticalAlignment="Stretch" />
<TextBox DockPanel.Dock="Top" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible" Text="{Binding RuntimeData.CommandsText, UpdateSourceTrigger=PropertyChanged}" Foreground="{Binding RuntimeData.CommandsTextColor}" TextChanged="StaticCommandsTextBox_TextChanged" AcceptsReturn="True" VerticalAlignment="Stretch" />
</DockPanel>
<DockPanel x:Name="logPanel" Grid.Column="1">
<DockPanel Visibility="{Binding RuntimeData.LogPanelVisible}" Grid.Column="1">
<Label DockPanel.Dock="Top" Content="History:" />
<ListBox DockPanel.Dock="Top" x:Name="logListBox" VerticalAlignment="Stretch" />
<ListBox DockPanel.Dock="Top" VerticalAlignment="Stretch" ItemsSource="{Binding RuntimeData.Logs}" />
</DockPanel>
<DockPanel Visibility="Collapsed" x:Name="errorPanel" Grid.Column="1">
<DockPanel Visibility="{Binding RuntimeData.ErrorPanelVisible}" Grid.Column="1">
<Label DockPanel.Dock="Top" Content="Errors:" />
<ListBox DockPanel.Dock="Top" x:Name="errorListBox" Foreground="Red" VerticalAlignment="Stretch" />
<ListBox DockPanel.Dock="Top" Foreground="Red" VerticalAlignment="Stretch" ItemsSource="{Binding RuntimeData.Errors}" />
</DockPanel>
</Grid>
</DockPanel>
+86 -81
View File
@@ -9,6 +9,8 @@ using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Language;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using WindowsInput;
@@ -22,12 +24,13 @@ namespace ClipCMD;
public partial class MainWindow : Window
{
private readonly Dictionary<string, string> commands = new Dictionary<string, string>();
private readonly string commandsPath;
private readonly System.Windows.Forms.NotifyIcon notifyIcon;
private readonly string settingsPath;
private IDataObject? oldData;
private WindowState storedWindowState = WindowState.Normal;
private readonly string cmdPath;
private readonly string fixPath;
public RuntimeData RuntimeData { get; set; } = new();
public Settings Settings { get; set; } = new();
public MainWindow()
{
@@ -42,8 +45,6 @@ public partial class MainWindow : Window
notifyIcon.Click += NotifyIcon_Click;
InitializeComponent();
string applicationDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string folderPath = Path.Combine(applicationDataPath, "ClipCMD");
@@ -52,65 +53,42 @@ public partial class MainWindow : Window
_ = Directory.CreateDirectory(folderPath);
}
cmdPath = Path.Combine(folderPath, "cmd.txt");
fixPath = Path.Combine(folderPath, "fix.txt");
commandsPath = Path.Combine(folderPath, "cmd.txt");
settingsPath = Path.Combine(folderPath, "settings.txt");
if (File.Exists(commandsPath))
{
RuntimeData.CommandsText = File.ReadAllText(commandsPath);
}
if (File.Exists(settingsPath))
{
Settings = JsonSerializer.Deserialize<Settings>(File.ReadAllText(settingsPath)) ?? new Settings();
}
DataContext = this;
InitializeComponent();
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
// Initialize the clipboard now that we have a window source to use
ClipboardManager windowClipboardManager = new ClipboardManager(this);
windowClipboardManager.ClipboardChanged += ClipboardManager_ClipboardChanged;
if (File.Exists(cmdPath))
{
commandsTextBox.Text = File.ReadAllText(cmdPath);
}
if (File.Exists(fixPath))
{
string[] lines = File.ReadAllLines(fixPath);
if (lines.Length == 2)
{
prefixTextBox.Text = lines[0];
suffixTextBox.Text = lines[1];
}
else
{
File.Delete(fixPath);
}
}
}
private void OnClose(object? sender, CancelEventArgs args)
private void AddError(string commandNames, string error)
{
notifyIcon.Dispose();
RuntimeData.Errors.Add($"[{commandNames}]\n{error}");
}
private void OnStateChanged(object? sender, EventArgs args)
private void CancelAutoType_Click(object sender, RoutedEventArgs e)
{
if (WindowState == WindowState.Minimized)
{
Hide();
notifyIcon?.ShowBalloonTip(2000);
}
else
{
storedWindowState = WindowState;
}
RuntimeData.AutoTypeRunning = false;
}
private void NotifyIcon_Click(object? sender, EventArgs e)
{
Show();
WindowState = storedWindowState;
}
private IDataObject? oldData;
private void ClipboardManager_ClipboardChanged(object? sender, EventArgs e)
private async void ClipboardManager_ClipboardChanged(object? sender, EventArgs e)
{
if (!Clipboard.ContainsText() || (oldData is not null && Clipboard.IsCurrent(oldData)))
{
@@ -126,13 +104,13 @@ public partial class MainWindow : Window
return;
}
if (!clipboardText.StartsWith(prefixTextBox.Text) || !clipboardText.EndsWith(suffixTextBox.Text))
if (!clipboardText.StartsWith(Settings.Prefix) || !clipboardText.EndsWith(Settings.Suffix))
{
oldData = Clipboard.GetDataObject();
return;
}
clipboardText = clipboardText[prefixTextBox.Text.Length..^suffixTextBox.Text.Length].Trim().Replace("\"\"", "\0");
clipboardText = clipboardText[Settings.Prefix.Length..^Settings.Suffix.Length].Trim().Replace("\"\"", "\0");
TextFieldParser parser = new TextFieldParser(new StringReader(clipboardText))
{
@@ -170,32 +148,77 @@ public partial class MainWindow : Window
_ = outText.AppendLine(commandResult?.ToString() ?? string.Empty);
}
logListBox.Items.Insert(0, $"{command} > {outText.ToString().TrimEnd()}");
RuntimeData.Logs.Insert(0, $"{command} > {outText.ToString().TrimEnd()}");
Clipboard.SetText(outText.ToString().TrimEnd());
InputSimulator inputSimulator = new InputSimulator();
oldData = Clipboard.GetDataObject();
InputSimulator inputSimulator = new InputSimulator();
_ = inputSimulator.Keyboard.ModifiedKeyStroke(new[] { VirtualKeyCode.CONTROL }, new[] { VirtualKeyCode.VK_V });
if (Settings.Mode == ClipCMDMode.ClipBoard)
{
Clipboard.SetText(outText.ToString().TrimEnd());
if (Settings.AutoPaste)
{
_ = inputSimulator.Keyboard.ModifiedKeyStroke(new[] { VirtualKeyCode.CONTROL }, new[] { VirtualKeyCode.VK_V });
}
}
else if (Settings.Mode == ClipCMDMode.AutoType)
{
RuntimeData.AutoTypeRunning = true;
foreach (char c in outText.ToString())
{
_ = inputSimulator.Keyboard.TextEntry(c);
await Task.Delay(Settings.AutoTypeDelay);
if (!RuntimeData.AutoTypeRunning)
{
break;
}
}
RuntimeData.AutoTypeRunning = false;
}
}
catch (Exception ex)
{
logListBox.Items.Insert(0, $"Error: {ex.Message}");
RuntimeData.Logs.Insert(0, $"Error: {ex.Message}");
Debug.WriteLine(ex);
}
}
private void NotifyIcon_Click(object? sender, EventArgs e)
{
Show();
WindowState = storedWindowState;
}
private void OnClose(object? sender, CancelEventArgs args)
{
notifyIcon.Dispose();
File.WriteAllText(settingsPath, JsonSerializer.Serialize(Settings));
}
private void OnStateChanged(object? sender, EventArgs args)
{
if (WindowState == WindowState.Minimized)
{
Hide();
notifyIcon?.ShowBalloonTip(2000);
}
else
{
storedWindowState = WindowState;
}
}
private void StaticCommandsTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
string[] lines = commandsTextBox.Text.Split('\n').Append("[#END#]").ToArray();
string[] lines = RuntimeData.CommandsText.Split('\n').Append("[#END#]").ToArray();
string commandNames = string.Empty;
StringBuilder script = new StringBuilder();
commandsTextBox.Foreground = System.Windows.Media.Brushes.Black;
errorPanel.Visibility = Visibility.Collapsed;
logPanel.Visibility = Visibility.Visible;
errorListBox.Items.Clear();
RuntimeData.Errors.Clear();
commands.Clear();
foreach (string l in lines)
@@ -248,24 +271,6 @@ public partial class MainWindow : Window
_ = commands.TryAdd("list", $"\"{string.Join(", ", commands.Keys)}\"");
File.WriteAllText(cmdPath, commandsTextBox.Text);
}
private void AddError(string commandNames, string error)
{
errorPanel.Visibility = Visibility.Visible;
logPanel.Visibility = Visibility.Collapsed;
commandsTextBox.Foreground = System.Windows.Media.Brushes.Red;
_ = errorListBox.Items.Add($"[{commandNames}]\n{error}");
}
private void FixTextBox_TextChanged(object sender, System.Windows.Input.KeyEventArgs e)
{
if (prefixTextBox is null || suffixTextBox is null)
{
return;
}
File.WriteAllLines(fixPath, new[] { prefixTextBox.Text, suffixTextBox.Text });
File.WriteAllText(commandsPath, RuntimeData.CommandsText);
}
}
+78
View File
@@ -0,0 +1,78 @@
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Media;
namespace ClipCMD;
public class RuntimeData : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
private bool autoTypeRunning = false;
private string commandsText = string.Empty;
private Visibility errorPanelVisible = Visibility.Collapsed;
private Visibility logPanelVisible = Visibility.Visible;
public bool AutoTypeRunning
{
get => autoTypeRunning;
set
{
autoTypeRunning = value;
OnPropertyChanged();
}
}
public string CommandsText
{
get => commandsText;
set
{
commandsText = value;
OnPropertyChanged();
}
}
public Color CommandsTextColor => Errors.Count > 0 ? Colors.Red : Colors.Black;
public Visibility ErrorPanelVisible
{
get => errorPanelVisible;
set
{
errorPanelVisible = value;
OnPropertyChanged();
}
}
public ObservableCollection<string> Errors { get; } = new();
public Visibility LogPanelVisible
{
get => logPanelVisible;
set
{
logPanelVisible = value;
OnPropertyChanged();
}
}
public ObservableCollection<string> Logs { get; } = new();
public RuntimeData()
{
Errors.CollectionChanged += (sender, args) =>
{
ErrorPanelVisible = Errors.Any() ? Visibility.Visible : Visibility.Collapsed;
LogPanelVisible = Errors.Any() ? Visibility.Collapsed : Visibility.Visible;
};
}
private void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
+77
View File
@@ -0,0 +1,77 @@
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace ClipCMD;
public class Settings : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
private bool autoPaste = true;
private int autoTypeDelay = 100;
private ClipCMDMode mode = ClipCMDMode.ClipBoard;
private string prefix = "_";
private string suffix = "_";
public bool AutoPaste
{
get => autoPaste;
set
{
autoPaste = value;
OnPropertyChanged();
}
}
public int AutoTypeDelay
{
get => autoTypeDelay;
set
{
autoTypeDelay = Math.Clamp(value, 0, 1000);
OnPropertyChanged();
}
}
public ClipCMDMode Mode
{
get => mode;
set
{
mode = value;
OnPropertyChanged();
}
}
public string Prefix
{
get => prefix;
set
{
prefix = value;
OnPropertyChanged();
}
}
public string Suffix
{
get => suffix;
set
{
suffix = value;
OnPropertyChanged();
}
}
protected void OnPropertyChanged([CallerMemberName] string? name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
public enum ClipCMDMode
{
ClipBoard,
AutoType
}