原本是想實現控制檯程序運行時自動全屏,可是隻找到VC下的實現方法(http://www.vckbase.com/bbs/prime/viewprime.asp?id=347)。
其中要使用兩個未公開的Win32 API函數來存取控制檯窗口,這就須要使用動態調用的方法,動態調用中使用的Windows API函數主要有三個,即:Loadlibrary,GetProcAddress和Freelibrary。步驟以下:
1.Loadlibrary:裝載指定DLL動態庫
2.GetProcAddress:得到函數的入口地址
3.Freelibrary:從內存中卸載動態庫
可是C#中是沒有函數指針,沒法直接使用GetProcAddress返回的入口地址。後來找到資料,其實.NET2.0新增了Marshal.GetDelegateForFunctionPointer方法能夠知足這個要求,MSDN裏的解釋是:將非託管函數指針轉換爲委託。
後面的事就簡單啦,我把它編成了一個類來方便調用。

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Text;

usingSystem.Runtime.InteropServices;

namespacefeiyun0112.cnblogs.com

{

publicclassDllInvoke

{

WinAPI

privateIntPtrhLib;

publicDllInvoke(StringDLLPath)

{

hLib=LoadLibrary(DLLPath);

}

~DllInvoke()

{

FreeLibrary(hLib);

}

//將要執行的函數轉換爲委託

publicDelegateInvoke(stringAPIName,Typet)

{

IntPtrapi=GetProcAddress(hLib,APIName);

return(Delegate)Marshal.GetDelegateForFunctionPointer(api,t);

}

}

}
下面是使用的例子:

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Text;

usingSystem.Runtime.InteropServices;

usingfeiyun0112.cnblogs.com;

namespaceConsoleApplication1

{

classProgram

{

WinAPI

publicdelegateboolSetConsoleDisplayMode(IntPtrhOut,intdwNewMode,outintlpdwOldMode);

staticvoidMain(string[]args)

{

DllInvokedll=newDllInvoke("kernel32.dll");

intdwOldMode;

//標準輸出句柄

IntPtrhOut=GetStdHandle(STD_OUTPUT_HANDLE);

//調用WinAPI,設置屏幕最大化

SetConsoleDisplayModes=(SetConsoleDisplayMode)dll.Invoke("SetConsoleDisplayMode",typeof(SetConsoleDisplayMode));

s(hOut,1,outdwOldMode);

Console.WriteLine("********************FullScreenMode********************");

Console.ReadLine();

}

}

}