Register System hotkeys and System Tray functions in Windows

Source: Internet
Author: User

Previously written screenshot program. System hotkeys and system pallets are implemented. Recently I want to use this function for something, so I will try it out.

// PrintScreenDlg.h : header file//#if !defined(AFX_PRINTSCREENDLG_H__9CB8322A_B3F5_4916_8051_B808B83AE4EB__INCLUDED_)#define AFX_PRINTSCREENDLG_H__9CB8322A_B3F5_4916_8051_B808B83AE4EB__INCLUDED_#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000/////////////////////////////////////////////////////////////////////////////// CPrintScreenDlg dialogclass CPrintScreenDlg : public CDialog{// Constructionpublic:CPrintScreenDlg(CWnd* pParent = NULL);// standard constructor// Dialog Data//{{AFX_DATA(CPrintScreenDlg)enum { IDD = IDD_PRINTSCREEN_DIALOG };CStringm_HotKey;BOOLm_bSaveToFile;intm_FileType;//}}AFX_DATA// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CPrintScreenDlg)protected:virtual void DoDataExchange(CDataExchange* pDX);// DDX/DDV support//}}AFX_VIRTUAL// Implementationprotected:HICON m_hIcon;// Generated message map functions//{{AFX_MSG(CPrintScreenDlg)virtual BOOL OnInitDialog();afx_msg void OnSysCommand(UINT nID, LPARAM lParam);afx_msg void OnPaint();afx_msg HCURSOR OnQueryDragIcon();afx_msg void OnPrtsrc();afx_msg void OnExit();afx_msg void OnDestroy();    afx_msg long OnHotKey(WPARAM wParam, LPARAM lParam);afx_msg void OnHidden();    afx_msg void OnIconNotify(WPARAM wParam, LPARAM lParam);//}}AFX_MSGDECLARE_MESSAGE_MAP()private:VOID MenuPopup_Notify(int nCmd);    enum { printscreen=1, };    NOTIFYICONDATA m_nid;    VOID PrintWholeScreen();    VOID SaveCapturedBitmap(HBITMAP hCaptureBitmap);};//{{AFX_INSERT_LOCATION}}// Microsoft Visual C++ will insert additional declarations immediately before the previous line.#endif // !defined(AFX_PRINTSCREENDLG_H__9CB8322A_B3F5_4916_8051_B808B83AE4EB__INCLUDED_)
// Printscreendlg. CPP: implementation file // # include "stdafx. H "# include" printscreen. H "# include" printscreendlg. H "# include <windows. h> # ifdef _ debug # define new debug_new # UNDEF this_filestatic char this_file [] = _ file __; # endif # define wm_iconnotify (wm_user + 909) //////////////////////////////////////// /// // caboutdlg dialog used for app aboutclass caboutdlg: publi C cdialog {public: caboutdlg (); // dialog data // {afx_data (caboutdlg) Enum {IDD = idd_aboutbox }; //} afx_data // classwizard generated virtual function overrides // {afx_virtual (caboutdlg) protected: Virtual void dodataexchange (cdataexchange * PDX ); // DDX/DDV support //} afx_virtual // implementationprotected: // {afx_msg (caboutdlg) //} afx_msgdeclare_message_map ()}; caboutdlg: caboutdlg (): cdialog (caboutdlg: IDD) {// {afx_data_init (caboutdlg) //} afx_data_init} void caboutdlg: dodataexchange (cdataexchange * PDX) {cdialog: dodataexchange (PDX ); // {afx_data_map (caboutdlg) //} afx_data_map} Export (caboutdlg, cdialog) // {afx_msg_map (caboutdlg) // No message handlers //} Export () //////////////////////////////////////// /// // cprintscreendlg dialogcpri Ntscreendlg: cprintscreendlg (cwnd * pparent/* = NULL */): cdialog (cprintscreendlg: IDD, pparent) {// {afx_data_init (cprintscreendlg) m_hotkey = _ T ("Ctrl + D"); m_bsavetofile = false; m_filetype = 0; ///} afx_data_init // note that loadicon does not require a subsequent destroyicon in response = afxgetapp ()-> loadicon (idr_mainframe);} void exchange: dodataexchange (cdataexchange * PDX) {cdialog: dodataex Change (PDX); // {afx_data_map (Signature) ddx_text (PDX, idc_hotkey, m_hotkey); ddx_check (PDX, signature, m_bsavetofile); ddx_cbindex (PDX, expires, m_filetype ); //} afx_data_map} evaluate (outputs, cdialog) // {afx_msg_map (outputs) on_wm_syscommand () on_wm_paint () values (id_prtsrc, onprtsrc) Evaluate (id_exit, onexit) on_wm_destroy () On_message (wm_hotkey, onhotkey) on_message (wm_iconnotify, oniconnotify) on_bn_clicked (id_hidden, onhidden) //} afx_msg_mapend_message_map () //////////////////////////////////////// /// // cprintscreendlg message handlersbool cprintscreendlg:: oninitdialog () {cdialog: oninitdialog (); // Add "about... "menu item to system menu. // idm_aboutbox must be in the system command R Ange. Assert (idm_aboutbox & 0xfff0) = idm_aboutbox); Assert (idm_aboutbox <0xf000); cmenu * psysmenu = getsystemmenu (false); If (psysmenu! = NULL) {cstring straboutmenu; straboutmenu. loadstring (ids_aboutbox); If (! Straboutmenu. isempty () {psysmenu-> appendmenu (mf_separator); psysmenu-> appendmenu (mf_string, idm_aboutbox, straboutmenu); }}// set the icon for this dialog. the framework does this automatically // when the application's main window is not a dialogseticon (m_hicon, true); // set big iconseticon (m_hicon, false ); // set small icon // todo: add extra initialization here // regester the hotkey registerhotkey (Th Is-> getsafehwnd (), printscreen, mod_control, 'd); Return true; // return true unless you set the focus to a control} void cprintscreendlg :: onsyscommand (uint NID, lparam) {If (NID & 0xfff0) = idm_aboutbox) {caboutdlg dlgabout; dlgabout. domodal ();} else {cdialog: onsyscommand (NID, lparam) ;}// if you add a Minimize button to your dialog, you will need the code below // to draw the icon. for MFC appli Cations using the document/view model, // This is automatically done for you by the framework. void cprintscreendlg: onpaint () {If (isiconic () {cpaintdc DC (this); // device context for paintingsendmessage (wm_iconerasebkgnd, (wparam) DC. getsafehdc (), 0); // center icon in client rectangleint cxicon = getsystemmetrics (sm_cxicon); int cyicon = getsystemmetrics (sm_cyicon); crect rect; getclientrect (& rect) I NT x = (rect. width ()-cxicon + 1)/2; int y = (rect. height ()-cyicon + 1)/2; // draw the icondc. drawicon (X, Y, m_hicon);} else {cdialog: onpaint ();}} // The system callthis to obtain the cursor to display while the user drags // The minimized window. hcursor cprintscreendlg: onquerydragicon () {return (hcursor) m_hicon;} void cprintscreendlg: printwholescreen () {int nscreenwidth = getsystemmetrics (Sm _ Cxscreen); int nscreenheight = getsystemmetrics (sm_cyscreen); hwnd rows =: get1_topwindow (); HDC h1_topdc =: getdc (rows); HDC rows = createcompatibledc (h1_topdc ); hbitmap values = values (hsf-topdc, nscreenwidth, nscreenheight); SelectObject (values, values); bitblt (values, nscreenwidth, nscreenheight, hsf-topdc, srccopy); If (M_bsavetofile) {savecapturedbitmap (hcapturebitmap);} If (! Openclipboard () MessageBox ("Open clipboard failed! "," Warning "); else {If (! Emptyclipboard () MessageBox ("Clear clipboard failed! "," Warning "); else {setclipboarddata (cf_bitmap, latency);} closeclipboard () ;}:: releasedc (hsf-topwnd, hsf-topdc); deletedc (hcapturedc ); deleteobject (hcapturebitmap);} void cprintscreendlg: savecapturedbitmap (hbitmap hcapturebitmap) {HDC = NULL; // int ibits = 0 for each pixel at the current resolution; // word wbitcount = 0 for each pixel in the bitmap; // defines the color palette size, pixel bytes in the bitmap, bitmap file size, and number of written file bytes. DWORD dwpalettesize = 0, dwbmbitssize = 0, Dwdibsize = 0, dwwritten = 0; // Bitmap bitmap; // bitmapfileheader bmfhdr; // bitmapinfoheader bi; // point to the bitmap information header structure lpbitmapinfoheader lpbi; // defines the file, allocates a memory handle, and the color palette handle FH, hdib, hpal, holdpal = NULL; // calculate the number of bytes occupied by each pixel in a bitmap file. HDC = createdc ("display", null); ibits = getdevicecaps (HDC, bitspixel) * getdevicecaps (HDC, planes); deletedc (HDC); If (ibits <= 1) wbitcount = 1; else if (ibit S <= 4) wbitcount = 4; else if (ibits <= 8) wbitcount = 8; else if (ibits <= 24) wbitcount = 24; else wbitcount = 32; getObject (hcapturebitmap, sizeof (Bitmap), (lpstr) & Bitmap); bi. bisize = sizeof (bitmapinfoheader); bi. biwidth = bitmap. bmwidth; bi. biheight = bitmap. bmheight; bi. biplanes = 1; bi. bibitcount = wbitcount; bi. bicompression = bi_rgb; bi. bisizeimage = 0; bi. bixpelspermeter = 0; bi. biypels Permeter = 0; bi. biclrimportant = 0; bi. biclrused = 0; dwbmbitssize = (bitmap. bmwidth * wbitcount + 31)/32) * 4 * bitmap. bmheight; // allocate memory hdib = globalalloc (ghnd, dwbmbitssize + dwpalettesize + sizeof (bitmapinfoheader) for bitmap content; If (null = hdib) {cstring errmsg; errmsg. format ("failed to allocate % u memory, globalalloc () returned error code: % u. \ R \ n % s (% u) ", dwbmbitssize + dwpalettesize + sizeof (bitmapinfoheader), getlasterror (), _ file __, _ line __); messageBox (errmsg, _ T ("error"); return;} lpbi = (lpbitmapinfoheader) globallock (hdib); * lpbi = Bi; // process the palette hpal = getstockobject (default_palette); If (hpal) {HDC =: getdc (null); holdpal =: selectpalette (HDC, (hpalette) hpal, false); realizepalette (HDC);} // obtain the new pixel value getdibits (HDC, hcap Turebitmap, 0, (uint) bitmap. bmheight, (lpstr) lpbi + sizeof (bitmapinfoheader) + dwpalettesize, (bitmapinfo *) lpbi, dib_rgb_colors); // restore if (holdpal) {: selectpalette (HDC, (hpalette) holdpal, true); realizepalette (HDC);: releasedc (null, HDC);} // create a bitmap file cstring szfilename; systemtime effecime; getlocaltime (& effecime ); szfilename. format ("%u-0000u-0000u-000002u000002u.bmp", using ime. wyear, too ime. wmonth, too ime. Wday, too ime. whour, mongoime. wminute); FH = createfile (szfilename, generic_write, 0, null, create_always, file_attribute_normal, null); If (FH = invalid_handle_value) return; // set the bitmap file header bmfhdr. bftype = 0x4d42; // "BM" dwdibsize = sizeof (bitmapfileheader) + sizeof (bitmapinfoheader) + dwpalettesize + dwbmbitssize; bmfhdr. bfsize = dwdibsize; bmfhdr. bfreserved1 = 0; bmfhdr. bfreserved2 = 0; bmfhdr. BFO Ffbits = (DWORD) sizeof (bitmapfileheader) + (DWORD) sizeof (bitmapinfoheader) + dwpalettesize; // write bitmap file header writefile (FH, (lpstr) & bmfhdr, sizeof (bitmapfileheader ), & dwwritten, null); // write the remaining content of the bitmap file writefile (FH, (lpstr) lpbi, dwdibsize, & dwwritten, null); // clear globalunlock (hdib ); globalfree (hdib); closehandle (FH); return;} void cprintscreendlg: onprtsrc () {// todo: add your control notification handler Co De here showwindow (sw_hide); updatedata (); printwholescreen (); showwindow (sw_normal);} void cprintscreendlg: onexit () {// todo: add your control notification handler code here sendmessage (wm_close);} void cprintscreendlg: ondestroy () {unregisterhotkey (this-> getsafehwnd (), 1); shell_policyicon (nim_delete, & m_nid); cdialog: ondestroy (); // todo: add your message handler code here} Long cprintscreendlg: On Hotkey (wparam, lparam) {Switch (wparam) {Case printscreen: {onprtsrc ();} break; default: return 1;} return 0;} void cprintscreendlg :: onhidden () {// todo: add your control notification handler code here // initialize the system tray icon m_nid.cbsize = sizeof (notifyicondata); m_nid.hwnd = getsafehwnd (); m_nid.uid = 128; m_nid.uflags = nif_icon | nif_message | nif_tip; m_nid.ucallbackmessage = wm_iconnotify; M_nid.hicon = m_hicon; strcpy (m_nid.sztip, "I am here! :) "); Shell_policyicon (nim_add, & m_nid); showwindow (sw_hide);} void handle: oniconnotify (wparam, lparam) {Switch (lparam) {case when: // load main window here {shell_policyicon (nim_delete, & m_nid); showwindow (sw_normal); setforegroundwindow ();} break; Case wm_rbuttonup: {trace ("case wm_rbuttonup "); point point; cmenu menupopup; // get mouse position getcursorpo S (& Point); // popup context menu bool bsuc = menupopup. loadmenu (idr_menuright); If (! Bsuc) {MessageBox ("loadmenu failed! "); Return;} int ncmd = menupopup. trackpopupmenu (tpm_leftbutton | tpm_rightbutton | tpm_bottomalign | tpm_returncmd, point. x, point. y, this, null); menupopup_policy (ncmd);} break; default: break;} return;} void cprintscreendlg: menupopup_policy (INT ncmd) {Switch (ncmd) {case when: {shell_policyicon (nim_delete, & m_nid); showwindow (sw_normal); setforegroundwindow () ;}break; Case id_menuitem_exit: {shell_policyicon (nim_delete, & m_nid ); sendmessage (wm_close);} break; default: break;} return ;}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.