Chrome增加启动参数
最近在改chrome源码时一个需求是启动便全屏,起初一直纠结在\src\chrome\browser\ui下的各种工程中,看各种不懂的代码,偶然间发现了chrome可以设置启动参数从而实现上述功能。
貌似本来chrome已经提供了用于添加启动参数的方法,定义如下:
// Append a switch [with optional value] to the command line. void AppendSwitch(const std::string& switch_string);
但我尝试多次都失败,也不知道问题出在哪里,而且工程太大一debug就死机。。。
最后决定在初初始化CommandLine类前便手动加入启动参数,期间遇到了问题便是char* 和 wchar*的转换了,这里简单记录下。
Window API提供了GetCommandLineW()获得命令行参数, 函数原型为:
//return the pointer to the command-line string for the current process. LPTSTR WINAPI GetCommandLine(void);
LPTSTR在chrome中的定义为:
typedef WCHAR *LPTSTR
为了在原来启动参数后加入我们需要的,我们可以将command_line转换成char*, 加入启动参数后再转换为wchar*
更改\chromium\src\base\command_line.cc
bool CommandLine::Init(int argc, const char* const* argv) { if (current_process_commandline_) { return false; } current_process_commandline_ = new CommandLine(NO_PROGRAM); #if defined(OS_WIN) //保存原始启动参数 LPWSTR command_line = ::GetCommandLineW(); LPWSTR command_line2; //增加启动参数 //将WChar*转换为Char* size_t len = wcslen(command_line) + 1; size_t converted = 0; char *CStr; char *CStr2; char *CStr3; CStr = (char*)malloc(len*sizeof(char)); CStr2 = (char*)malloc(len*sizeof(char)); CStr3 = (char*)malloc((len*2)*sizeof(char)); wcstombs_s(&converted, CStr, len, command_line, _TRUNCATE); strcpy(CStr3,CStr); //加入任意启动参数,这里举个例子 strcpy(CStr2," -kiosk -user-data-dir=\".\""); strcat(CStr3,CStr2); //将char*转化为wchar len = strlen(CStr3) + 1; converted = 0; command_line2 = (wchar_t*)malloc(len*sizeof(wchar_t)); mbstowcs_s(&converted, command_line2, len, CStr3, _TRUNCATE); current_process_commandline_->ParseFromString(command_line2); #elif defined(OS_POSIX) current_process_commandline_->InitFromArgv(argc, argv); #endif return true; }
Init只执行一次,current_process_commandline_实例只有一个,我们的启动参数会永久保存。
其他的,诸如:CString、LPWSTR、TCHAR CHAR、LPSTR之间也是一样的。
对了,Chrome提供了非常多的启动参数,均定义在\chromium\src\chrome\common的chrome_switches.h下,比如常见的全屏启动、默认主页、取消同源策略等。