Windows Command-Line: Introducing the Windows Pseudo Console (ConPTY)

Rich Turner

In this, the fourth post in the Windows Command-Line series, we’ll discuss the new Windows Pseudo Console (ConPTY) infrastructure and API – why we built it, what it’s for, how it works, how to use it, and more.

Posts in the “Windows Command-Line” series

Note: This chapter list will be updated as more posts are published:

  1. Backgrounder
  2. The Evolution of the Windows Command-Line
  3. Inside the Windows Console
  4. Introducing the Windows Pseudo Console (ConPTY) [This Post]
  5. Unicode and UTF-8 Output Text Buffer

In the previous post in this series, we started to explore the internals of the Windows Console and Windows’ Command-Line infrastructure. We also discussed many of Console’s strengths and outlined its key weaknesses.

One of those weaknesses is that Windows tries to be “helpful” but gets in the way of alternative and 3rd party Console developers, service developers, etc. When building a Console or service, developers need to be able to access/supply the communication pipes through which their Terminal/service communicates with command-line applications. In the *NIX world, this isn’t a problem because *NIX provides a “Pseudo Terminal” (PTY) infrastructure which makes it easy to build the communication plumbing for a Console or service, but Windows does not …

… until now!

From TTY to PTY

Before we dig into what we’ve done, let’s briefly revisit how Terminals evolved:

In the beginning was the TTY

As discussed in the first ‘backgrounder’ post in this series, in the early days of computing, users operated computers via electromechanical Teletype (TTY) devices connected to a computer via some form of serial communications link (typically a 20mA current loop).

Ken Thompson and Dennis Richie (standing) working on a DEC PDP-11 via teletype (notice no electronic display)
Ken Thompson and Dennis Richie (standing) working on a DEC PDP-11 via teletype (notice no electronic display)

Rise of the Terminals

Teletype devices were replaced by computerized Terminals with electronic display devices (usually CRT screens). Terminals were generally very simple devices (hence the term “dumb terminal”) containing only the electronics and compute-power required to:

  1. Accept text input via the keyboard
  2. Buffer input text one line at a time (enabling local editing before sending)
  3. Send/receive text via serial communications (usually via the once ubiquitous RS-232 interface)
  4. Display received text on the Terminal’s display

Despite their simplicity (or perhaps because of it), Terminals rapidly became the primary devices used to operate mini, mainframe, and server computers: Most data entry clerks, computer operators, system administrators, scientists, researchers, software developers, and industry luminaries earned their digital-stripes by pounding away on Terminals from DEC, IBM, Wyse, and many others.

Admiral Grace Hopper in her office with a DEC VT220 Terminal on her desk
Admiral Grace Hopper in her office with a DEC VT220 Terminal on her desk

The Rise and Rise of Software Terminals

Starting in the mid 1980’s, dedicated Terminal devices gradually started to be replaced by general purpose computers that were rapidly becoming more affordable, popular, and powerful. Many early PCs and other computers of the ’80s had Terminal applications that could open a connection to the PC’s RS-232 serial port and exchange data with whatever was listening on the other end of the connection.

As general-purpose computers grew in sophistication, the Graphical User Interface (GUI) arrived and introduced a whole new world of simultaneously running applications, including Terminal applications.

But a problem arose: How would a Terminal application speak to another Command-Line application running on the same machine? And how would you attach a physical serial cable between the two apps running on the same computer?

Enter, the Pseudo Terminal (PTY)

In the *NIX world, this problem was solved by the introduction of the Pseudo Terminal (PTY).

The PTY virtualizes a computer’s serial communications hardware, exposing “master” and “slave” pseudo-devices: Terminal apps connect to a master pseudo-device; Command-Line applications (e.g. shells like Cmd, PowerShell, and bash) connect to a slave pseudo-device. When the Terminal client sends text and/or control commands (encoded as text) to the master, the text is relayed along to the associated “slave”. Text emitted by the application is sent to the slave and is then routed back to the master and thus to the Terminal. Data is always sent/received asynchronously.

Terminal to/from PTY to/from App/Shell
Terminal PTY App/Shell

Importantly, the “slave” pseudo-device emulates the behavior of a physical Terminal device and converts command characters into POSIX signals. For example, if a user types CTRL+C into the Terminal, the ASCII value of CTRL+C (0x03) is sent via the master. When received by the slave, the 0x03 value is removed from the input stream and a SIGINT signal is generated.

This PTY infrastructure is used extensively by *NIX Terminal applications, text pane managers (like screen, tmux), etc. Such apps call openpty() which returns a pair of file descriptors (fd) for the PTY’s master and slave. The app can then fork/exec the child Command-Line application (e.g. bash), which uses its slave fds to listen and return text to the attached Terminal.

This mechanism allows Terminal applications to “talk” directly to Command-Line applications running locally in the same way as the Terminal would talk with a remote Computer via a serial/network connection.

What, no Windows Pseudo Console?

So, as we discussed in the previous post in this series – Inside the Windows Console – while the Windows Console is conceptually similar to the traditional *NIX Terminal, it differs in several key ways, especially at its lowest-levels which can cause problems for developers of Windows Command-Line apps, 3rd-party Terminals/Consoles, and server apps:

  1. Windows lacks a PTY infrastructure: When the user launches a Command-Line app (e.g. Cmd, PowerShell, wsl, ipconfig, etc.), Windows itself “hooks up” a new or existing Console instance to the app
  2. Windows obstructs 3rd party Consoles and Server Apps: Windows (currently) does not provide Terminals a way to supply the communication pipes via which it wants to communicate with a Command-Line app. 3rd party Terminals are forced to create an off-screen Console, and to send it user-input and scrape its output, redrawing the output on the 3rd party Console’s own display!
  3. Only Windows has a Console API: Windows Command-Line apps rely on the Win32 Console API which reduces code portability because every other platform “speaks text/VT” rather than calling APIs
  4. Windows Command-Line Remoting is substandard: Windows’ Command-Line apps’ dependence on Console API significantly impedes interop & remoting scenarios

What to do?

We’ve heard from many, many developers, who’ve frequently requested a PTY-like mechanism in Windows – especially those who created and/or work on ConEmu/Cmder, Console2/ConsoleZ, Hyper, VSCode, Visual Studio, WSL, Docker, and OpenSSH.

Well, we finally did it: We created a Pseudo Console for Windows:

Welcome, to the Windows Pseudo Console (ConPTY)

Since taking ownership of the Console ~4 years ago, the Console Team has been busy overhauling the Windows Console & Command-Line internals. While doing so, we regularly and carefully considered the issues described above and many other related asks and issues. But the internals weren’t in the right shape to make a Pseudo Console feasible … until now!

Windows’ new Pseudo Console (ConPTY) infrastructure, API, and several other supporting changes will remedy/facilitate an entire class of issues … without breaking or damaging backward compatibility for existing command-line applications!

The new Win32 ConPTY API (formal docs to follow soon) is now available in recent Windows 10 Insider builds and corresponding Windows 10 Insider Preview SDK, and will ship in the next major release of Windows 10 (due sometime in fall/winter 2018).

Console/ConHost’s Architecture

To understand ConPTY, we have to revisit the architecture of Windows Console … or more accurately … ConHost!

It’s important to understand that while ConHost implements what you see and know as the Windows Console application itself, ConHost also contains and implements most of Windows’ Command-Line infrastructure! From now on, however, ConHost also becomes a true “Console Host”, supporting all Command-Line applications and/or GUI applications that communicate with Command-Line applications!

How? Why? What? Let’s dig in some more:

Here’s a high-level view of the internal architecture of Console/ConHost:

Console Architecture including the ConPTY

Compared to the architecture we outlined in the previous “Console Internals” post in this series, ConHost now contains a few additional modules for handling VT and a new ConPTY module that implements the public API:

  • ConPTY API: The new Win32 ConPTY API provides a mechanism that is similar to the POSIX PTY model, but in a Windows-relevant manner
  • VT Interactivity: Receives incoming UTF-8 encoded text, converts each displayable text character into the corresponding INPUT_RECORD, and stores them in the Input Buffer. It also handles control sequences such as 0x03 (CTRL+C) converting them into KEY_EVENT_RECORDS that will effect the corresponding control action
  • VT Renderer: Generates the VT sequences necessary to move the cursor and render the text and styling in regions of the Output Buffer that have changed since the previous frame

Okay, but what does this actually mean?

How Do Windows Command-Line Applications Work?

To better understand the impact of the new ConPTY infrastructure, let’s consider for a moment how Windows Console and Command-Line applications have worked up until now.

Whenever a user launches a Command-Line application like Cmd, PowerShell, or ssh, Windows creates a new Win32 process into which it loads the app’s executable binary file, and any dependencies (resources or libraries).

The newly created process usually inherits the stdin and stdout handles from its parent. If the parent was a Windows GUI process, there are no stdin and stdout handles and so Windows will spin up and attach the new app to a new Console instance. Communications between Command-Line apps and their Console are transported via ConDrv.

For example, if launched from a non-elevated PowerShell instance, the new app process will inherit its parent’s stdin/stdout handles and will therefore receive input from and emit output to the same Console as the parent.

There is a little “hand-waving” going on here as there are cases where Command-Line apps are launched attached to a new Console instance, especially for security reasons, but the cases described above are generally true. Ultimately, when a Command-Line app/shell is launched, Windows connects it to a Console (ConHost.exe) instance via ConDrv:

Console architecture in Win10 1803

How does ConHost work?

Whenever a Command-Line application is executed, Windows will connect the app to a new or existing ConHost instance. The app and its Console instance are connected via the kernel-mode Console Driver (ConDrv) which sends/receives IOCTL messages containing serialized API call requests and/or text data.

Historically, as outlined in prior posts, ConHost’s job today is a relatively simple one:

  • The user generates input via keyboard/mouse/pen/touch which is converted into KEY_EVENT_RECORD or MOUSE_EVENT_RECORD and stored in the Input Buffer
  • The Input Buffer is drained one record at a time and performs the requested input action like draw text on screen, move cursor, copy/paste text, etc. Many of these actions result in the Output Buffer’s contents being changed. These changed regions are recorded by ConHost’s state engine
  • Each frame, the Console renders the OutputBuffer’s changed regions to the display

When a Command-Line app calls Windows Console APIs, the API calls are serialized into IOCTL messages and sent via the ConDrv driver. ConDrv then delivers the IOCTL messages to the attached Console, which decodes and executes the requested API call. Return/output values are serialized back into an IOCTL message and sent back to the app via ConDrv.

ConHost – Investing in yesterday for tomorrow

Microsoft tries, wherever possible, to maintain backward compatibility with existing apps/tools. This is especially true in the Command-Line world. In fact, 32-bit editions of Windows 10 can still run many/most “Win16” 16-bit Windows apps and executables!

As mentioned above, one of ConHost’s key roles is to provide services to Command-Line apps that it hosts, especially legacy apps that call and rely on the Win32 Console API. ConHost now offers some new services:

  • Seamlessly provide PTY-like infrastructure for communication with modern Consoles and Terminals
  • Modernizes legacy/traditional Command-Line Apps
    • Receives & converts UTF-8 encoded text/VT into input records (as if typed by user)
    • Executes Console API calls for the app it’s hosting, updating its “Output Buffer” accordingly
    • Renders changed regions of the output buffer as UTF-8 encoded text/VT

Below is an example of a modern Console app talking via a ConPTY ConHost to a Command-Line app

ConPty bridging Traditional and Modern Command-Line apps

In this new model:

  1. Console:
    1. Creates its own communication pipes
    2. Calls the ConPTY API to create a ConPTY causing Windows to spin up a ConHost instance connected to the other end of the pipes
    3. Creates an instance of the Command-Line app (e.g. PowerShell) attached to ConHost as usual
  2. ConHost:
    1. Reads UTF-8 encoded text/VT input and converts into INPUT_RECORD that are sent to the Command-Line app
    2. Executes API calls from the Command-Line app which may modify the contents of the Output Buffer
    3. Renders changes in its Output Buffer as UTF-8 encoded text/VT and sends the resulting text to its Console
  3. Command-Line app:
    1. Runs as usual, reading input and calling Console APIs without any knowledge that its ConPTY ConHost is translating its input/output from/to UTF-8 encoded text/VT!

The latter point is important! When a legacy Command-Line app uses a Console API like WriteConsoleOutput(...), the specified text is written to the attached ConHost’s Output Buffer. Periodically, ConHost renders changed areas of the Output Buffer as text/VT which is sent via stdout back to the Console.

Ultimately, this means that even traditional Command-Line apps “speak text/VT” externally, without requiring any changes!

Using the new ConPTY infrastructure, 3rd party Consoles can now communicate directly with modern and traditional Command-Line applications, and speak text/VT with all of them.

Remoting Windows Command-Line Applications

The mechanism above works great on a single machine, but also helps when you interact with, for example, a PowerShell instance running on a remote Windows machine or in a container

To run Command-Line applications remotely (i.e. on remote machines, servers, or in containers), there is a challenge: Command-Line apps running on remote machines communicate with a local ConHost instance because IOCTL messages are not designed for use over a network connection. So how does input from a Console running on your client machine get to the remote machine, and how does output from the app running on the remote machine get back to your client Console? Further, what if you’re running a Linux or Mac machine that has Terminals, but not Windows-compatible Consoles, and don’t understand how Windows Console works?

So, to remotely operate a Windows machine we need a communications broker of some kind – one that can transparently serialize data across some form of network connection and manage app instance lifetime, etc.

Something like ssh, perhaps?

Thankfully, OpenSSH was recently ported to Windows and added as a Windows 10 optional feature. PowerShell Core has also adopted ssh as one of its supported PowerShell Core Remoting protocols. And for those who’ve invested in Windows PowerShell, Windows PowerShell Remoting is still a viable option.

Let’s consider how OpenSSH for Windows allows us to remotely operate Windows Command-Line shells and apps today:

Command-Line Remoting Before ConPTY

Currently, OpenSSH involves some unwanted convolutions:

  1. The user:
    1. Runs the ssh client and Windows attaches a Console instance as usual
    2. Types into the Console which sends keystrokes to the ssh clent
  2. The ssh client:
    1. Reads input as bytes of text data
    2. Sends the text data via the network to the listening sshd service
  3. The sshd service has to jump through several hoops:
    1. Launches the default shell (i.e. Cmd) which causes Windows to spawn & connect a new Console instance
    2. Finds & attaches itself to the Cmd instance’s Console
    3. Moves Console off-screen (and/or hides it)
    4. Sends input data received from ssh client to the off-screen Console as input
  4. The cmd instance operates as it always has:
    1. Gathers input delivered by the sshd service
    2. Does work
    3. Calls Console APIs to emit/style text, move the cursor, etc.
  5. The attached [off-screen] Console:
    1. Executes the API calls, updating its output buffer
  6. The sshd service:
    1. Scrapes the off-screen Console’s output buffer, finds differences, encodes them into text/VT and sends them back to …
  7. The ssh client which sends the text back to …
  8. The Console, which draws the text on the screen

Fun, right? No, it’s not! There’s a lot that can and does go wrong, especially in the process of simulating and sending user-input and scraping the output buffer to/from the off-screen Console. This results in instability, crashes, data corruption, excessive power consumption, etc. Further, not all apps do the work to scrape text properties as well as text itself, which results in text formatting being lost, and remoted applications’ text being “monochromatized”!

Remoting Using Modern ConHost and ConPTY

Surely we can do better than this? Yes, yes we can – let’s make a few architectural changes and use our new ConPTY:

Command-Line Remoting With ConPTY

In the diagram above, we can see:

  1. The user:
    1. Runs the ssh client and Windows attaches a Console instance as usual
    2. Types into the Console which sends keystrokes to the ssh clent
  2. The ssh client:
    1. Reads input as bytes of text data
    2. Sends the text data via the network to the listening sshd service
  3. The sshd service:
    1. Creates stdin/stdout pipes
    2. Calls the ConPTY API to create a ConPTY
    3. Launches instance of Cmd attached to the other end of the ConPTY. Windows spins-up and attaches a new ConHost instance
  4. The cmd instance operates as it always has:
    1. Gathers input
    2. Does work
    3. Calls Console APIs to emit/style text, move the cursor, etc.
  5. The ConPTY ConHost instance:
    1. Executes the API calls, updating its output buffer
    2. Renders changed regions of the output buffer as UTF-8 encoded text/VT which is sent back to the Console/Terminal via ssh

The ConPTY-enabled approach above is clearly much cleaner and simpler for the sshd service. The only Windows Console API calls are being executed entirely within a Command-Line app’s ConHost instance which converts any visible changes into text/VT: Nothing ConHost is connected to need know that the app its hosting calls Console APIs rather than generating text/VT itself!

We think you’ll agree that this new ConPTY remoting mechanism results in an elegant, consistent, simpler architecture. Combined with the powerful features built into ConHost, supporting legacy apps, and rendering changes caused by apps calling Console APIs into text/VT, the new ConHost and ConPTY infrastructure helps us carry the past into the future.

The ConPTY API and how to use it

The ConPTY API is available in the current Windows 10 Insider Preview SDK. By now, I am sure you’re itching to see some code 😉

Let’s take a look at the API declarations:

// Creates a "Pseudo Console" (ConPTY).
HRESULT WINAPI CreatePseudoConsole(
                                _In_ COORD size,        // ConPty Dimensions
                                _In_ HANDLE hInput,     // ConPty Input
                                _In_ HANDLE hOutput,    // ConPty Output
                                _In_ DWORD dwFlags,     // ConPty Flags
                                _Out_ HPCON* phPC);     // ConPty Reference

// Resizes the given ConPTY to the specified size, in characters.
HRESULT WINAPI ResizePseudoConsole(_In_ HPCON hPC, _In_ COORD size);

// Closes the ConPTY and all associated handles. Client applications attached 
// to the ConPTY will also terminated. 
VOID WINAPI ClosePseudoConsole(_In_ HPCON hPC);

The ConPTY API above essentially exposes three new functions:

  • CreatePseudoConsole(size, hInput, hOutput, dwFlags, phPC)
    • Creates a pty with dimensions of w columns and h rows of characters using pipes created by the caller:
      • size: Width and Height (in chars) of the ConPTY buffer
      • hInput: For writing input to the PTY, encoded as UTF-8, text/VT sequences
      • hOutput: For reading the output from the PTY, encoded as UTF-8, text/VT sequences
      • dwFlags: Possible values:
        • PSEUDOCONSOLE_INHERIT_CURSOR: The created ConPTY will attempt to inherit the cursor position of the parent Terminal application
      • phPC: handle to a Console reference for the cerated ConPty
    • Returns: Success/failure. On success, phPC contains handle to the new ConPty
  • ResizePseudoConsole(hPC, size)
    • Resizes the given ConPTY’s internal buffer to represent a display of the specified character width and height
  • ClosePseudoConsole(hPC)
    • Closes the ConPTY and all associated handles. Client applications attached to the ConPTY will also terminated, as if they were running in a console window that was closed

Using the ConPTY API

Below is a small code example of how to call the ConPTY API to create a Pseudo Console and attach a Command-Line application to the created ConPTY.

Note: A simple sample illustrating how to use the Pseudo Console API is available here.

    
    // Note: Most error checking removed for brevity.  
    // ...
    
    // Initializes the specified startup info struct with the required properties and
    // updates its thread attribute list with the specified ConPTY handle
    HRESULT InitializeStartupInfoAttachedToConPTY(STARTUPINFOEX* siEx, HPCON hPC)
    {
        HRESULT hr = E_UNEXPECTED;
        size_t size;

        siEx->StartupInfo.cb = sizeof(STARTUPINFOEX);
        
        // Create the appropriately sized thread attribute list
        InitializeProcThreadAttributeList(NULL, 1, 0, &size);
        std::unique_ptr<BYTE[]> attrList = std::make_unique<BYTE[]>(size);
        
        // Set startup info's attribute list & initialize it
        siEx->lpAttributeList = reinterpret_cast<PPROC_THREAD_ATTRIBUTE_LIST>(
            attrList.get());
        bool fSuccess = InitializeProcThreadAttributeList(
            siEx->lpAttributeList, 1, 0, (PSIZE_T)&size);
            
        if (fSuccess)
        {
            // Set thread attribute list's Pseudo Console to the specified ConPTY
            fSuccess = UpdateProcThreadAttribute(
                            lpAttributeList,
                            0,
                            PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
                            hPC,
                            sizeof(HPCON),
                            NULL,
                            NULL);
            return fSuccess ? S_OK : HRESULT_FROM_WIN32(GetLastError());
        }
        else
        {
            hr = HRESULT_FROM_WIN32(GetLastError());
        }
        return hr;
    }
    
    // ...
    
    HANDLE hOut, hIn;
    HANDLE outPipeOurSide, inPipeOurSide;
    HANDLE outPipePseudoConsoleSide, inPipePseudoConsoleSide;
    HPCON hPC = 0;

    // Create the in/out pipes:
    CreatePipe(&inPipePseudoConsoleSide, &inPipeOurSide, NULL, 0);
    CreatePipe(&outPipeOurSide, &outPipePseudoConsoleSide, NULL, 0);

    // Create the Pseudo Console, using the pipes
    CreatePseudoConsole(
        {80, 32}, 
        inPipePseudoConsoleSide, 
        outPipePseudoConsoleSide, 
        0, 
        &hPC);

    // Prepare the StartupInfoEx structure attached to the ConPTY.
    STARTUPINFOEX siEx{};
    InitializeStartupInfoAttachedToConPTY(&siEx, hPC);

    // Create the client application, using startup info containing ConPTY info
    wchar_t* commandline = L"c:\\windows\\system32\\cmd.exe";
    PROCESS_INFORMATION piClient{};
    fSuccess = CreateProcessW(
                    nullptr,
                    commandline,
                    nullptr,
                    nullptr,
                    TRUE,
                    EXTENDED_STARTUPINFO_PRESENT,
                    nullptr,
                    nullptr,
                    &siEx->StartupInfo,
                    &piClient);

    // ...

At this point, cmd.exe is running connected to the ConPTY created by CreatePseudoConsole(). The caller uses the ConPTY’s handles that it created to write and read to/from the Cmd instance. The Pseudo Console can be resized by calling ResizePseudoConsole(), and can be closed by calling ClosePseudoConsole():

Writing to Pseudo Console

Writing input to the ConPTY is simple:

// Input "echo Hello, World!", press enter to have cmd process the command,
//  input an up arrow (to get the previous command), and enter again to execute.
std::string helloWorld = "echo Hello, World!\n\x1b[A\n";
DWORD dwWritten;
WriteFile(hIn, helloWorld.c_str(), (DWORD)helloWorld.length(), &dwWritten, nullptr);

Resizing the Pseudo Console

This scenario shows how to resize the ConPTY:

// Suppose some other async callback triggered us to resize.
//      This call will update the Terminal with the size we received.
HRESULT hr = ResizePseudoConsole(hPC, {120, 30});

Closing the Pseudo Console

Closing the ConPTY couldn’t be simpler:

ClosePseudoConsole(hPC);

Note: Closing the ConPTY will terminate the associated ConHost and any attached clients.

Call To Action!

The introduction of the ConPTY API is perhaps one of the most fundamental, and liberating, changes that’s happened to the Windows Command-Line in several years … if not decades!

We, the Console team, have already ported some of Microsoft’s tools to use the ConPTY API. We’re also working with several teams inside Microsoft (Windows Subsystem for Linux (WSL), Windows Containers, VSCode, Visual Studio, etc.), and with several external parties including @ConEmuMaximus5 – creator of the awesome ConEmu 3rd party Console for Windows.

But we need your help to raise awareness of, and to start adopting the new ConPTY API:

Command-Line Application Developers

If you own and/or maintain an existing traditional Windows Command-Line application, you’re largely off the hook and don’t have much to do: ConHost will do all the work for you – you can continue to depend upon and call the Console API’s as you always have, and your app will work just as it always has, while also benefitting from improved, higher-fidelity experience if operated remotely 😃

But if you’d like to, you can also introduce new VT support gradually or in new feature areas if you wish – the decision is yours.

If, on the other hand you’re currently or are planning on writing new Windows Command-Line applications, we strongly encourage you to consider simply emitting UTF-8 encoded text/VT instead of calling the Windows Console API: “Speaking VT” will give you access to many features that will not be available via the Windows Console API (e.g. 16M RGB True Color support)

3rd Party Console/Service Developers

If you’re a developer working on a stand-alone Console/Terminal app, or are integrating a Console inside of an application, then we strongly encourage you to explore and adopt the new ConPTY API at your earliest convenience: Adopting the ConPTY API (rather than the older off-screen Console mechanism) is likely to eliminate several classes of bugs, while increasing stability, reliability, and performance.

As an example, the VSCode team currently maintains an issue (GitHub #45693) that tracks several issues caused by Windows’ current lack of a Pseudo Console.

Detecting the ConPTY API

The new ConPTY API will be available for the first time in the Autumn/Fall 2018 release of Windows 10.

If you need to support earlier versions of Windows, then you’ll likely need to test at runtime whether the currently running version of Windows supports ConPTY. As with most Win32 API’s an effective way to test if an API is present is to use Runtime Dynamic Linking approach of calling LoadLibrary() & GetProcAddress().

If the currently running version of Windows supports ConPTY, your app can find and call the new ConPTY APIs. If not, you’ll have to revert to the convoluted mechanisms used until now, as outlined above.

Calling ConPTY from languages other than C

The ‘C’ based ConPTY sample above can be found in the Terminal repo’s Samples/ConPTY/EchoCon folder.

In this repo, you’ll also find samples for:

ConPTY Source Code

Since Windows Console and Windows Terminal are now open source, you can also find the source code for ConPTY itself here in the Terminal GitHub repo! 😁

So, where are we?

Another long post … this is getting to be a habit! Once again, if you’ve read and followed the post this far, THANK YOU! 😃

There’s a lot to unpack from the information above, but we feel it is important to understand why we make changes and improvements such as introducing a Pseudo Console API, as well as what we built. Our goals here are to eradicate an entire class of issues and limitations for developers of Console and server apps, and to make developing code for the Windows Command Line infrastructure more powerful, consistent, and fun.

We look forward to hearing from you via Feedback Hub. For more complex problems, please file issues on our Windows Console GitHub Repo. And if you have questions, please ping me on Twitter.

We can’t wait to hear about what you build atop the new Pseudo Console API.

Rich & the Windows Console Team: Team Console

14 comments

Discussion is closed. Login to edit/delete existing comments.

  • Terry Liew 0

    Great work! Unfortunately the example given doesn’t work, keep crashing at CreateProcess() with error code 87 (Parameter is incorrect). Thought the example does deliver the concept, but a working example could be much more helpful, at least, I can see what actually the PTY is sending to me when the console program do some colored extended ascii text printing…

  • Marcel Hendrix 0

    This begs a question: Is it/Will it be possible to connect GUI apps to these pseudo terminals? We could then script these apps in a very easy way (I’m probably overlooking a few issues :-), by logging and playing back key/mouse records. Of course complicated graphics feedback would not render, but most users with the desire to do scripting are aware of that fact already.

    • Rich TurnerMicrosoft employee 0

      You’ve been able to do this in WSL1 for quite some time already 😉

  • Kaz Delphi 0

    Can it be used in Windows 7?

    • Kaz Delphi 0

      What I mean is a program with ConPTY(Forgive me for my English)

  • Yuwei Ba 0

    Great Work!

    I created a tool using this feature which you can record and share your PowerShell sessions just like asciinema.

    Please have a look at PowerSession ! https://ibigbug.online/powersession-initial-release

  • Anton Zhvakin 0

    The great series of articles, thank you a lot!

    But I’ve got a question(don’t know where I should ask): may be I misunderstood something, but if Far Manager uses Console API, why it works differently in modern Windows Terminal comparing to with just console in windows(conhost.exe, am I right?)? I mean Far doesn’t receive some keyboard sequences(e.g. Shift+Enter or context menu button on keyboard, or Ctrl+Backspace) in new Windows Terminal. It looks like it uses ConPTY encoding, but it mustn’t use it, isn’t it? Why is it happening?

    May be my question is stupid, but I really want to understand how it works.

    Thank you in advance.

    • Anton Zhvakin 0

      I’ve read the article some more times and I think I got it. New Windows Terminal handles all input by itself, and then pass it to conhost via text encoding(conpty), and then conhost converts it to console api calls to far.

      But is there any workaround to run far in new windows terminal but without conpty?

  • J.M. Becker 0

    Will this be part of Windows? I’m excited about this, … I’m seriously thinking of joining the MS world from Linux.

  • Andriy Savin 0

    Hello Rich!
    When you’re saying that for new Windows Command-Line applications “we strongly encourage you to consider simply emitting UTF-8 encoded text/VT instead of calling the Windows Console API”. Could you explain how do I “simply emit text/VT” in my command line app? Which set of APIs do I use? I can guess that the app inherits pipe handles from the ConHost, or somehow connects as a “slave” (like on the first diagram). You gave extensive information on the Terminal-to-ConPTY interaction, but no example on App-to-ConPTY interaction. Could you provide some, please?
    Additionally, I’m wondering if there is any support for this modern communication in .Net console API?
    Thanks in advance!

  • Adam Young 0

    Rebirth of the windows command line interface, great effort; have been experimenting with ConPTY’s within a native rlogind service initial experiences are without major issue; shall publish via github.

    This may not be the best place to post, yet one issue i’ve been unable to overcome.
    How does the ConPTY master/creator access the exit-value of the associated shell, as GetExitCodeProcess() on the process handle does not seem to reflect.

    Thanks

    • Rich TurnerMicrosoft employee 0

      Thanks Adam – Glad ConPTY is working for you. Look forward to seeing your rlogind 🙂

      Best place to post issues or ask questions etc. re. Console and Terminal is over on the team’s GitHub repo: https://github.com/microsoft/terminal.

      While you’re there, you could even review the implementation of the ConPTY if you were interested 😉 https://github.com/microsoft/terminal/tree/ae71dce2ca32c62399652ed19ccd9a32c167338d/src/winconpty

      • Adam Young 0

        Hi Rich,

        Appreciate the feedback. Have resolved previous issue and published initial results under https://github.com/adamyg/winxsh.

        For interest, I’m also the maintainer of the native windows Midnight Commander which takes advantage of the recent VTTerm support, also under same github repo.

        Regards, Adam

Feedback usabilla icon