An amusing little example I came up with of how to open a window that is a child window of a console window. Just in case I need it in the future. Also useful for spawning a window from an OpenGL app, or hanging a child window off a separate thread.
// This is an example of how to open a Child Window from a Console
// Window in C#.
// By John Stewien 2010
using System;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ConsoleApplication {
/// <summary>
/// A simple form with a CheckBox that can be used to verify the
/// responsiveness of the Form.
/// </summary>
public class Form1 : Form {
public Form1() {
CheckBox checkBox1 = new System.Windows.Forms.CheckBox();
checkBox1.AutoSize = true;
checkBox1.Text = "Check / Uncheck to test responsiveness";
Controls.Add(checkBox1);
Text = "Form1";
}
}
class Program {
// Import the required Windows API functions
[DllImport("User32.dll", CharSet = CharSet.Auto)]
static extern IntPtr FindWindow(char[] lpClassName, char[] lpWindowName);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
static extern int SetWindowLongW(HandleRef hWnd, int nIndex, IntPtr dwNewLong);
const int GWLP_HWNDPARENT = -8;
// Store these parameters as statics as they are called from static methods
static IntPtr consoleHWnd;
static Form1 form;
/// <summary>
/// Method for running the form, called from a thread
/// </summary>
static void RunForm() {
form = new Form1();
SetWindowLongW(new HandleRef(form, form.Handle), GWLP_HWNDPARENT, consoleHWnd);
Application.Run(form);
}
// Delegate for invoking a method with no parameters
delegate void SimpleDelegate();
static void Main(string[] args) {
// Set the Console Title and then find its HWND
Console.Title = "Child Window On Console Test";
consoleHWnd = FindWindow("ConsoleWindowClass".ToCharArray(), Console.Title.ToCharArray());
// Run the Form
Thread thread = new Thread(new ThreadStart(RunForm));
thread.Start();
// Do some text stuff on the Console to show it is working
Console.WriteLine("Enter Text. Enter \"exit\" to exit.");
string text = "";
while (text != "exit")
text = Console.ReadLine();
// Close the Form so we can exit
form.Invoke(new SimpleDelegate(form.Close));
}
}
}