문제

I am creating a GUI in using VC++ CLR windows form and wanted to make a hotkey to restore my windows from the system tray that I have minimized. I've found that RegisterHotKey is a way to make a global hotkey in the system but I don't understand how to make use of it inside my code.

Any thoughts??

도움이 되었습니까?

해결책

First you need to #include the Windows headers, put it in the stdafx.h precompiled header file for example:

// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
#pragma once

#include <Windows.h>
#pragma comment(lib, "user32.lib")

The #pragma ensures that the linker will link the import library for user32.dll, required to link RegisterHotKey().

Next, inside the Form class you need to override the OnHandleCreated() method. It will run whenever the native window for the Form is created, something that can happen more than once. Make that look like this:

protected:
    virtual void OnHandleCreated(EventArgs^ e) override {
        __super::OnHandleCreated(e);
        RegisterHotKey((HWND)this->Handle.ToPointer(), 1, 
            MOD_ALT | MOD_CONTROL, (UINT)Keys::F1); 
    }

I hard-coded the hotkey to Ctrl+Alt+F1, change that to the one you want to use. You can add additional hotkeys, change the id argument (2nd argument, I used 1).

Then you need to detect the WM_HOTKEY message that windows will send to you when the user presses the key. That requires overriding the form's WndProc() method, like this:

protected:
    virtual void WndProc(Message% m) override {
        if (m.Msg == WM_HOTKEY && m.WParam.ToInt32() == 1) {
            this->WindowState = FormWindowState::Normal;
            this->BringToFront();
        }
        __super::WndProc(m);
    }

Test this by minimizing the form, pressing Ctrl+Alt+F1 and you'll see the window getting restored and moved back into the foreground.

다른 팁

Thanks for your help Hans, I tried with the codes but it didn't really work like I wanted it to. My program will be minimized into the system tray with the codes below

private:
    System::Void MyForm::MyForm_Resize(System::Object^  sender, System::EventArgs^  e)  {
        if (WindowState == FormWindowState::Minimized)
        {
            Hide();
        }
    }

If I commented out the part where it hides as it minimize, it worked out fine though.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top