In WPF, use the console to output log information

Original link:

In WPF, use the console to output log information_SaylorLee's blog - CSDN blog_wpf print log

This method is only effective when VS debugging is attached, and running directly (whether DEBUG compilation or RELEASE compilation) has no effect.

core code

 public class ConsoleLogHelper
    {
    
    

        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("kernel32", CharSet = CharSet.Auto)]
        internal static extern bool AllocConsole();

        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("kernel32", CharSet = CharSet.Auto)]
        internal static extern bool FreeConsole();

        /// <summary>
        /// 在程序启动时,执行一次即可
        /// </summary>
        public static void OpenConsole()
        {
    
    
            try
            {
    
    
                var consoleTitle = "App Runtime Log";
                AllocConsole();
                Console.BackgroundColor = ConsoleColor.Black;

                Console.CursorVisible = false;
                Console.Title = consoleTitle;
            }
            catch (Exception)
            {
    
    
                throw;
            }
        }


        /// <summary>
        /// 该方法只在退出程序时,调用
        /// </summary>
        public static void CloseConsole()
        {
    
    
            FreeConsole();
        }

        public static void WriteLine(string msg)
        {
    
    
            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            Console.WriteLine(msg);
            Console.ForegroundColor = ConsoleColor.White;
        }
        public static void WriteLineError(string msg)
        {
    
    
            Console.ForegroundColor = ConsoleColor.Red;
            WriteLine(msg);
        }

        public static void WriteLineError(Exception ex)
        {
    
    
            WriteLineError(ex.Message);
        }

        public static void WriteLineInfo(string msg)
        {
    
    
            Console.ForegroundColor = ConsoleColor.Cyan;
            WriteLine(msg);
        }

    }

In WPF, use the console to output log information_SaylorLee's blog - CSDN blog_wpf print log

WPF uses Console.Write to print information to the console window - Xie Chengxu - Blog Park

Guess you like

Origin blog.csdn.net/lj22377/article/details/127421269