我想創建一個應用程序,只能有一個實例,而不是打開第二個實例,我想「提高」當前正在運行的實例。我正在檢查使用wxSingleInstanceChecker
,但我不知道如何「提高」運行的。應用程序單實例wxWidgets
single = new wxSingleInstanceChecker;
if (single->IsAnotherRunning()) {
wxDELETE(single); return false;
}
我想創建一個應用程序,只能有一個實例,而不是打開第二個實例,我想「提高」當前正在運行的實例。我正在檢查使用wxSingleInstanceChecker
,但我不知道如何「提高」運行的。應用程序單實例wxWidgets
single = new wxSingleInstanceChecker;
if (single->IsAnotherRunning()) {
wxDELETE(single); return false;
}
下面是如何發送消息到現有的過程,但我不知道如何使該進程的主框架留在所有其他窗口的頂部。在我看來,這是窗口管理器的工作,不能或很難通過wxWidgets實現,但創建它時,您可以使窗口wxSTAY_ON_TOP
。所以,它要麼「永遠在最前面」,要麼最小化。
// BUILD: g++ this_file.cpp -Wall $(wx-config --cxxflags --libs net,core,base)
#include <wx/wx.h>
#include <wx/snglinst.h>
#include <wx/ipc.h>
class CConnection : public wxConnection
{
protected:
bool OnExec(const wxString& topic, const wxString& data);
};
class CServer : public wxServer
{
public:
wxConnectionBase *OnAcceptConnection(const wxString& topic) {
return new CConnection;
}
};
class CApp : public wxApp
{
public:
bool OnInit() {
// Check if there is another process running.
if (m_one.IsAnotherRunning()) {
// Create a IPC client and use it to ask the existing process to show itself.
wxClient *client = new wxClient;
wxConnectionBase *conn = client->MakeConnection("localhost", "/tmp/a_socket" /* or a port number */, "a_topic");
conn->Execute("raise");
delete conn;
delete client;
// Don't enter the message loop.
return false;
}
// Create the main frame.
wxFrame *frm = new wxFrame(NULL, wxID_ANY, "There can be only one.");
frm->Show(true);
// Start a IPC server.
m_server = new CServer;
m_server->Create("/tmp/a_socket" /* or the same port number */);
// Enter the message loop.
return this->wxApp::OnInit();
}
int OnExit() {
delete m_server;
return this->wxApp::OnExit();
}
private:
wxSingleInstanceChecker m_one;
CServer *m_server;
};
DECLARE_APP(CApp)
IMPLEMENT_APP(CApp)
bool CConnection::OnExec(const wxString& topic, const wxString& data)
{
if (topic.compare("a_topic") == 0 && data.compare("raise") == 0) {
wxTheApp->GetTopWindow()->Show(true); // This actually won't work.
}
return true;
}
您確實需要使用某種IPC的作爲the other answer所示,然後你可以使用wxFrame::Raise()
把它放在Z-順序的頂部。
請注意,將第二個實例的命令行參數轉發給第一個實例也是很常見的,例如,打開現有實例中命令行上指定的文檔,這就解釋了爲什麼你真的必須使用IPC - wxWidgets無法猜測你的命令行語法,特別是你的語義。