Attach Console with WPF application

Attach Console with WPF application

Attach Console with WPF application

Today I am going to explain Attach Console with WPF application.

Problem: Sometime developer wants to know regarding some of variables value on clients machine while one’s application is running or wants to check execution steps.

Solution: Developer can attach console to see real time execution or use Logger for future use. We will see first concept in action as of now and we will discuss Logger concept some another day.

Let’s have look into code, how could we Attach Console with WPF application!!

In WPF application we will write our below code in App.xaml  and App.xaml.cs

App.xaml code snippet is as below, we will add Startup=”Application_Startup”:

<Application x:Class="AttachConsole.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml" Startup="Application_Startup">
    <Application.Resources>
         
    </Application.Resources>
</Application>

 

App.xaml.cs code snippet is as below:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;

namespace AttachConsole
{
    public partial class App : Application
    {
        [DllImport("kernel32", SetLastError = true)]
        private static extern bool AttachConsole(int dwProcessId);

        [DllImport("user32.dll")]
        private static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll", SetLastError = true)]
        private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

        [STAThread]
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            IntPtr ptr = GetForegroundWindow();
            int u;
            GetWindowThreadProcessId(ptr, out u);
            Process process = Process.GetProcessById(u);
            AttachConsole(process.Id);
        }
    }
}

 

Output for  Attach Console with WPF application:

Attach Console with WPF application
Attach Console with WPF application

 

Hey folks hope you have enjoyed this post and learnt something new concept.