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);
//}
}
}
}