⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 powerbar.cpp

📁 windows ce 程序设计书 的源代码
💻 CPP
字号:
//====================================================================
// PowerBar - An example Today screen item
//
// Written for the book Programming Windows CE
// Copyright (C) 2003 Douglas Boling
//====================================================================
#include <windows.h>                 // For all that Windows stuff
#include <aygshell.h>                // Pocket PC includes
#include <todaycmn.h>                // Today screen includes
#include "PowerBar.h"                // PowerBar includes

// Returns number of elements
#define TODAYWND  TEXT ("MyPowerBarWnd")

// Procedure defs
//
// Global data
//
HINSTANCE hInst;
int nBattValue = 0;
BOOL fAC = FALSE;
BOOL fCharging = FALSE;
BOOL fNewData = TRUE;
int nFontHeight;

// Message dispatch table for TodayWindowProc
const struct decodeUINT MainMessages[] = {
    WM_CREATE, DoCreateMain,
    WM_PAINT, DoPaintMain,
    WM_ERASEBKGND, DoEraseBackgroundMain,
    WM_LBUTTONUP, DoLButtonUpMain,
    WM_TODAYCUSTOM_CLEARCACHE, DoClearCacheMain,
    WM_TODAYCUSTOM_QUERYREFRESHCACHE, DoQueryRefreshCacheMain,
};

//====================================================================
// DllMain - DLL initialization entry point
//
BOOL WINAPI DllMain (HANDLE hinstDLL, DWORD dwReason,
                     LPVOID lpvReserved) {
    switch (dwReason) {
    case DLL_PROCESS_ATTACH:
        hInst = (HINSTANCE) hinstDLL;
        break;

    case DLL_PROCESS_DETACH:
        // We do this so we can reload the DLL later.
        UnregisterClass (TODAYWND, hInst);
        break;
    }
    return TRUE;
}
//----------------------------------------------------------------------
// MyRegisterClass - Registers the item's window class
//
int MyRegisterClass (HINSTANCE hInst) {
    WNDCLASS wc;

    // Register the item's window class.
    memset (&wc, 0, sizeof (wc));
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = TodayWndProc;
    wc.hInstance = hInst;
    wc.lpszClassName = TODAYWND;
    wc.hbrBackground = (HBRUSH) (COLOR_WINDOW+1);
    return RegisterClass (&wc);
}
//======================================================================
// InitializeCustomItem - Entry point called by Today screen to 
// indicate the item window to be created
//
HWND APIENTRY InitializeCustomItem(TODAYLISTITEM *ptli, HWND hwndParent) {

    HWND hWnd;
    // See if not enabled.
    if (!ptli->fEnabled)
        return FALSE;
    MyRegisterClass (hInst);

    // Create a child window for our Today window entry.
    hWnd = CreateWindow (TODAYWND, NULL, WS_VISIBLE | WS_CHILD, 
                         0, 0, GetSystemMetrics (SM_CXSCREEN), 0,
                         hwndParent, NULL, hInst, 0);
    return hWnd;
}
//======================================================================
// Message handling procedures 
//
//======================================================================
// TodayWndProc - Window procedure for the Today entry child window
//
LRESULT TodayWndProc (HWND hWnd, UINT wMsg, WPARAM wParam, LPARAM lParam) {
    INT i;
    //
    // Search message list to see if we need to handle this
    // message. If in list, call procedure.
    //
    for (i = 0; i < dim(MainMessages); i++) {
        if (wMsg == MainMessages[i].Code)
            return (*MainMessages[i].Fxn)(hWnd, wMsg, wParam, lParam);
    }
    return DefWindowProc (hWnd, wMsg, wParam, lParam);
}
//----------------------------------------------------------------------
// DoCreateMain - Process WM_CREATE message for window.
//
LRESULT DoCreateMain (HWND hWnd, UINT wMsg, WPARAM wParam, 
                      LPARAM lParam) {
    HDC hdc;
    TEXTMETRIC tm;

    // Query height of default font.
    hdc = GetDC (hWnd);
    GetTextMetrics (hdc, &tm);
    nFontHeight = tm.tmHeight + tm.tmExternalLeading;
    ReleaseDC (hWnd, hdc);

    nBattValue = -1;  // Initialize the old battery value.
    return 0;
}
//----------------------------------------------------------------------
// DoQueryRefreshCacheMain - Process WM_TODAYCUSTOM_QUERYREFRESHCACHE 
// message for window.
//
LRESULT DoQueryRefreshCacheMain (HWND hWnd, UINT wMsg, WPARAM wParam, 
                                 LPARAM lParam) {

    TODAYLISTITEM *ptli = (TODAYLISTITEM *)wParam;
    SYSTEM_POWER_STATUS_EX sps;

    // Set the height of our entry.
    if ((ptli->grfFlags < 5) || (ptli->grfFlags > 23))
        ptli->cyp = 20;
    else
        ptli->cyp = ptli->grfFlags;

    // Check the power status.
    GetSystemPowerStatusEx (&sps, FALSE);

    // Save AC status.
    if (sps.ACLineStatus == 1)
        fAC = TRUE;
    else
        fAC = FALSE;

    // Save charging status.
    if (sps.BatteryFlag & 0x08)
        fCharging = TRUE;
    else
        fCharging = FALSE;


    // If the battery value has changed since the last check, 
    // set the flag to force a redraw of the Today screen.
    if (sps.BatteryLifePercent != nBattValue) {
        nBattValue = sps.BatteryLifePercent;
        fNewData = TRUE;
    } else
        fNewData = FALSE;
    return fNewData;
}
//----------------------------------------------------------------------
// DoClearCacheMain - Process WM_TODAYCUSTOM_CLEARCACHE message 
// for window.
//
LRESULT DoClearCacheMain (HWND hWnd, UINT wMsg, WPARAM wParam, 
                          LPARAM lParam) {
    // Nothing to do here since the example doesn't cache data
    return 0;
}
//----------------------------------------------------------------------
// DoLButtonUpMain - Process WM_LBUTTONUP message for window.
//
LRESULT DoLButtonUpMain (HWND hWnd, UINT wMsg, WPARAM wParam, 
                         LPARAM lParam) {
    SHELLEXECUTEINFO se;
    DWORD dwAttr;

    // Launch the Control Panel's power applet.
    memset (&se, 0, sizeof (se));
    se.cbSize = sizeof (se);
    se.hwnd = hWnd;
    se.lpFile = TEXT ("ctlpnl.exe");
    se.lpVerb = TEXT("open");
    se.lpDirectory = TEXT ("\\windows");
    se.lpParameters = TEXT ("powerg.cpl");

    // See if power cpl is a standalone exe.
    dwAttr = GetFileAttributes (TEXT("\\windows\\powerg.exe"));
    if (dwAttr != (DWORD)-1)
        se.lpFile = TEXT ("powerg.exe");

    ShellExecuteEx (&se);    // Launch the Control Panel.
    return 0;
}
//----------------------------------------------------------------------
// DoEraseBackgroundMain - Process WM_ERASEBKGND message for window.
//
LRESULT DoEraseBackgroundMain (HWND hWnd, UINT wMsg, WPARAM wParam, 
                     LPARAM lParam) {

	TODAYDRAWWATERMARKINFO wmi;
	wmi.hwnd = hWnd;
	wmi.hdc = (HDC)wParam;
	GetClientRect (hWnd, &wmi.rc);
	SendMessage (GetParent (hWnd), TODAYM_DRAWWATERMARK, 0, 
	             (LPARAM)&wmi);
    return 1;
}
//----------------------------------------------------------------------
// DoPaintMain - Process WM_PAINT message for window.
//
LRESULT DoPaintMain (HWND hWnd, UINT wMsg, WPARAM wParam, 
                     LPARAM lParam) {
    PAINTSTRUCT ps;
    RECT rect;
    HDC hdc;
    TCHAR szText[32];
    int nPercent;
    COLORREF rgbLeft = RGB (0, 255, 0), rgbText;
    HICON hIcon;
    HBRUSH hbr;

    // Ensure a valid battery value.
    nPercent = nBattValue;
    if (nBattValue == 255) {
        nPercent = 100;
        if (!fCharging && !fAC) 
            rgbLeft = RGB (255, 0, 0);
    } else if (nBattValue < 33) {
        rgbLeft = RGB (255, 0, 0);
    } 

    hdc = BeginPaint (hWnd, &ps);
    GetClientRect (hWnd, &rect);

    // Draw icon if room.
    if (rect.bottom - rect.top > 18) {
        hIcon = (HICON)LoadImage (hInst, MAKEINTRESOURCE (ID_ICON), 
                                  IMAGE_ICON, 16, 16, 0);
        DrawIcon (hdc, 2, 2, hIcon);
        DeleteObject (hIcon);
    }
    // Draw percent bar.
    hbr = CreateSolidBrush (rgbLeft);
    rect.left += 30;
    rect.right -= 5;
    rect.right = rect.left + ((rect.right - rect.left)*nPercent)/100;
    rect.top++;
    rect.bottom--;
    FillRect (hdc, &rect, hbr);
    DeleteObject (hbr);

    // Draw text percent if room.
    // Ask for rect again since we messed it up above.
    GetClientRect (hWnd, &rect);
    if (rect.bottom - rect.top > nFontHeight) {

        if (fCharging)
            lstrcpy (szText, TEXT ("Charging"));
        else if (!fAC && (nBattValue > 100))
            lstrcpy (szText, TEXT ("Unknown"));
        else
            wsprintf (szText, TEXT ("%02d%%"), nPercent);
        rgbText = (COLORREF)SendMessage (GetParent(hWnd), 
                                         TODAYM_GETCOLOR,
                                         (WPARAM)TODAYCOLOR_TEXT, 0);
        SetTextColor (hdc, rgbText);
        SetBkMode (hdc, TRANSPARENT);
        DrawText (hdc, szText, -1, &rect, DT_CENTER | DT_SINGLELINE | 
                  DT_VCENTER);
    }
    EndPaint (hWnd, &ps);

    // Reset my "redraw now" flag.
    fNewData = FALSE;
    return 0;
}
//======================================================================
// CustomItemOptionsDlgProc - Options Dialog box procedure 
//
BOOL CALLBACK CustomItemOptionsDlgProc (HWND hWnd, UINT wMsg, 
                                        WPARAM wParam, LPARAM lParam) {
    static TODAYLISTITEM *ptli;
    static HFONT hFont;
    WORD wID;
    int i;

    switch (wMsg) {
    case WM_INITDIALOG:
        {
            TEXTMETRIC tm;
            LOGFONT lf;
            HDC hdc;
            SHINITDLGINFO shidi;

            // Create a Done button and size dialog.
            shidi.dwMask = SHIDIM_FLAGS;
            shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIZEDLG;
            shidi.hDlg = hWnd;
            SHInitDialog(&shidi);

            ptli = (TODAYLISTITEM *)lParam;

            // Jump through hoops to look like 
            // other Today Options dialogs.
            hdc = GetDC (hWnd);
            GetTextMetrics (hdc, &tm);
            memset (&lf, 0, sizeof (lf));
            // Create proper font. It's not 8 or 9 pt; it must be 8.5.
            lf.lfHeight = -1 * 
                          (17 * GetDeviceCaps (hdc, LOGPIXELSY)/72)/2;
            lf.lfWeight = FW_SEMIBOLD;
            lf.lfPitchAndFamily = tm.tmPitchAndFamily;
            lstrcpy (lf.lfFaceName, TEXT("Tahoma"));
            hFont = CreateFontIndirect (&lf);
            ReleaseDC (hWnd, hdc);
            // Query bar size setting from registry.
			i = 999;
            MyGetSetTodayItemReg (&i, TRUE);
            if (i == 0) i = 23;
            if (i < 16)
                wID = ID_SHORT;
            else if (i < 20)
                wID = ID_MED;
            else
                wID = ID_TALL;
            CheckRadioButton (hWnd, ID_SHORT, ID_TALL, wID);
        }
        break;

    case WM_DESTROY:
        if (hFont) 
            DeleteObject (hFont);
        break;
        
    case WM_PAINT:
        {
            // Draw a line 24 pixels down from the top per spec.
            PAINTSTRUCT ps;
            HDC hdc;
            RECT rect;
            HPEN hOld, hPen = (HPEN)GetStockObject (BLACK_PEN);

            GetClientRect (hWnd, &rect);
            hdc = BeginPaint (hWnd, &ps);
            rect.top = rect.top + 23;
            rect.bottom = rect.top;
            hOld = (HPEN)SelectObject (hdc, hPen);
            Polyline (hdc, (LPPOINT)&rect, 2);

            // Draw this line to separate about data from radio buttons.
            rect.top += 70;
            rect.bottom += 70;
            Polyline (hdc, (LPPOINT)&rect, 2);
            SelectObject (hdc, hOld);
            EndPaint (hWnd, &ps);
        }
        break;
    case WM_CTLCOLORSTATIC:
        // Modify the color and font of the header text string.
        if ((HWND)lParam != GetDlgItem (hWnd, IDC_STATIC_TITLE)) 
            break;
        SelectObject ((HDC)wParam, hFont);
        SetTextColor ((HDC)wParam, RGB (0, 0, 156));
        SetBkColor ((HDC)wParam, RGB (255, 255, 255));
        return (BOOL)GetStockObject (WHITE_BRUSH);
        
    case WM_COMMAND:
        wID = LOWORD (wParam);
        switch (wID) {
        case IDOK:
            i = 20;
            if (MyIsBtnChecked (hWnd, ID_MED))
                i = 16;
            else if (MyIsBtnChecked (hWnd, ID_SHORT))
                i = 5;
            // Save the height value.
            MyGetSetTodayItemReg (&i, FALSE);
            ptli->grfFlags = i;
        case IDCANCEL:
            EndDialog (hWnd, 0);
            break;
        }
        break;
    }
    return FALSE;
}
//----------------------------------------------------------------------
// MyGetSetTodayItemReg - Writes the Flags value of the Today item's 
// registry entry
//      
int MyGetSetTodayItemReg (int *pnFlagData, BOOL fRead) {
    HKEY hKey, hSubKey = 0;
    int rc, i = 0;
    DWORD dwType, dwSize;
    TCHAR *pName, szKey[128], szDll[MAX_PATH], szName[MAX_PATH];

    GetModuleFileName (hInst, szName, dim (szName));
    for (pName = szName + lstrlen (szName); 
         (pName > szName) && (*pName != TEXT('\\')); pName--);
    if (*pName == TEXT('\\')) pName++;

    // Open the Today screen's item key.
    rc = RegOpenKeyEx (HKEY_LOCAL_MACHINE, 
                       TEXT ("Software\\Microsoft\\today\\items"),
                       0, 0, &hKey);
    // Enumerate the item list until
    // we find a key with our DLL name.
    while (rc == ERROR_SUCCESS) {
        dwSize = sizeof (szKey);
        rc = RegEnumKeyEx (hKey, i++, szKey, &dwSize, NULL, NULL, NULL, NULL);
        if (rc != ERROR_SUCCESS)
            break;
        // Open the subkey.
        rc = RegOpenKeyEx (hKey, szKey, 0, 0, &hSubKey);
        if (rc == ERROR_SUCCESS) {
            // Get DLL name.
            dwSize = sizeof (szDll);
            rc = RegQueryValueEx (hSubKey, TEXT ("DLL"), 0, &dwType, 
                                  (PBYTE)szDll, &dwSize);
            if (rc == ERROR_SUCCESS) {
                // See if this is us.
                if (lstrcmpi (szDll, pName) == 0) 
                    break;  //Yes!
            }
            RegCloseKey (hSubKey);
            hSubKey = 0;
        }
        rc = ERROR_SUCCESS;
    }
    if (hSubKey) {
        if (fRead) {
            dwSize = sizeof (DWORD);
            rc = RegQueryValueEx (hSubKey, TEXT("Flags"), 0, &dwType, 
                             (PBYTE)pnFlagData, &dwSize);
            if (rc != ERROR_SUCCESS)
                *pnFlagData = 20;
        } else 
            rc = RegSetValueEx (hSubKey, TEXT("Flags"), 0, REG_DWORD, 
                           (PBYTE)pnFlagData, sizeof (DWORD));

        RegCloseKey (hSubKey);
    }
    RegCloseKey (hKey);
    return rc;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -