C 在窗體程式中執行控制台程式並管理其程序

2021-09-01 05:37:22 字數 3132 閱讀 1327

執行環境

public

void

frpstart()

p =newprocess};

//監聽控制台的輸出

p.outputdatareceived +=

newdatareceivedeventhandler

((sender, e)

=>})

; p.

start()

; p.

beginoutputreadline()

;}

注意上面新建程序的引數useshellexecute = false,如果這裡設定為false,那麼filename這個引數中控制台程式的只能用絕對路徑,即workingdirectory引數無效。

如果不設定useshellexecute為false,則無法重定向輸出。

如果useshellexecute = true,則filename可以直接使用控制台程式的名字,前提是workingdirectory裡面的路徑是正確的。

接下來就是關於控制台程序的管理了,如果僅僅按照上面編寫,程式關閉之後控制台程式會殘留在程序中。

由於無法將控制台程式當成執行緒執行,因此需要乙個東西用來將控制台程序與主程式關聯在一起。

這裡參考了這篇帖子。

public

void

frpstart()

....

....

..p.

start()

; p.

beginoutputreadline()

;//將其加入job

//job的初始化省略了,可以在建構函式初始化,使用單例模式

job.

addprocess

(p.handle);}

private

static

void

killprocess

(process p)

}catch

(exception e)

}

public

class

job: idisposable

; var extendedinfo =

newjobobject_extended_limit_information

;try",

marshal.

getlastwin32error()

));}

finally}}

public bool addprocess

(intptr processhandle)

return succ;

}public bool addprocess

(int processid)

#region idisposable

private bool disposed;

public

void

dispose()

protected virtual void

dispose

(bool disposing)

if(handle != intptr.zero)}~

job(

) #endregion

#region interop

[dllimport

("kernel32.dll"

, charset = charset.unicode)

]private

static extern intptr createjobobject

(intptr a, string lpname);[

dllimport

("kernel32.dll"

, setlasterror =

true)]

private

static extern bool setinformationjobobject

(intptr hjob, jobobjectinfotype infotype, intptr lpjobobjectinfo, uint32 cbjobobjectinfolength);[

dllimport

("kernel32.dll"

, setlasterror =

true)]

private

static extern bool assignprocesstojobobject

(intptr job, intptr process);[

dllimport

("kernel32.dll"

, setlasterror =

true)]

[return

:marshalas

(unmanagedtype.bool)

]private

static extern bool closehandle

(intptr hobject)

; #endregion

}#region helper classes

[structlayout

(layoutkind.sequential)

]struct io_counters

[structlayout

(layoutkind.sequential)

]struct jobobject_basic_limit_information

[structlayout

(layoutkind.sequential)

]public struct security_attributes

[structlayout

(layoutkind.sequential)

]struct jobobject_extended_limit_information

public

enum jobobjectinfotype

#endregion

c 控制台程式靜默執行

class program region 隱藏黑色視窗 dllimport user32.dll entrypoint showwindow setlasterror true static extern bool showwindow intptr hwnd,uint ncmdshow dllim...

控制台程式裡呼叫控制台程式

現在遇到這麼個問題,我想用控制台裡呼叫控制台程式來實現多文字。但是在控制台裡呼叫控制台程式時,它不是出現新的控制台視窗顯示,而是已有的控制台裡顯示呼叫的程式,system d code 練習 jjplace editor debug editor.exe winexec d code 練習 jjpl...

centos 後台執行C 控制台程式

1.nohup nohup 無疑是我們首先想到的辦法。顧名思義,nohup 的用途就是讓提交的命令忽略 hangup 訊號。讓我們先來看一下 nohup 的幫助資訊 nohup 1 user commands nohup 1 name nohup run a command immune to ha...