grig_p
Oct. 31, 2017, 2:27 p.m.

Qt - WinAPI. How to show a running application on top of your application

There was at me somehow a problem to operate applications - the services written on Qt, from application - a kernel written also on Qt. And, if the service application is not running, then it should be started, and if it is running, its window should be brought to the foreground. QProcess is used to invoke applications.


It looks like this.
Process creation:

  1. QProcess *app;
  2. bool pw = false;
  3. ...
  4. void createProcess()
  5. {
  6. app = new QProcess(this);
  7. app->setProgram("MyProgram.exe");
  8. app->setArguments(QStringList() << "arg1" << "arg2");
  9. connect(app, SIGNAL(started()), this, SLOT(onProcStarted()));
  10. connect(app, SIGNAL(finished()), this, SLOT(onProcFinished()));
  11. }

Call:

  1. if (!pw)
  2. { //If the application is not running, then run it
  3. app->start(QIODevice::ReadOnly);
  4. }
  5. else
  6. { // If it's running, we'll show it from the top
  7. HWND hWnd = FindWindow(nullptr, L"Заголовок главного окна");
  8. if (hWnd > 0){
  9. ShowWindow(hWnd, SW_RESTORE);
  10. SetForegroundWindow(hWnd);
  11. }
  12. }

Slots:

  1. void onProcStarted()
  2. {
  3. pw = true;
  4. }
  5.  
  6. void onProcFinished(int)
  7. {
  8. pw = false;
  9. }

As I understood, QProcess does not know how to bring to the forefront the window of the running process. Therefore, I have to resort to WinApi. But showing the window in this form does not work. Moreover, the FindWindow function does not work. It does not return the correct handle. Although there is a window.

The solution was related to the direct indication of the encoding as follows:

  1. QTextCodec *codec = QTextCodec::codecForName("UTF-8");
  2. QString s = codec->toUnicode("Заголовок главного окна");
  3. LPCWSTR lps = (LPCWSTR)s.utf16();
  4.  
  5. HWND hWnd = FindWindow(nullptr, lps);
  6. if (hWnd > 0) {
  7. ShowWindow(hWnd, SW_RESTORE);
  8. SetForegroundWindow(hWnd);
  9. }

By article asked0question(s)

3

Do you like it? Share on social networks!

Юрий
  • June 16, 2018, 9:19 p.m.

А можно по ID процесса  выводить на передний план окно?

myProcess->processId();
Evgenii Legotckoi
  • June 18, 2018, 1 p.m.

Если зарыться в API системы, то, думаю, что можно, тут тоже использовался WinAPI.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html