标签:space roc windows wsm null lin string ges res
已知的问题:
1. 调试的时候会报IO 异常,非调试环境是正常的
2. Windows 应用程序才可以使用,可以用非windows应用程序包一层
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using windowsApiAcitonSimulation.Win32Action; namespace winFormTest { static class Program { [DllImport("kernel32.dll", SetLastError = true)] static extern bool AttachConsole(uint dwProcessId); [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr GetStdHandle(int nStdHandle); [DllImport("kernel32.dll", SetLastError = true)] static extern bool ReadConsoleOutputCharacter(IntPtr hConsoleOutput, [Out] StringBuilder lpCharacter, uint length, Coord bufferCoord, out uint lpNumberOfCharactersRead); [StructLayout(LayoutKind.Sequential)] public struct Coord { public short X; public short Y; } public static string ReadCharacterAt(int x, int y, int length) { IntPtr consoleHandle = GetStdHandle(-11); if (consoleHandle == IntPtr.Zero) { return null; } Coord position = new Coord { X = (short)x, Y = (short)y }; StringBuilder result = new StringBuilder(length); uint read = 0; if (ReadConsoleOutputCharacter(consoleHandle, result, (uint)length, position, out read)) { return result.ToString(); } else { return null; } } /// <summary> /// 关闭进程 /// </summary> /// <param name="processName">进程名</param> private static Process GetNgrokProcess(string processName) { Process[] myproc = Process.GetProcesses(); foreach (Process item in myproc) { if (item.ProcessName == processName) { return item; } } return null; } /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { var process = GetNgrokProcess("ngrok"); //注意要是 Windows 应用程序才可以 AttachConsole成功 var flag = AttachConsole((uint)process.Id); Console.CursorLeft = 0; Console.CursorTop = 0; string content = ReadCharacterAt(0, 2, 45); //if (content?.IndexOf("reconnecting") > -1) //{ // var ptr = WindowsApiHelp.FindWindow("ConsoleWindowClass", @"ngrok.bat"); // if (ptr == IntPtr.Zero) // { // ptr = WindowsApiHelp.FindWindow("ConsoleWindowClass", @"选择ngrok.bat"); // } // var pid = GetCurrentProcessID(ptr); // WindowsApiHelp.SendMessage(ptr, WindowsMessages.WM_CLOSE, 0, 0); //} } } }
c# 通过win32 api 得到指定Console application Content
标签:space roc windows wsm null lin string ges res
原文地址:https://www.cnblogs.com/gaocong/p/11792989.html