Skip to content

Instantly share code, notes, and snippets.

@secretGeek
Created August 30, 2017 12:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save secretGeek/e1fead625e672f52a01910d550d5c6dc to your computer and use it in GitHub Desktop.
Save secretGeek/e1fead625e672f52a01910d550d5c6dc to your computer and use it in GitHub Desktop.
simulate Alt-Enter in parent console from windows app
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace PaulBettsWIN32
{
static class Program
{
[STAThread]
static void Main(string[] args)
{
runTest();
}
private static void runTest()
{
uint pid = 0x0ffffffff; //ATTACH_PARENT_PROCESS
try
{
var image = NativeMethods.GetImagePathForPid(pid);
if (!executableUsesWin32Subsystem(image))
{
if (!NativeMethods.AttachConsole(pid))
{
var f = new Win32Exception();
throw f;
}
var hStdOut = NativeMethods.GetStdHandle(-11);
if (!NativeMethods.SetConsoleDisplayMode(hStdOut, 1, IntPtr.Zero))
{
var f = new Win32Exception();
throw f;
}
NativeMethods.FreeConsole();
return;
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}
}
private static bool executableUsesWin32Subsystem(object o)
{
return false;
}
}
public static class NativeMethods
{
public static bool GetImagePathForPid(uint pid)
{
return true;
}
[DllImport("kernel32", SetLastError = true)]
public static extern bool FreeConsole();
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool AttachConsole(uint dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetConsoleDisplayMode(
IntPtr ConsoleOutput,
uint Flags,
IntPtr whoKnows);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment