簡體   English   中英

在C#中輸出對Label的命令行響應

[英]Output Command Line response to Label in C#

編輯 :感謝lunarquaker的幫助。 以下是已批准答案中帶有setLabel方法的當前工作代碼。 變量“ sender”和“ e”被更改為“ sender2”和“ e2”,因為這是在按鈕內部發生的,該按鈕已經在使用“ sender”和“ e”變量

        Process process = new Process();
        string command = @"/K C:\ti\uniflash_3.4\uniflashCLI.bat -config C:\users\david\desktop\twinHM\TTwin9V.usf -setOptions com=3 -operations program";
        process.StartInfo.FileName = "CMD.exe";
        process.StartInfo.Arguments = command;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.CreateNoWindow = true;
        process.OutputDataReceived += (sender2, e2) => setLabelText(lblCMDResponse, e2.Data);
        lblCMDResponse.Visible = true;
        process.Start();
        process.BeginOutputReadLine();

和setLabel方法

    private void setLabelText(Label label, string text)
    {
        if (label.InvokeRequired)
        {
            label.Invoke((System.Action)(() => setLabelText(label, text)));
        }
        else
        {
            label.Text = text;
        }
    }

我正在編寫一個C#應用程序,該程序處理創建參數文件,然后將該文件和二進制文件刷新到微處理器。 在后端,我實際上是在使用uniflash命令行工具進行刷新,但是我想對用戶隱藏任何看起來“計算機化”或“技術化”的內容(因為我認為這會嚇到他們)我想在運行時隱藏CMD,並且出於相同的原因,我不想打開並顯示控制台,但是我想從CMD中逐行獲取響應,然后將該響應寫到一個標簽上,我的用戶將會看到。 我希望該標簽在大多數情況下變化太快,以至於用戶無法閱讀它,但是它會提醒他們任何問題(主要是確保設備已插入並且開關設置為FTDI)

我在弄清楚如何做到這一點時遇到了麻煩。

到目前為止,這是我在該部分中所做的:

Process process = new Process();
string command = @"/K C:\ti\uniflash_3.4\uniflashCLI.bat -config C:\users\david\desktop\twinHM\TTwin9V.usf -setOptions com=3 -operations program";
process.StartInfo.FileName = "CMD.exe";
process.StartInfo.Arguments = command;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();

我知道在開始之前,我需要訂閱OutputDataRecieved事件並將其設置為我的標簽。 我以該線程為例,但是當我嘗試將其插入時,它抱怨(sender,e)部分,因為這些不是它可以找到的變量。 我也認識到Console.WriteLine(stuff)與設置標簽的text屬性並不完全相同,而且我不知道如何使用最新消息連續更新該標簽

我將繼續閱讀OutputDataReceived的文檔,以了解是否可以了解我在哪里做錯了(除非有人在這里回答),但是我真的很感謝將標簽附加到標簽上的任何幫助(或者實際上很簡單)將輸出設置為text屬性?)

也許我缺少了一些東西。 用InvokeRequired檢查創建setLabelText方法不起作用嗎? 首先,您對OutputDataReceived事件的訂閱將其與設置標簽的方法相關聯:

process.OutputDataReceived += (sender, e) => setLabelText(myLabel, e.Data);

然后,更新標簽的方法:

    private void setLabelText(Label label, string text)
    {
        if (label.InvokeRequired)
        {
            label.Invoke((System.Action)(() => setLabelText(label, text)));
        }
        else
        {
            label.Text = text;
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM