From 272cf488a37cb80975cd86fe6ad968ebd1c496d9 Mon Sep 17 00:00:00 2001 From: fofolee Date: Sun, 19 Jan 2025 16:07:06 +0800 Subject: [PATCH] =?UTF-8?q?=E7=A7=BB=E9=99=A4quickcommand.runCSharp?= =?UTF-8?q?=EF=BC=8C=E6=A8=A1=E6=8B=9F=E6=93=8D=E4=BD=9C=E4=B8=ADwin?= =?UTF-8?q?=E4=B8=8B=E7=9A=84=E5=B1=8F=E5=B9=95=E6=88=AA=E5=9B=BE=E4=BD=BF?= =?UTF-8?q?=E7=94=A8runCsharpFeature=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/lib/csharp/index.js | 1 - plugin/lib/csharp/utils.cs | 652 ++++++++++-------- .../quickcomposer/simulate/screenCapture.js | 111 +-- src/js/composer/commands/scriptCommands.js | 7 - .../monaco/types/quickcommand.api.d.ts | 31 +- 5 files changed, 384 insertions(+), 418 deletions(-) diff --git a/plugin/lib/csharp/index.js b/plugin/lib/csharp/index.js index 9dd9ae2..339b268 100644 --- a/plugin/lib/csharp/index.js +++ b/plugin/lib/csharp/index.js @@ -174,7 +174,6 @@ const runCsharpFeature = async (feature, args = [], options = {}) => { console.log(featureExePath, args.join(" ")); currentChild = child_process.spawn(featureExePath, args, { encoding: null, - windowsHide: true, }); let stdoutData = Buffer.from([]); diff --git a/plugin/lib/csharp/utils.cs b/plugin/lib/csharp/utils.cs index 9a87308..1002e6e 100644 --- a/plugin/lib/csharp/utils.cs +++ b/plugin/lib/csharp/utils.cs @@ -5,328 +5,413 @@ using System.Net.NetworkInformation; using System.Diagnostics; using System.IO; using Microsoft.Win32; +using System.Drawing; +using System.Drawing.Imaging; public class SystemUtils { - #region Win32 API - [DllImport("user32.dll", CharSet = CharSet.Auto)] - private static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni); + #region Win32 API + [DllImport("user32.dll", CharSet = CharSet.Auto)] + private static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni); - [DllImport("user32.dll")] - private static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); + [DllImport("user32.dll")] + private static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); - [DllImport("user32.dll")] - private static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] + private static extern IntPtr GetForegroundWindow(); - [DllImport("PowrProf.dll", CharSet = CharSet.Auto, ExactSpelling = true)] - private static extern bool SetSuspendState(bool hibernate, bool forceCritical, bool disableWakeEvent); + [DllImport("PowrProf.dll", CharSet = CharSet.Auto, ExactSpelling = true)] + private static extern bool SetSuspendState(bool hibernate, bool forceCritical, bool disableWakeEvent); - [DllImport("kernel32.dll")] - private static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags); + [DllImport("kernel32.dll")] + private static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags); - private const int SPI_SETDESKWALLPAPER = 20; - private const int SPIF_UPDATEINIFILE = 0x01; - private const int SPIF_SENDCHANGE = 0x02; - private const int WM_SYSCOMMAND = 0x0112; - private const int SC_MONITORPOWER = 0xF170; + [DllImport("user32.dll")] + static extern IntPtr GetDesktopWindow(); - [Flags] - private enum EXECUTION_STATE : uint + [DllImport("user32.dll")] + static extern IntPtr GetWindowDC(IntPtr hWnd); + + [DllImport("gdi32.dll")] + static extern bool BitBlt(IntPtr hdcDest, int nXDest, int nYDest, + int nWidth, int nHeight, IntPtr hdcSrc, + int nXSrc, int nYSrc, int dwRop); + + [DllImport("gdi32.dll")] + static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight); + + [DllImport("gdi32.dll")] + static extern IntPtr CreateCompatibleDC(IntPtr hDC); + + [DllImport("gdi32.dll")] + static extern bool DeleteDC(IntPtr hDC); + + [DllImport("gdi32.dll")] + static extern bool DeleteObject(IntPtr hObject); + + [DllImport("gdi32.dll")] + static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); + + [StructLayout(LayoutKind.Sequential)] + public struct RECT + { + public int left; + public int top; + public int right; + public int bottom; + } + + [DllImport("user32.dll")] + private static extern int GetWindowRect(IntPtr hWnd, ref RECT rect); + + [DllImport("user32.dll")] + private static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC); + + private const int SPI_SETDESKWALLPAPER = 20; + private const int SPIF_UPDATEINIFILE = 0x01; + private const int SPIF_SENDCHANGE = 0x02; + private const int WM_SYSCOMMAND = 0x0112; + private const int SC_MONITORPOWER = 0xF170; + + [Flags] + private enum EXECUTION_STATE : uint + { + ES_AWAYMODE_REQUIRED = 0x00000040, + ES_CONTINUOUS = 0x80000000, + ES_DISPLAY_REQUIRED = 0x00000002, + ES_SYSTEM_REQUIRED = 0x00000001 + } + #endregion + + public static void Main(string[] args) + { + if (args.Length == 0 || args[0] == "-h" || args[0] == "--help") { - ES_AWAYMODE_REQUIRED = 0x00000040, - ES_CONTINUOUS = 0x80000000, - ES_DISPLAY_REQUIRED = 0x00000002, - ES_SYSTEM_REQUIRED = 0x00000001 + ShowHelp(); + return; } - #endregion - public static void Main(string[] args) + string type = GetArgumentValue(args, "-type"); + if (string.IsNullOrEmpty(type)) { - if (args.Length == 0 || args[0] == "-h" || args[0] == "--help") - { - ShowHelp(); + Console.Error.WriteLine("Error: 必须指定操作类型 (-type)"); + return; + } + + try + { + switch (type.ToLower()) + { + case "wallpaper": + string wallpaperPath = GetArgumentValue(args, "-path"); + if (string.IsNullOrEmpty(wallpaperPath)) + { + Console.Error.WriteLine("Error: 必须指定壁纸路径 (-path)"); return; - } + } + SetWallpaper(wallpaperPath); + break; - string type = GetArgumentValue(args, "-type"); - if (string.IsNullOrEmpty(type)) - { - Console.Error.WriteLine("Error: 必须指定操作类型 (-type)"); + case "monitor": + string action = GetArgumentValue(args, "-action"); + if (string.IsNullOrEmpty(action)) + { + Console.Error.WriteLine("Error: 必须指定动作 (-action)"); return; - } + } + ControlMonitor(action); + break; - try - { - switch (type.ToLower()) - { - case "wallpaper": - string wallpaperPath = GetArgumentValue(args, "-path"); - if (string.IsNullOrEmpty(wallpaperPath)) - { - Console.Error.WriteLine("Error: 必须指定壁纸路径 (-path)"); - return; - } - SetWallpaper(wallpaperPath); - break; + case "power": + string mode = GetArgumentValue(args, "-mode"); + if (string.IsNullOrEmpty(mode)) + { + Console.Error.WriteLine("Error: 必须指定电源模式 (-mode)"); + return; + } + PowerControl(mode); + break; - case "monitor": - string action = GetArgumentValue(args, "-action"); - if (string.IsNullOrEmpty(action)) - { - Console.Error.WriteLine("Error: 必须指定动作 (-action)"); - return; - } - ControlMonitor(action); - break; + case "network": + string interfaceName = GetArgumentValue(args, "-interface"); + string ip = GetArgumentValue(args, "-ip"); + string mask = GetArgumentValue(args, "-mask"); + string gateway = GetArgumentValue(args, "-gateway"); + string dns = GetArgumentValue(args, "-dns"); + ConfigureNetwork(interfaceName, ip, mask, gateway, dns); + break; - case "power": - string mode = GetArgumentValue(args, "-mode"); - if (string.IsNullOrEmpty(mode)) - { - Console.Error.WriteLine("Error: 必须指定电源模式 (-mode)"); - return; - } - PowerControl(mode); - break; + case "startup": + string appPath = GetArgumentValue(args, "-path"); + string appName = GetArgumentValue(args, "-name"); + bool remove = HasArgument(args, "-remove"); + ManageStartup(appPath, appName, remove); + break; - case "network": - string interfaceName = GetArgumentValue(args, "-interface"); - string ip = GetArgumentValue(args, "-ip"); - string mask = GetArgumentValue(args, "-mask"); - string gateway = GetArgumentValue(args, "-gateway"); - string dns = GetArgumentValue(args, "-dns"); - ConfigureNetwork(interfaceName, ip, mask, gateway, dns); - break; + case "shortcut": + string targetPath = GetArgumentValue(args, "-target"); + string shortcutPath = GetArgumentValue(args, "-path"); + string shortcutArgs = GetArgumentValue(args, "-args"); + CreateShortcut(targetPath, shortcutPath, shortcutArgs); + break; - case "startup": - string appPath = GetArgumentValue(args, "-path"); - string appName = GetArgumentValue(args, "-name"); - bool remove = HasArgument(args, "-remove"); - ManageStartup(appPath, appName, remove); - break; + case "brightness": + string brightness = GetArgumentValue(args, "-level"); + if (string.IsNullOrEmpty(brightness)) + { + Console.Error.WriteLine("Error: 必须指定亮度级别 (-level)"); + return; + } + SetBrightness(int.Parse(brightness)); + break; - case "shortcut": - string targetPath = GetArgumentValue(args, "-target"); - string shortcutPath = GetArgumentValue(args, "-path"); - string shortcutArgs = GetArgumentValue(args, "-args"); - CreateShortcut(targetPath, shortcutPath, shortcutArgs); - break; + case "screenshot": + string savePath = GetArgumentValue(args, "-path"); + if (string.IsNullOrEmpty(savePath)) + { + Console.Error.WriteLine("Error: 必须指定保存路径 (-path)"); + return; + } + CaptureScreenToFile(savePath); + Console.WriteLine("成功保存截图"); + break; - case "brightness": - string brightness = GetArgumentValue(args, "-level"); - if (string.IsNullOrEmpty(brightness)) - { - Console.Error.WriteLine("Error: 必须指定亮度级别 (-level)"); - return; - } - SetBrightness(int.Parse(brightness)); - break; + default: + Console.Error.WriteLine("Error: 不支持的操作类型"); + break; + } + } + catch (Exception ex) + { + Console.Error.WriteLine(string.Format("Error: {0}", ex.Message)); + } + } - default: - Console.Error.WriteLine("Error: 不支持的操作类型"); - break; - } - } - catch (Exception ex) - { - Console.Error.WriteLine(string.Format("Error: {0}", ex.Message)); - } + private static void SetWallpaper(string path) + { + if (!File.Exists(path)) + { + throw new Exception("壁纸文件不存在"); } - private static void SetWallpaper(string path) - { - if (!File.Exists(path)) - { - throw new Exception("壁纸文件不存在"); - } + SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE); + Console.WriteLine("成功设置壁纸"); + } - SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, path, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE); - Console.WriteLine("成功设置壁纸"); + private static void ControlMonitor(string action) + { + IntPtr hWnd = GetForegroundWindow(); + switch (action.ToLower()) + { + case "off": + SendMessage(hWnd, WM_SYSCOMMAND, SC_MONITORPOWER, 2); + break; + case "on": + SendMessage(hWnd, WM_SYSCOMMAND, SC_MONITORPOWER, -1); + break; + default: + throw new Exception("不支持的显示器操作"); + } + Console.WriteLine("成功控制显示器"); + } + + private static void PowerControl(string mode) + { + switch (mode.ToLower()) + { + case "sleep": + SetSuspendState(false, false, false); + break; + case "hibernate": + SetSuspendState(true, false, false); + break; + case "awake": + SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_SYSTEM_REQUIRED); + break; + case "normal": + SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS); + break; + default: + throw new Exception("不支持的电源模式"); + } + Console.WriteLine("成功设置电源模式"); + } + + private static void ConfigureNetwork(string interfaceName, string ip, string mask, string gateway, string dns) + { + // 使用netsh命令配置网络 + StringBuilder command = new StringBuilder(); + command.AppendFormat("interface ip set address \"{0}\" static {1} {2}", interfaceName, ip, mask); + if (!string.IsNullOrEmpty(gateway)) + { + command.AppendFormat(" {0}", gateway); } - private static void ControlMonitor(string action) + ProcessStartInfo startInfo = new ProcessStartInfo { - IntPtr hWnd = GetForegroundWindow(); - switch (action.ToLower()) - { - case "off": - SendMessage(hWnd, WM_SYSCOMMAND, SC_MONITORPOWER, 2); - break; - case "on": - SendMessage(hWnd, WM_SYSCOMMAND, SC_MONITORPOWER, -1); - break; - default: - throw new Exception("不支持的显示器操作"); - } - Console.WriteLine("成功控制显示器"); + FileName = "netsh", + Arguments = command.ToString(), + UseShellExecute = false, + RedirectStandardOutput = true, + CreateNoWindow = true + }; + + using (Process process = Process.Start(startInfo)) + { + process.WaitForExit(); + if (process.ExitCode != 0) + { + throw new Exception("设置IP地址失败"); + } } - private static void PowerControl(string mode) + if (!string.IsNullOrEmpty(dns)) { - switch (mode.ToLower()) + command.Clear(); + command.AppendFormat("interface ip set dns \"{0}\" static {1}", interfaceName, dns); + startInfo.Arguments = command.ToString(); + + using (Process process = Process.Start(startInfo)) + { + process.WaitForExit(); + if (process.ExitCode != 0) { - case "sleep": - SetSuspendState(false, false, false); - break; - case "hibernate": - SetSuspendState(true, false, false); - break; - case "awake": - SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_SYSTEM_REQUIRED); - break; - case "normal": - SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS); - break; - default: - throw new Exception("不支持的电源模式"); + throw new Exception("设置DNS失败"); } - Console.WriteLine("成功设置电源模式"); + } } - private static void ConfigureNetwork(string interfaceName, string ip, string mask, string gateway, string dns) + Console.WriteLine("成功配置网络"); + } + + private static void ManageStartup(string appPath, string appName, bool remove) + { + string keyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; + using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyPath, true)) { - // 使用netsh命令配置网络 - StringBuilder command = new StringBuilder(); - command.AppendFormat("interface ip set address \"{0}\" static {1} {2}", interfaceName, ip, mask); - if (!string.IsNullOrEmpty(gateway)) - { - command.AppendFormat(" {0}", gateway); - } + if (key == null) + { + throw new Exception("无法访问启动项注册表"); + } - ProcessStartInfo startInfo = new ProcessStartInfo - { - FileName = "netsh", - Arguments = command.ToString(), - UseShellExecute = false, - RedirectStandardOutput = true, - CreateNoWindow = true - }; - - using (Process process = Process.Start(startInfo)) - { - process.WaitForExit(); - if (process.ExitCode != 0) - { - throw new Exception("设置IP地址失败"); - } - } - - if (!string.IsNullOrEmpty(dns)) - { - command.Clear(); - command.AppendFormat("interface ip set dns \"{0}\" static {1}", interfaceName, dns); - startInfo.Arguments = command.ToString(); - - using (Process process = Process.Start(startInfo)) - { - process.WaitForExit(); - if (process.ExitCode != 0) - { - throw new Exception("设置DNS失败"); - } - } - } - - Console.WriteLine("成功配置网络"); + if (remove) + { + key.DeleteValue(appName, false); + Console.WriteLine("成功移除开机启动项"); + } + else + { + key.SetValue(appName, appPath); + Console.WriteLine("成功添加开机启动项"); + } } + } - private static void ManageStartup(string appPath, string appName, bool remove) - { - string keyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; - using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyPath, true)) - { - if (key == null) - { - throw new Exception("无法访问启动项注册表"); - } - - if (remove) - { - key.DeleteValue(appName, false); - Console.WriteLine("成功移除开机启动项"); - } - else - { - key.SetValue(appName, appPath); - Console.WriteLine("成功添加开机启动项"); - } - } - } - - private static void CreateShortcut(string targetPath, string shortcutPath, string args) - { - // 使用PowerShell创建快捷方式 - StringBuilder command = new StringBuilder(); - command.AppendFormat(@" + private static void CreateShortcut(string targetPath, string shortcutPath, string args) + { + // 使用PowerShell创建快捷方式 + StringBuilder command = new StringBuilder(); + command.AppendFormat(@" $WshShell = New-Object -comObject WScript.Shell $Shortcut = $WshShell.CreateShortcut('{0}') $Shortcut.TargetPath = '{1}'", - shortcutPath.Replace("'", "''"), - targetPath.Replace("'", "''")); + shortcutPath.Replace("'", "''"), + targetPath.Replace("'", "''")); - if (!string.IsNullOrEmpty(args)) - { - command.AppendFormat(@" + if (!string.IsNullOrEmpty(args)) + { + command.AppendFormat(@" $Shortcut.Arguments = '{0}'", - args.Replace("'", "''")); - } + args.Replace("'", "''")); + } - command.Append(@" + command.Append(@" $Shortcut.Save()"); - ProcessStartInfo startInfo = new ProcessStartInfo - { - FileName = "powershell", - Arguments = command.ToString(), - UseShellExecute = false, - RedirectStandardOutput = true, - CreateNoWindow = true - }; + ProcessStartInfo startInfo = new ProcessStartInfo + { + FileName = "powershell", + Arguments = command.ToString(), + UseShellExecute = false, + RedirectStandardOutput = true, + CreateNoWindow = true + }; - using (Process process = Process.Start(startInfo)) - { - process.WaitForExit(); - if (process.ExitCode != 0) - { - throw new Exception("创建快捷方式失败"); - } - } - - Console.WriteLine("成功创建快捷方式"); + using (Process process = Process.Start(startInfo)) + { + process.WaitForExit(); + if (process.ExitCode != 0) + { + throw new Exception("创建快捷方式失败"); + } } - private static void SetBrightness(int level) + Console.WriteLine("成功创建快捷方式"); + } + + private static void SetBrightness(int level) + { + if (level < 0 || level > 100) { - if (level < 0 || level > 100) - { - throw new Exception("亮度级别必须在0-100之间"); - } - - // 使用PowerShell命令设置亮度 - ProcessStartInfo startInfo = new ProcessStartInfo - { - FileName = "powershell", - Arguments = string.Format("(Get-WmiObject -Namespace root/WMI -Class WmiMonitorBrightnessMethods).WmiSetBrightness(1,{0})", level), - UseShellExecute = false, - RedirectStandardOutput = true, - CreateNoWindow = true - }; - - using (Process process = Process.Start(startInfo)) - { - process.WaitForExit(); - if (process.ExitCode != 0) - { - throw new Exception("设置亮度失败"); - } - } - - Console.WriteLine("成功设置亮度"); + throw new Exception("亮度级别必须在0-100之间"); } - private static void ShowHelp() + // 使用PowerShell命令设置亮度 + ProcessStartInfo startInfo = new ProcessStartInfo { - string help = @" + FileName = "powershell", + Arguments = string.Format("(Get-WmiObject -Namespace root/WMI -Class WmiMonitorBrightnessMethods).WmiSetBrightness(1,{0})", level), + UseShellExecute = false, + RedirectStandardOutput = true, + CreateNoWindow = true + }; + + using (Process process = Process.Start(startInfo)) + { + process.WaitForExit(); + if (process.ExitCode != 0) + { + throw new Exception("设置亮度失败"); + } + } + + Console.WriteLine("成功设置亮度"); + } + + private static Image CaptureScreen() + { + IntPtr handle = GetDesktopWindow(); + IntPtr hdcSrc = GetWindowDC(handle); + RECT windowRect = new RECT(); + GetWindowRect(handle, ref windowRect); + int width = windowRect.right - windowRect.left; + int height = windowRect.bottom - windowRect.top; + + IntPtr hdcDest = CreateCompatibleDC(hdcSrc); + IntPtr hBitmap = CreateCompatibleBitmap(hdcSrc, width, height); + IntPtr hOld = SelectObject(hdcDest, hBitmap); + + BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, 0x00CC0020); + SelectObject(hdcDest, hOld); + DeleteDC(hdcDest); + + Image img = Image.FromHbitmap(hBitmap); + DeleteObject(hBitmap); + ReleaseDC(handle, hdcSrc); + + return img; + } + + private static void CaptureScreenToFile(string path) + { + Image img = CaptureScreen(); + img.Save(path, ImageFormat.Png); + img.Dispose(); + } + + private static void ShowHelp() + { + string help = @" Windows 系统工具使用说明 =================== @@ -378,6 +463,11 @@ utils.exe -type <操作类型> [参数...] -level <亮度> 亮度级别(0-100) 示例: utils.exe -type brightness -level 75 +8. screenshot - 屏幕截图 + 参数: + -path <保存路径> 截图保存路径 + 示例: utils.exe -type screenshot -path ""C:\screenshot.png"" + 注意事项: -------- 1. 某些操作可能需要管理员权限 @@ -385,23 +475,23 @@ utils.exe -type <操作类型> [参数...] 3. 电源控制可能会影响正在运行的程序 4. 建议在更改系统设置前先备份当前配置 "; - Console.WriteLine(help); - } + Console.WriteLine(help); + } - private static string GetArgumentValue(string[] args, string key) + private static string GetArgumentValue(string[] args, string key) + { + for (int i = 0; i < args.Length - 1; i++) { - for (int i = 0; i < args.Length - 1; i++) - { - if (args[i].Equals(key, StringComparison.OrdinalIgnoreCase)) - { - return args[i + 1]; - } - } - return null; + if (args[i].Equals(key, StringComparison.OrdinalIgnoreCase)) + { + return args[i + 1]; + } } + return null; + } - private static bool HasArgument(string[] args, string key) - { - return Array.Exists(args, arg => arg.Equals(key, StringComparison.OrdinalIgnoreCase)); - } + private static bool HasArgument(string[] args, string key) + { + return Array.Exists(args, arg => arg.Equals(key, StringComparison.OrdinalIgnoreCase)); + } } diff --git a/plugin/lib/quickcomposer/simulate/screenCapture.js b/plugin/lib/quickcomposer/simulate/screenCapture.js index 14c4eae..9bb7fa9 100644 --- a/plugin/lib/quickcomposer/simulate/screenCapture.js +++ b/plugin/lib/quickcomposer/simulate/screenCapture.js @@ -3,122 +3,29 @@ const { promisify } = require("util"); const fs = require("fs"); const path = require("path"); const os = require("os"); +const { runCsharpFeature } = require("../../csharp"); const execFileAsync = promisify(execFile); const readFileAsync = promisify(fs.readFile); const unlinkAsync = promisify(fs.unlink); -// Windows C# 截图代码 -const csharpScript = ` -using System; -using System.Runtime.InteropServices; -using System.Drawing; -using System.Drawing.Imaging; -using System.Collections.Generic; -using Microsoft.VisualBasic; - -public class ScreenCapture -{ - [DllImport("user32.dll")] - static extern IntPtr GetDC(IntPtr hwnd); - - [DllImport("user32.dll")] - static extern IntPtr GetDesktopWindow(); - - [DllImport("user32.dll")] - static extern IntPtr GetWindowDC(IntPtr hWnd); - - [DllImport("user32.dll")] - static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC); - - [DllImport("gdi32.dll")] - static extern bool BitBlt(IntPtr hdcDest, int nXDest, int nYDest, - int nWidth, int nHeight, IntPtr hdcSrc, - int nXSrc, int nYSrc, int dwRop); - - [DllImport("gdi32.dll")] - static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight); - - [DllImport("gdi32.dll")] - static extern IntPtr CreateCompatibleDC(IntPtr hDC); - - [DllImport("gdi32.dll")] - static extern bool DeleteDC(IntPtr hDC); - - [DllImport("gdi32.dll")] - static extern bool DeleteObject(IntPtr hObject); - - [DllImport("gdi32.dll")] - static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); - - public Image CaptureScreen() - { - return CaptureWindow(GetDesktopWindow()); - } - - private Image CaptureWindow(IntPtr handle) - { - IntPtr hdcSrc = GetWindowDC(handle); - User32.RECT windowRect = new User32.RECT(); - User32.GetWindowRect(handle, ref windowRect); - int width = windowRect.right - windowRect.left; - int height = windowRect.bottom - windowRect.top; - - IntPtr hdcDest = CreateCompatibleDC(hdcSrc); - IntPtr hBitmap = CreateCompatibleBitmap(hdcSrc, width, height); - IntPtr hOld = SelectObject(hdcDest, hBitmap); - - BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, 0x00CC0020); - SelectObject(hdcDest, hOld); - DeleteDC(hdcDest); - - Image img = Image.FromHbitmap(hBitmap); - DeleteObject(hBitmap); - ReleaseDC(handle, hdcSrc); - - return img; - } - - public void CaptureScreenToFile(string filename, ImageFormat format) - { - Image img = CaptureScreen(); - img.Save(filename, format); - } - - public class User32 - { - public struct RECT - { - public int left; - public int top; - public int right; - public int bottom; - } - - [DllImport("user32.dll")] - public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect); - } - - public static void Main() - { - ScreenCapture sc = new ScreenCapture(); - sc.CaptureScreenToFile(">>tempscreenshot<<", ImageFormat.Png); - } -} -`; - // Windows 截图实现 async function captureWindowsScreen() { const tmpFile = path.join(os.tmpdir(), `screen-${Date.now()}.png`); try { - await window.quickcommand.runCsharp( - csharpScript.replace(">>tempscreenshot<<", tmpFile.replace(/\\/g, "\\\\")) - ); + await runCsharpFeature("utils", [ + "-type", + "screenshot", + "-path", + tmpFile, + ]); const imageBuffer = await readFileAsync(tmpFile); return `data:image/png;base64,${imageBuffer.toString("base64")}`; } catch (error) { console.error("Windows截图失败:", error); return null; + } finally { + await unlinkAsync(tmpFile).catch(() => {}); } } diff --git a/src/js/composer/commands/scriptCommands.js b/src/js/composer/commands/scriptCommands.js index 1b5ebe9..f33a5f7 100644 --- a/src/js/composer/commands/scriptCommands.js +++ b/src/js/composer/commands/scriptCommands.js @@ -42,12 +42,5 @@ export const scriptCommands = { }, ], }, - { - value: "quickcommand.runCsharp", - label: "执行C#脚本", - icon: "script", - outputVariable: "result", - saveOutput: true, - }, ], }; diff --git a/src/plugins/monaco/types/quickcommand.api.d.ts b/src/plugins/monaco/types/quickcommand.api.d.ts index 5fb9062..3e230de 100644 --- a/src/plugins/monaco/types/quickcommand.api.d.ts +++ b/src/plugins/monaco/types/quickcommand.api.d.ts @@ -57,11 +57,11 @@ interface quickcommandApi { * for (var i = 0; i < 15; i++) { * // 每一个选项为 json 格式, 使用clickFn注册选项单击事件时id属性是必需的 * opt.push({ - * id: i, - * title: `选项${i}`, - * description: `选项${i}的描述`, + * id: i, + * title: `选项${i}`, + * description: `选项${i}的描述`, * icon: `http://www.u.tools/favicon.ico`, - * abcd: `选项${i}的自定义属性`, + * abcd: `选项${i}的自定义属性`, * clickFn:function(e){console.log(e)} * }) * } @@ -347,29 +347,6 @@ interface quickcommandApi { */ runPowerShell(script: string): Promise; - /** - * 运行C#脚本,并返回运行结果 (Promise) - * - * 需要安装.NET Framework - * - * ```js - * const script = `using System; - * class Program { - * static void Main(string[] args) { - * Console.WriteLine("Hello, World!"); - * } - * }` - * quickcommand.runCsharp(script).then(res => { - * console.log(res) - * }).catch(err => { - * console.log(err) - * }) - * ``` - * - * @param script C# 脚本代码 - */ - runCsharp(script: string): Promise; - /** * MacOS 下运行 AppleScript 脚本并返回运行结果 (Promise) *