Public Declare Function AttachConsole Lib "kernel32.dll" (ByVal ProcessID As Integer) As Boolean
一个参数,就是进程ID。要实现附着,必须得提供其进程ID,那么就需要经过非常复杂的过程。那么,现在请大家再次鄙视下微软,因为这个 API 函数还留有另外一个常量:ATTACH_PARENT_PROCESS(十进制值:-1),能够实现直接附着到父进程(即调用程序的进程上)。
那么,现在对上例教程的代码稍加修改,就可以得到:
Public Declare Function AllocConsole Lib "kernel32.dll" () As Long
Public
Declare Function FreeConsole Lib "kernel32.dll" () As Long
Public Declare
Function SetConsoleTitle Lib "kernel32.dll" Alias "SetConsoleTitleA" (ByVal
lpConsoleTitle As String) As Long
Public Declare Sub Sleep Lib "kernel32.dll"
(ByVal dwMilliseconds As Long)
Public Declare Function AttachConsole Lib
"kernel32.dll" (ByVal ProcessID As Integer) As Boolean
Sub Main()
If Not AttachConsole(-1) Then Call AllocConsole
Call
SetConsoleTitle("My Console")
Call Sleep(2000)
Call FreeConsole
End
Sub
那么,这个程序的处理过程大概是:首先执行AttachConsole(-1),即附着父进程。假如是双击打开,AttachConsole(-1)就会失败,返回False,于是就执行了后面的Call
AllocConsole。如果是命令行调用,则AttachConsole(-1)成功,返回True,于是就不执行后面的Call
AllocConsole。
原理很简单,现在生成EXE,在命令行中运行看看,是否标题已改成了 My Console 也没有弹出新的命令行窗口呢?