2011-09-22 21 views
2

如何獲取從Windows服務管理器對話框傳遞的啓動參數。我希望能夠通過命令行參數傳遞給主函數來獲取它們。QtService不會從服務管理器窗口傳遞啓動參數

enter image description here

如果我創建服務時傳遞參數binPath然後我得到傳遞到主函數的參數。

sc create "Myservice" binPath= "Path_to_exe\Myservice.exe -port 18082" 

但是這種方式我們需要每次卸載和安裝服務來更改任何參數。 有沒有辦法在Qt中獲取啓動參數?

如果我使用.NET創建服務,我可以使用以下函數來獲取這些啓動參數。

System::Environment::GetCommandLineArgs(); 

回答

1

我知道這個問題是舊的,但如何保持解答和問題仍然存在,直到今天,我認爲是適當的給出一個可能的答案。

您可以通過重新實現void QtServiceBase::createApplication (int & argc, char ** argv)

得到一個Qt服務的啓動參數按照docs

This function is only called when no service specific arguments were passed to the service constructor, and is called by exec() before it calls the executeApplication() and start() functions. 

所以,當你的服務調用start功能ARGS將可用,因爲在start函數之前調用createApplication

這裏,例如:

#include <QtCore> 
#include "qtservice.h" 

class Service : public QtService<QCoreApplication> 
{ 
public: 
    explicit Service(int argc, char *argv[], const QString &name) : QtService<QCoreApplication>(argc, argv, name) 
    { 
     setServiceDescription("Service"); 
     setServiceFlags(QtServiceBase::CanBeSuspended); 
     setStartupType(QtServiceController::ManualStartup); 
    } 

protected: 
    void start() 
    { 
     // use args; 
    } 

    void stop() 
    { 
    } 

    void pause() 
    { 
    } 

    void resume() 
    { 
    } 

    void processCommand(int code) 
    { 
    } 

    void createApplication(int &argc, char **argv) 
    { 
     for (int i = 0; i < argc; i++) 
      args.append(QString(argv[i])); 

     QtService::createApplication(argc, argv); 
    } 
private: 
    QStringList args; 
}; 


int main(int argc, char *argv[]) 
{ 
    Service s(argc, argv, "Service"); 
    return s.exec(); 
}