Code tidy up

pull/7/head
LeapwardKoex 2024-02-08 23:02:54 +13:00
parent 3a7183399e
commit 7ef849bf9b
7 changed files with 112 additions and 186 deletions

View File

@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Windows;
namespace WpfMaiTouchEmulator;
@ -88,22 +82,17 @@ internal class MaiTouchComConnector
void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string recievedData = serialPort.ReadExisting();
var recievedData = serialPort.ReadExisting();
var commands = recievedData.Split(new[] { '}' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string command in commands)
foreach (var command in commands)
{
string cleanedCommand = command.TrimStart('{');
// Implement your logic to process the received data here
var cleanedCommand = command.TrimStart('{');
Console.WriteLine($"Received data: {cleanedCommand}");
OnDataRecieved(cleanedCommand);
// Check if the received packet is a STAT packet
if (cleanedCommand == "STAT")
{
// Simulate entering active mode
isActiveMode = true;
Console.WriteLine("Entered Active Mode");
}
else if (cleanedCommand == "RSET")
{
@ -115,12 +104,11 @@ internal class MaiTouchComConnector
}
else if (cleanedCommand[2] == 'r' || cleanedCommand[2] == 'k')
{
char leftOrRight = cleanedCommand[0];
char sensor = cleanedCommand[1];
char ratio = cleanedCommand[3];
var leftOrRight = cleanedCommand[0];
var sensor = cleanedCommand[1];
var ratio = cleanedCommand[3];
// Create the new string in the specified format
string newString = $"({leftOrRight}{sensor}{cleanedCommand[2]}{ratio})";
var newString = $"({leftOrRight}{sensor}{cleanedCommand[2]}{ratio})";
serialPort.Write(newString);
OnDataSent(newString);
}

View File

@ -1,9 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows;
using System.Windows.Controls;
namespace WpfMaiTouchEmulator;

View File

@ -1,19 +1,8 @@
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfMaiTouchEmulator;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private readonly MaiTouchSensorButtonStateManager buttonState;

View File

@ -1,25 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Media.Imaging; // For BitmapImage
using System.IO;
using System.Windows.Interop; // For Imaging.CreateBitmapSourceFromHBitmap
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Controls.Primitives; // For Marshal
namespace WpfMaiTouchEmulator;
/// <summary>
@ -30,20 +12,25 @@ public partial class TouchPanel : Window
internal Action<TouchValue> onTouch;
internal Action<TouchValue> onRelease;
[DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr window, int index, int value);
private readonly Dictionary<int, System.Windows.Controls.Image> activeTouches = [];
private readonly TouchPanelPositionManager _positionManager;
[DllImport("user32.dll")]
public static extern int GetWindowLong(IntPtr window, int index);
private enum ResizeDirection
{
BottomRight = 8,
}
public const int GWL_EXSTYLE = -20;
public const int WS_EX_TRANSPARENT = 0x00000020;
public const int WS_EX_LAYERED = 0x00080000;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool ReleaseCapture();
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
public TouchPanel()
{
InitializeComponent();
this.Topmost = true;
Topmost = true;
_positionManager = new TouchPanelPositionManager();
}
@ -60,12 +47,6 @@ public partial class TouchPanel : Window
}
}
private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// This allows the entire window to be draggable
DragMove();
}
private void DragBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// This event is for the draggable bar, it calls DragMove to move the window
@ -80,17 +61,6 @@ public partial class TouchPanel : Window
}
}
private enum ResizeDirection
{
BottomRight = 8,
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool ReleaseCapture();
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
private void ResizeWindow(ResizeDirection direction)
{
ReleaseCapture();
@ -100,14 +70,10 @@ public partial class TouchPanel : Window
IntPtr.Zero);
}
private Dictionary<int, System.Windows.Controls.Image> activeTouches = new Dictionary<int, System.Windows.Controls.Image>();
private TouchPanelPositionManager _positionManager;
private void Element_TouchDown(object sender, TouchEventArgs e)
{
// Cast the sender to a Border to ensure it's the correct element type.
var element = sender as System.Windows.Controls.Image;
if (element != null)
if (sender is System.Windows.Controls.Image element)
{
// Highlight the element and add it to the active touches tracking.
HighlightElement(element, true);
@ -125,7 +91,7 @@ public partial class TouchPanel : Window
if (hitTestResult != null && hitTestResult.VisualHit is System.Windows.Controls.Image newElement)
{
// If this touch point is already tracking another element, unhighlight the previous one.
if (activeTouches.TryGetValue(e.TouchDevice.Id, out System.Windows.Controls.Image previousElement) && previousElement != newElement)
if (activeTouches.TryGetValue(e.TouchDevice.Id, out var previousElement) && previousElement != newElement)
{
HighlightElement(previousElement, false);
onRelease((TouchValue)previousElement.Tag);
@ -149,7 +115,7 @@ public partial class TouchPanel : Window
private void Element_TouchUp(object sender, TouchEventArgs e)
{
// When touch is lifted, unhighlight the associated element and remove it from tracking.
if (activeTouches.TryGetValue(e.TouchDevice.Id, out System.Windows.Controls.Image element))
if (activeTouches.TryGetValue(e.TouchDevice.Id, out var element))
{
HighlightElement(element, false);
onRelease((TouchValue)element.Tag);
@ -159,10 +125,10 @@ public partial class TouchPanel : Window
e.Handled = true;
}
private bool IsTouchInsideWindow(System.Windows.Point touchPoint)
private bool IsTouchInsideWindow(Point touchPoint)
{
// Define the window's bounds
var windowBounds = new Rect(0, 0, this.ActualWidth, this.ActualHeight);
var windowBounds = new Rect(0, 0, ActualWidth, ActualHeight);
// Check if the touch point is within the window's bounds
return windowBounds.Contains(touchPoint);

View File

@ -1,49 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Windows;
namespace WpfMaiTouchEmulator
namespace WpfMaiTouchEmulator;
class TouchPanelPositionManager
{
class TouchPanelPositionManager
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string? lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string? lpClassName, string lpWindowName);
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
public Rect? GetSinMaiWindowPosition()
{
var hWnd = FindWindow(null, "Sinmai");
if (hWnd != IntPtr.Zero)
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
public Rect? GetSinMaiWindowPosition()
{
// Replace "OtherAppWindowName" with the window name (title) of the other application
IntPtr hWnd = FindWindow(null, "Sinmai");
if (hWnd != IntPtr.Zero)
RECT rect;
if (GetWindowRect(hWnd, out rect))
{
RECT rect;
if (GetWindowRect(hWnd, out rect))
{
// Calculate the desired size and position based on the other application's window
int width = Convert.ToInt32((rect.Right - rect.Left));
int height = width;
int left = rect.Left + ((rect.Right - rect.Left) - width) / 2; // Center horizontally
int top = rect.Bottom - height;
return new Rect(left, top, width, height);
}
// Calculate the desired size and position based on the other application's window
var width = Convert.ToInt32((rect.Right - rect.Left));
var height = width;
var left = rect.Left + ((rect.Right - rect.Left) - width) / 2; // Center horizontally
var top = rect.Bottom - height;
return new Rect(left, top, width, height);
}
return null;
}
return null;
}
}

View File

@ -1,64 +1,61 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
namespace WpfMaiTouchEmulator
namespace WpfMaiTouchEmulator;
internal class VirtualComPortManager
{
class VirtualComPortManager
public Task<string> CheckInstalledPortsAsync()
{
public Task<string> CheckInstalledPortsAsync()
{
return ExecuteCommandAsync("C:\\Program Files (x86)\\com0com\\setupc.exe", $"list");
}
return ExecuteCommandAsync("C:\\Program Files (x86)\\com0com\\setupc.exe", $"list");
}
public Task<string> InstallComPort()
{
return ExecuteCommandAsync("C:\\Program Files (x86)\\com0com\\setupc.exe", $"install PortName=COM3 PortName=COM23");
}
public Task<string> InstallComPort()
{
return ExecuteCommandAsync("C:\\Program Files (x86)\\com0com\\setupc.exe", $"install PortName=COM3 PortName=COM23");
}
public Task<string> UninstallVirtualPorts()
{
return ExecuteCommandAsync("C:\\Program Files (x86)\\com0com\\setupc.exe", $"uninstall");
}
public Task<string> UninstallVirtualPorts()
{
return ExecuteCommandAsync("C:\\Program Files (x86)\\com0com\\setupc.exe", $"uninstall");
}
private async Task<string> ExecuteCommandAsync(string command, string arguments)
private async Task<string> ExecuteCommandAsync(string command, string arguments)
{
var processStartInfo = new ProcessStartInfo
{
var processStartInfo = new ProcessStartInfo
FileName = command,
Arguments = arguments,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
WorkingDirectory = "C:\\Program Files (x86)\\com0com"
};
var outputBuilder = new StringBuilder();
using var process = new Process { StartInfo = processStartInfo };
process.OutputDataReceived += (sender, args) =>
{
if (args.Data != null)
{
FileName = command,
Arguments = arguments,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
WorkingDirectory = "C:\\Program Files (x86)\\com0com"
};
var outputBuilder = new StringBuilder();
using (var process = new Process { StartInfo = processStartInfo })
{
process.OutputDataReceived += (sender, args) =>
{
if (args.Data != null)
outputBuilder.AppendLine(args.Data);
};
process.ErrorDataReceived += (sender, args) =>
{
if (args.Data != null)
outputBuilder.AppendLine(args.Data);
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
await process.WaitForExitAsync();
return outputBuilder.ToString();
outputBuilder.AppendLine(args.Data);
}
}
};
process.ErrorDataReceived += (sender, args) =>
{
if (args.Data != null)
{
outputBuilder.AppendLine(args.Data);
}
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
await process.WaitForExitAsync();
return outputBuilder.ToString();
}
}

View File

@ -1,6 +1,4 @@
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
public static class VisualTreeHelperExtensions
@ -11,10 +9,10 @@ public static class VisualTreeHelperExtensions
var images = new List<Image>();
// Recursive search of the visual tree to find all Image controls
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child != null && child is Image)
if (child is not null and Image)
{
images.Add((Image)child);
}