programing

WPF 어플리케이션에서 콘솔로 출력되지 않았습니까?

iphone6s 2023. 4. 12. 21:54
반응형

WPF 어플리케이션에서 콘솔로 출력되지 않았습니까?

사용하고 있다Console.WriteLine()매우 간단한 WPF 테스트애플리케이션에서 어플리케이션을 실행해도 콘솔에 아무것도 입력되지 않습니다.여기서 무슨 일이 일어나고 있는지 아는 사람 있나요?

VS 2008에서 WPF 어플리케이션을 생성하여 단순히 추가함으로써 재현할 수 있습니다.Console.WriteLine("text")어디서든 실행할 수 있습니다.좋은 생각 있어요?

지금 당장 필요한 건Console.WriteLine()log4net이나 다른 로깅 솔루션을 사용할 수 있다는 것은 알고 있습니다만, 이 어플리케이션에는 그다지 많은 기능이 필요하지 않습니다.

편집: 기억해 두었어야 했는데Console.WriteLine()콘솔 어플리케이션용입니다.아, 그럼 바보같은 질문은 하지 마세요.그렇죠?-) 저는 그냥System.Diagnostics.Trace.WriteLine()DebugView를 참조해 주세요.

사용할 수 있습니다.

Trace.WriteLine("text");

그러면 Visual Studio의 "출력" 창에 출력됩니다(디버깅 시).

Diagnostics 어셈블리가 포함되어 있는지 확인합니다.

using System.Diagnostics;

Properties(프로퍼티)를 오른쪽 클릭하여 Application(애플리케이션) 탭을 클릭하고 Output Type(출력 유형)을 Console Application(콘솔 애플리케이션)으로 변경합니다.콘솔 애플리케이션)도 표시됩니다(애플리케이션 출력 유형이 Console Application(콘솔 애플리케이션)으로 전환된 경우에도 WPF 애플리케이션은 정상적으로 실행됩니다).

콘솔을 실제로 호출하기 전에 콘솔 창을 수동으로 만들어야 합니다.메서드를 씁니다.그러면 프로젝트 유형을 변경하지 않고 콘솔이 정상적으로 동작합니다(WPF 어플리케이션에서는 동작하지 않습니다).

다음은 ConsoleManager 클래스의 전체 소스 코드 예제이며, 프로젝트 유형에 관계없이 Console Manager 클래스를 사용하여 콘솔을 활성화/비활성화하는 방법을 보여 줍니다.

다음 수업에서, 당신은 그냥 글을 쓰면 됩니다.ConsoleManager.Show()에 대한 어떤 요구하기 전에Console.Write...

[SuppressUnmanagedCodeSecurity]
public static class ConsoleManager
{
    private const string Kernel32_DllName = "kernel32.dll";

    [DllImport(Kernel32_DllName)]
    private static extern bool AllocConsole();

    [DllImport(Kernel32_DllName)]
    private static extern bool FreeConsole();

    [DllImport(Kernel32_DllName)]
    private static extern IntPtr GetConsoleWindow();

    [DllImport(Kernel32_DllName)]
    private static extern int GetConsoleOutputCP();

    public static bool HasConsole
    {
        get { return GetConsoleWindow() != IntPtr.Zero; }
    }

    /// <summary>
    /// Creates a new console instance if the process is not attached to a console already.
    /// </summary>
    public static void Show()
    {
        //#if DEBUG
        if (!HasConsole)
        {
            AllocConsole();
            InvalidateOutAndError();
        }
        //#endif
    }

    /// <summary>
    /// If the process has a console attached to it, it will be detached and no longer visible. Writing to the System.Console is still possible, but no output will be shown.
    /// </summary>
    public static void Hide()
    {
        //#if DEBUG
        if (HasConsole)
        {
            SetOutAndErrorNull();
            FreeConsole();
        }
        //#endif
    }

    public static void Toggle()
    {
        if (HasConsole)
        {
            Hide();
        }
        else
        {
            Show();
        }
    }

    static void InvalidateOutAndError()
    {
        Type type = typeof(System.Console);

        System.Reflection.FieldInfo _out = type.GetField("_out",
            System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

        System.Reflection.FieldInfo _error = type.GetField("_error",
            System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

        System.Reflection.MethodInfo _InitializeStdOutError = type.GetMethod("InitializeStdOutError",
            System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

        Debug.Assert(_out != null);
        Debug.Assert(_error != null);

        Debug.Assert(_InitializeStdOutError != null);

        _out.SetValue(null, null);
        _error.SetValue(null, null);

        _InitializeStdOutError.Invoke(null, new object[] { true });
    }

    static void SetOutAndErrorNull()
    {
        Console.SetOut(TextWriter.Null);
        Console.SetError(TextWriter.Null);
    }
} 

오래된 투고입니다만, Visual Studio의 WPF 프로젝트에서 Output에 출력하려고 하는 경우는, 다음의 방법이 있습니다.

다음 내용 포함:

using System.Diagnostics;

그 후:

Debug.WriteLine("something");

존 라이데그렌이 계속해서 그 아이디어를 부정하고 있지만, 브라이언은 옳다.Visual Studio에서 방금 작업했어요.

WPF 응용 프로그램을 클리어하기 위해 기본적으로 콘솔창은 생성되지 않습니다.

WPF 응용 프로그램을 만든 다음 출력 유형을 "콘솔 응용 프로그램"으로 변경해야 합니다.프로젝트를 실행하면 WPF 창이 앞에 있는 콘솔 창이 나타납니다.

외관상으로는 그다지 예쁘지 않지만, 커맨드 라인에서 앱을 실행하고 피드백을 받고 싶기 때문에 도움이 되었습니다.그리고 특정 커맨드 옵션에서는 WPF 창을 띄웁니다.

명령줄 리다이렉션을 사용하면 콘솔용 출력을 확인할 수 있습니다.

예를 들어 다음과 같습니다.

C:\src\bin\Debug\Example.exe > output.txt

을 든든내 all all all all will will will will will will will will will will will will 。output.txtfilename을 클릭합니다.

콘솔을 사용합니다.출력 창에서 사용하는 WriteLine()...

Brian의 솔루션은 WPF 응용 프로그램을 시작할 때 항상 콘솔을 여는 입니다.콘솔 출력을 동적으로 이노블로 하는 경우(예를 들어 특정 명령줄 인수를 사용하여 기동했을 경우에만) 콜AttachConsole:

[DllImport("kernel32.dll")]
static extern bool AttachConsole(uint dwProcessId);

const uint ATTACH_PARENT_PROCESS = 0x0ffffffff;

그런 다음 콘솔에 쓰기를 시작할 때 다음을 수행합니다.

AttachConsole(ATTACH_PARENT_PROCESS);
Console.WriteLine("Hello world!");
Console.WriteLine("Writing to the hosting console!");

나는 해결책을 만들어냈다. varius post의 정보를 섞었다.

레이블과 텍스트 상자 하나가 포함된 양식입니다.콘솔 출력이 텍스트 상자로 리디렉션됩니다.

다음 세 가지 공개 메서드를 구현하는 ConsoleView라는 클래스가 너무 많습니다.Show(), Close() 및 Release().마지막은 콘솔을 열어 두고 닫기 버튼을 활성화하여 결과를 표시하는 것입니다.

폼은 FrmConsole이라고 불립니다.다음은 XAML과 c# 코드입니다.

용도는 매우 간단합니다.

ConsoleView.Show("Title of the Console");

콘솔을 엽니다.용도:

System.Console.WriteLine("The debug message");

콘솔에 출력 텍스트용.

용도:

ConsoleView.Close();

의 경우 콘솔을 닫습니다.

ConsoleView.Release();

콘솔을 열어 두고 닫기 버튼을 활성화합니다.

XAML

<Window x:Class="CustomControls.FrmConsole"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:CustomControls"
    mc:Ignorable="d"
    Height="500" Width="600" WindowStyle="None" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Topmost="True" Icon="Images/icoConsole.png">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="40"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="40"/>
    </Grid.RowDefinitions>
    <Label Grid.Row="0" Name="lblTitulo" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center" FontFamily="Arial" FontSize="14" FontWeight="Bold" Content="Titulo"/>
    <Grid Grid.Row="1">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="10"/>
        </Grid.ColumnDefinitions>
        <TextBox Grid.Column="1" Name="txtInner" FontFamily="Arial" FontSize="10" ScrollViewer.CanContentScroll="True" VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible" TextWrapping="Wrap"/>
    </Grid>
    <Button Name="btnCerrar" Grid.Row="2" Content="Cerrar" Width="100" Height="30" HorizontalAlignment="Center" HorizontalContentAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center"/>
</Grid>

창 코드:

partial class FrmConsole : Window
{
    private class ControlWriter : TextWriter
    {
        private TextBox textbox;
        public ControlWriter(TextBox textbox)
        {
            this.textbox = textbox;
        }

        public override void WriteLine(char value)
        {
            textbox.Dispatcher.Invoke(new Action(() =>
            {
                textbox.AppendText(value.ToString());
                textbox.AppendText(Environment.NewLine);
                textbox.ScrollToEnd();
            }));
        }

        public override void WriteLine(string value)
        {
            textbox.Dispatcher.Invoke(new Action(() =>
            {
                textbox.AppendText(value);
                textbox.AppendText(Environment.NewLine);
                textbox.ScrollToEnd();
            }));
        }

        public override void Write(char value)
        {
            textbox.Dispatcher.Invoke(new Action(() =>
            {
                textbox.AppendText(value.ToString());
                textbox.ScrollToEnd();
            }));
        }

        public override void Write(string value)
        {
            textbox.Dispatcher.Invoke(new Action(() =>
            {
                textbox.AppendText(value);
                textbox.ScrollToEnd();
            }));
        }

        public override Encoding Encoding
        {
            get { return Encoding.UTF8; }

        }
    }

    //DEFINICIONES DE LA CLASE
    #region DEFINICIONES DE LA CLASE

    #endregion


    //CONSTRUCTORES DE LA CLASE
    #region CONSTRUCTORES DE LA CLASE

    public FrmConsole(string titulo)
    {
        InitializeComponent();
        lblTitulo.Content = titulo;
        Clear();
        btnCerrar.Click += new RoutedEventHandler(BtnCerrar_Click);
        Console.SetOut(new ControlWriter(txtInner));
        DesactivarCerrar();
    }

    #endregion


    //PROPIEDADES
    #region PROPIEDADES

    #endregion


    //DELEGADOS
    #region DELEGADOS

    private void BtnCerrar_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }

    #endregion


    //METODOS Y FUNCIONES
    #region METODOS Y FUNCIONES

    public void ActivarCerrar()
    {
        btnCerrar.IsEnabled = true;
    }

    public void Clear()
    {
        txtInner.Clear();
    }

    public void DesactivarCerrar()
    {
        btnCerrar.IsEnabled = false;
    }

    #endregion  
}

ConsoleView클래스의 코드

static public class ConsoleView
{
    //DEFINICIONES DE LA CLASE
    #region DEFINICIONES DE LA CLASE
    static FrmConsole console;
    static Thread StatusThread;
    static bool isActive = false;
    #endregion

    //CONSTRUCTORES DE LA CLASE
    #region CONSTRUCTORES DE LA CLASE

    #endregion

    //PROPIEDADES
    #region PROPIEDADES

    #endregion

    //DELEGADOS
    #region DELEGADOS

    #endregion

    //METODOS Y FUNCIONES
    #region METODOS Y FUNCIONES

    public static void Show(string label)
    {
        if (isActive)
        {
            return;
        }

        isActive = true;
        //create the thread with its ThreadStart method
        StatusThread = new Thread(() =>
        {
            try
            {
                console = new FrmConsole(label);
                console.ShowDialog();
                //this call is needed so the thread remains open until the dispatcher is closed
                Dispatcher.Run();
            }
            catch (Exception)
            {
            }
        });

        //run the thread in STA mode to make it work correctly
        StatusThread.SetApartmentState(ApartmentState.STA);
        StatusThread.Priority = ThreadPriority.Normal;
        StatusThread.Start();

    }

    public static void Close()
    {
        isActive = false;
        if (console != null)
        {
            //need to use the dispatcher to call the Close method, because the window is created in another thread, and this method is called by the main thread
            console.Dispatcher.InvokeShutdown();
            console = null;
            StatusThread = null;
        }

        console = null;
    }

    public static void Release()
    {
        isActive = false;
        if (console != null)
        {
            console.Dispatcher.Invoke(console.ActivarCerrar);
        }

    }
    #endregion
}

나는 이 결과가 유익하기를 바란다.

언급URL : https://stackoverflow.com/questions/160587/no-output-to-console-from-a-wpf-application

반응형