Windows啟動瀏覽器並打開網頁

Windows啟動瀏覽器並打開網頁

啟動瀏覽器最簡單的方法是使用ShellExecute(),但無返回進程句炳,要關閉瀏覽器只能查找窗口.更好的方法是CreateProcess()啟動瀏覽器新進程並打帶網頁,並返回進程句柄,方便關閉瀏覽器.

BOOL CreateProcess(LPCTSTR lpApplicationName,//執行模塊名填空NULL即可

LPTSTR  lpCommandLine,//命令行填”瀏覽器Path+空格+網頁URL”

LPSECURITY_ATTRIBUTES lpProcessAttributes,//進程屬性  LPSECURITY_ATTRIBUTES lpThreadAttributes,//線程屬性

BOOL bInheritHandles,  //繼承進程句柄false

DWORD dwCreationFlags, //創建標誌填CREATE_NEW_CONSOLE

LPVOID lpEnvironment, //進程環境

LPCTSTR lpCurrentDirectory,// 進程的工作路徑填NULL

LPSTARTUPINFO lpStartupInfo, //STARTUPINFO結構

LPPROCESS_INFORMATION lpProcessInformation//PROCESS_INFORMATION結構

);

  1. 要注意的是命令行lpCommandLine:瀏覽器Path+空格+網頁URL
  2. 命令行最好使用寬字符Unicode否則路徑有漢字或非ASCII碼則無法運行
  3. 返回不為false則調用成功
  4. 保存lpProcessInformation返回瀏覽器新進柄

 

下麵給打開網頁源代碼,便於

bool Open_Url(char * url,char * browser_Path)

{

int result = 0;

char CommandA[2056];

WCHAR CommandW[2056];

int length;

SECURITY_ATTRIBUTES Security_Attributes_Process;// 進程屬性

SECURITY_ATTRIBUTES Security_Attributes_Thread;// 線程屬性

STARTUPINFO        Startup_Info;// 啟動信息

PROCESS_INFORMATION Process_Information;//  進程信息

strcpy(CommandA,browser_Path);

strcat(CommandA,” “);

strcat(CommandA,url);

// 轉換UNICODE

length = MultiByteToWideChar(CP_ACP, NULL, CommandA, strlen(CommandA), CommandW, sizeof(CommandW));

CommandW[length] = NULL;

// 進程屬性

Security_Attributes_Process.nLength              = sizeof(SECURITY_ATTRIBUTES);

Security_Attributes_Process.lpSecurityDescriptor = NULL;

Security_Attributes_Process.bInheritHandle       = true;

// 線程屬性

Security_Attributes_Thread.nLength               = sizeof(SECURITY_ATTRIBUTES);

Security_Attributes_Thread.lpSecurityDescriptor  = NULL;

Security_Attributes_Thread.bInheritHandle        = true;

// 啟動信息

ZeroMemory( &Startup_Info, sizeof(STARTUPINFO) );

Startup_Info.cb = sizeof(STARTUPINFO);

ZeroMemory( &Process_Information, sizeof(PROCESS_INFORMATION) );

// 創建進程

result = CreateProcessW(NULL,

CommandW,

&Security_Attributes_Process,

&Security_Attributes_Thread,

FALSE,

CREATE_NEW_CONSOLE,

NULL,

NULL,

&Startup_Info,

&Process_Information);

// 獲取進程句柄

if(result != 0)

return true;

else

return false;

}

評論