Как спрятать програмку в трей
Shell_NotifyIcon
Sends a message to the taskbar's status area.
BOOL Shell_NotifyIcon(
DWORD dwMessage,
PNOTIFYICONDATA lpdata
);
Parameters
dwMessage
[in] Variable of type DWORD that specifies the action to be taken. It can have one of the following values.
NIM_ADD
Adds an icon to the status area. The hWnd and uID members of the NOTIFYICONDATA structure pointed to by lpdata will be used to identify the icon in later calls to Shell_NotifyIcon.
NIM_DELETE
Deletes an icon from the status area. Use the hWnd and uID members of the NOTIFYICONDATA structure pointed to by lpdata to identify the icon to be deleted.
NIM_MODIFY
Modifies an icon in the status area. Use the hWnd and uID members of the NOTIFYICONDATA structure pointed to by lpdata to identify the icon to be modified.
NIM_SETFOCUS
Version 5.0. Returns focus to the taskbar notification area. Taskbar icons should use this message when they have completed their user interface operation. For example, if the taskbar icon displays a shortcut menu, but the user presses ESCAPE to cancel it, use NIM_SETFOCUS to return focus to the taskbar notification area.
NIM_SETVERSION
Version 5.0. Instructs the taskbar to behave according to the version number specified in the uVersion member of the structure pointed to by lpdata. This message allows you to specify whether you want the version 5.0 behavior found on Microsoft® Windows® 2000 systems, or that found with earlier Shell versions. The default value for uVersion is zero, indicating that the original Windows 95 notify icon behavior should be used. For details, see the Remarks section.
lpdata
[in] Address of a NOTIFYICONDATA structure. The content of the structure depends on the value of dwMessage.
Return Values
Returns TRUE if successful or FALSE otherwise. If dwMessage is set to NIM_SETVERSION, the function returns TRUE if the version was successfully changed or FALSE if the requested version is not supported.
Remarks
The taskbar notification area is sometimes erroneously called the "tray."
Version 5.0 of the Shell, found on Windows 2000, handles Shell_NotifyIcon mouse and keyboard events differently than earlier Shell versions found on Windows NT® 4.0, Windows 95, and Windows 98. The differences are:
If a user selects a notify icon's shortcut menu with the keyboard, the version 5.0 Shell sends the associated application a WM_CONTEXTMENU message. Earlier versions send WM_RBUTTONDOWN and WM_RBUTTONUP messages.
If a user selects a notify icon with the keyboard and activates it with the space bar or ENTER key, the version 5.0 Shell sends the associated application an NIN_KEYSELECT notification. Earlier versions send WM_RBUTTONDOWN and WM_RBUTTONUP messages.
If a user selects a notify icon with the mouse and activates it with the ENTER key, the version 5.0 Shell sends the associated application an NIN_SELECT notification. Earlier versions send WM_RBUTTONDOWN and WM_RBUTTONUP messages.
If a user passes the mouse pointer over an icon with which a balloon ToolTip is associated, the version 5.0 Shell sends the following messages.
NIN_BALLOONSHOW - Sent when the balloon is shown (balloons are queued).
NIN_BALLOONHIDE - Sent when the balloon disappears—when the icon is deleted, for example. This message is not sent if the balloon is dismissed because of a timeout or mouse click by the user.
NIN_BALLOONTIMEOUT - Sent when the balloon is dismissed because of a timeout.
NIN_BALLOONUSERCLICK - Sent when the balloon is dismissed because the user clicked the mouse.
You can select which way the Shell should behave by calling Shell_NotifyIcon with dwMessage set to NIM_SETVERSION. Set the uVersion member of the NOTIFYICONDATA structure to indicate whether you want pre-version 5.0 behavior or version 5.0 and later behavior.
Note The messages discussed above are not conventional Windows messages. They are sent as the lParam value of the application-defined message that is specified when the icon is added with NIM_ADD.
Windows 95/98/Me: Shell_NotifyIcon is supported by the Microsoft Layer for Unicode. To use this, you must add certain files to your application as outlined in Microsoft Layer for Unicode on Windows 95/98/Me Systems.
NOTIFYICONDATA
Contains information that the system needs to process taskbar status area messages.
typedef struct _NOTIFYICONDATA {
DWORD cbSize;
HWND hWnd;
UINT uID;
UINT uFlags;
UINT uCallbackMessage;
HICON hIcon;
#if (_WIN32_IE < 0x0500)
TCHAR szTip[64];
#else
TCHAR szTip[128];
#endif
#if (_WIN32_IE >= 0x0500)
DWORD dwState;
DWORD dwStateMask;
TCHAR szInfo[256];
union {
UINT uTimeout;
UINT uVersion;
} DUMMYUNIONNAME;
TCHAR szInfoTitle[64];
DWORD dwInfoFlags;
#endif
#if (_WIN32_IE >= 0x600)
GUID guidItem;
#endif
} NOTIFYICONDATA, *PNOTIFYICONDATA;
Members
cbSize
Size of this structure, in bytes.
hWnd
Handle to the window that receives notification messages associated with an icon in the taskbar status area. The Shell uses hWnd and uID to identify which icon to operate on when Shell_NotifyIcon is invoked.
uID
Application-defined identifier of the taskbar icon. The Shell uses hWnd and uID to identify which icon to operate on when Shell_NotifyIcon is invoked. You can have multiple icons associated with a single hWnd by assigning each a different uID.
uFlags
Flags that indicate which of the other members contain valid data. This member can be a combination of the following: Flag Description
NIF_ICON The hIcon member is valid.
NIF_MESSAGE The uCallbackMessage member is valid.
NIF_TIP The szTip member is valid.
NIF_STATE The dwState and dwStateMask members are valid.
NIF_INFO Use a balloon ToolTip instead of a standard ToolTip. The szInfo, uTimeout, szInfoTitle, and dwInfoFlags members are valid.
NIF_GUID Reserved.
uCallbackMessage
Application-defined message identifier. The system uses this identifier to send notifications to the window identified in hWnd. These notifications are sent when a mouse event occurs in the bounding rectangle of the icon, or when the icon is selected or activated with the keyboard. The wParam parameter of the message contains the identifier of the taskbar icon in which the event occurred. The lParam parameter holds the mouse or keyboard message associated with the event. For example, when the pointer moves over a taskbar icon, lParam is set to WM_MOUSEMOVE. See the Taskbar guide chapter for further discussion.
hIcon
Handle to the icon to be added, modified, or deleted.
szTip
Pointer to a null-terminated string with the text for a standard ToolTip. It can have a maximum of 64 characters including the terminating NULL.
For Version 5.0 and later, szTip can have a maximum of 128 characters, including the terminating NULL.
dwState
Version 5.0. State of the icon. There are two flags that can be set independently. Flag Description
NIS_HIDDEN The icon is hidden.
NIS_SHAREDICON The icon is shared.
dwStateMask
Version 5.0. A value that specifies which bits of the state member are retrieved or modified. For example, setting this member to NIS_HIDDEN causes only the item's hidden state to be retrieved.
szInfo
Version 5.0. Pointer to a null-terminated string with the text for a balloon ToolTip. It can have a maximum of 255 characters. To remove the ToolTip, set the NIF_INFO flag in uFlags and set szInfo to an empty string.
uTimeout
Union with uVersion. The timeout value, in milliseconds, for a balloon ToolTip. The system enforces minimum and maximum timeout values. uTimeout values that are too large are set to the maximum value and values that are too small default to the minimum value. The system minimum and maximum timeout values are currently set at 10 seconds and 30 seconds, respectively. See the remarks for further discussion of uTimeout.
uVersion
Version 5.0. Union with uTimeout. Specifies whether the Shell notify icon interface should use Windows 95 or Windows 2000 behavior. For more information on the differences in these two behaviors, see Shell_NotifyIcon. This member is only employed when using Shell_NotifyIcon to send an NIM_VERSION message. Value Description
0 Use the Windows 95 behavior. Use this value for applications designed for Windows versions prior to Windows 2000.
NOTIFYICON_VERSION Use the Windows 2000 behavior. Use this value for applications designed for Windows 2000 and later.
szInfoTitle
Version 5.0. Pointer to a null-terminated string containing a title for a balloon ToolTip. This title appears in boldface above the text. It can have a maximum of 63 characters.
dwInfoFlags
Version 5.0. Flags that can be set to add an icon to a balloon ToolTip. It is placed to the left of the title. If the szTitleInfo member is zero-length, the icon is not shown. These flags are mutually exclusive. Flag Description
NIIF_ERROR An error icon.
NIIF_INFO An information icon.
NIIF_NONE No icon.
NIIF_WARNING A warning icon.
NIIF_ICON_MASK Version 6.0. Reserved.
NIIF_NOSOUND Version 6.0. Do not play the associated sound. Applies only to balloon ToolTips.
guidItem
Version 6.0. Reserved.
Это все круто, но мне пример нужен, без примера никак.....
Ну посмотри в МСДН. Там же всего одна структура, попробуй экспериментальным путем разные значения...
Ну посмотри в МСДН. Там же всего одна структура, попробуй экспериментальным путем разные значения...
Конечно же посмотрб и попробую.... :)
Конечно же посмотрб и попробую.... :)
'
А как еню сделать при нажатии на иколнку???
'
А как еню сделать при нажатии на иколнку???
Аааа, тут не так все просто.
Я сам не делал, но рецепт слышал.
1)Надо создать меню в редакторе ресурсов.
2)Юзать ф-ю (наверное) TrackPopupMenu()
The TrackPopupMenu function displays a shortcut menu at the specified location and tracks the selection of items on the menu. The shortcut menu can appear anywhere on the screen.
To specify an area of the screen the menu should not overlap, use the TrackPopupMenuEx function.
BOOL TrackPopupMenu(
HMENU hMenu, // handle to shortcut menu
UINT uFlags, // options
int x, // horizontal position
int y, // vertical position
int nReserved, // reserved, must be zero
HWND hWnd, // handle to owner window
CONST RECT *prcRect // ignored
);
Parameters
hMenu
[in] Handle to the shortcut menu to be displayed. The handle can be obtained by calling CreatePopupMenu to create a new shortcut menu, or by calling GetSubMenu to retrieve a handle to a submenu associated with an existing menu item.
uFlags
[in] Use zero of more of these flags to specify function options.
Use one of the following flags to specify how the function positions the shortcut menu horizontally. Value Meaning
TPM_CENTERALIGN If this flag is set, the function centers the shortcut menu horizontally relative to the coordinate specified by the x parameter.
TPM_LEFTALIGN If this flag is set, the function positions the shortcut menu so that its left side is aligned with the coordinate specified by the x parameter.
TPM_RIGHTALIGN Positions the shortcut menu so that its right side is aligned with the coordinate specified by the x parameter.
Use one of the following flags to specify how the function positions the shortcut menu vertically. Value Meaning
TPM_BOTTOMALIGN If this flag is set, the function positions the shortcut menu so that its bottom side is aligned with the coordinate specified by the y parameter.
TPM_TOPALIGN If this flag is set, the function positions the shortcut menu so that its top side is aligned with the coordinate specified by the y parameter.
TPM_VCENTERALIGN If this flag is set, the function centers the shortcut menu vertically relative to the coordinate specified by the y parameter.
Use the following flags to determine the user selection without having to set up a parent window for the menu. Value Meaning
TPM_NONOTIFY If this flag is set, the function does not send notification messages when the user clicks on a menu item.
TPM_RETURNCMD If this flag is set, the function returns the menu item identifier of the user's selection in the return value.
Use one of the following flags to specify which mouse button the shortcut menu tracks. Value Meaning
TPM_LEFTBUTTON If this flag is set, the user can select menu items with only the left mouse button.
TPM_RIGHTBUTTON If this flag is set, the user can select menu items with both the left and right mouse buttons.
Windows 98/Me, Windows 2000/XP: Use any reasonable combination of the following flags to modify the animation of a menu. For example, by selecting a horizontal and a vertical flag you can achieve diagonal animation. Value Meaning
TPM_HORNEGANIMATION Animates the menu from right to left.
TPM_HORPOSANIMATION Animates the menu from left to right.
TPM_NOANIMATION Displays menu without animation.
TPM_VERNEGANIMATION Animates the menu from bottom to top.
TPM_VERPOSANIMATION Animates the menu from top to bottom.
For any animation to occur, the SystemParametersInfo function must set SPI_SETMENUANIMATION. Also, all the TPM_*ANIMATION flags, except TPM_NOANIMATION, are ignored if menu fade animation is on, See the SPI_GETMENUFADE flag in SystemParametersInfo.
Windows 98/Me, Windows 2000/XP: Use the TPM_RECURSE flag to display a menu when another menu is already displayed. This is intended to support context menus within a menu.
Windows XP: To have text layout from right-to-left, use TPM_LAYOUTRTL. By default, the text layout is left-to-right.
x
[in] Specifies the horizontal location of the shortcut menu, in screen coordinates.
y
[in] Specifies the vertical location of the shortcut menu, in screen coordinates.
nReserved
Reserved; must be zero.
hWnd
[in] Handle to the window that owns the shortcut menu. This window receives all messages from the menu. The window does not receive a WM_COMMAND message from the menu until the function returns.
If you specify TPM_NONOTIFY in the uFlags parameter, the function does not send messages to the window identified by hWnd. However, you must still pass a window handle in hWnd. It can be any window handle from your application.
prcRect
Ignored.
Return Values
If you specify TPM_RETURNCMD in the uFlags parameter, the return value is the menu-item identifier of the item that the user selected. If the user cancels the menu without making a selection, or if an error occurs, then the return value is zero.
If you do not specify TPM_RETURNCMD in the uFlags parameter, the return value is nonzero if the function succeeds and zero if it fails. To get extended error information, call GetLastError.
Remarks
To display a context menu for a notification icon, the current window must be the foreground window before the application calls TrackPopupMenu or TrackPopupMenuEx. Otherwise, the menu will not disappear when the user clicks outside of the menu or the window that created the menu (if it is visible). However, when the current window is the foreground window, the second time this menu is displayed, it displays and then immediately disappears. To correct this, you must force a task switch to the application that called TrackPopupMenu at some time in the near future. This is done by posting a benign message to the window or thread, as shown in the following code sample:
SetForegroundWindow(hDlg);
// Display the menu
TrackPopupMenu( hSubMenu,
TPM_RIGHTBUTTON,
pt.x,
pt.y,
0,
hDlg,
NULL);
PostMessage(hDlg, WM_NULL, 0, 0);
Example:
VOID APIENTRY DisplayContextMenu(HWND hwnd, POINT pt)
{
HMENU hmenu; // top-level menu
HMENU hmenuTrackPopup; // shortcut menu
// Load the menu resource.
if ((hmenu = LoadMenu(hinst, "ShortcutExample")) == NULL)
return;
// TrackPopupMenu cannot display the menu bar so get
// a handle to the first shortcut menu.
hmenuTrackPopup = GetSubMenu(hmenu, 0);
// Display the shortcut menu. Track the right mouse
// button.
TrackPopupMenu(hmenuTrackPopup,
TPM_LEFTALIGN | TPM_RIGHTBUTTON,
pt.x, pt.y, 0, hwnd, NULL);
// Destroy the menu.
DestroyMenu(hmenu);
}
Есть еще ф-я TrackPopupMenuEx()...
Как спрятать програмку в системный трей (радом с часами), чтобы он там сидела значком горела и не вопила....
System Tray: создание иконок и обработка поступающих сообщений
В данном разделе вам предлагается описание структуры NOTIFYICONDATA, объекты которой используются для создания иконок в System Tray (мне тяжело корректно перевести это устоявшееся название на русский язык), и для получения поступающих оттуда сообщений. Собственно область, которую называют System Tray представлена на следующем рисунке.
Структура NOTIFYICONDATA
DWORD cbSize;
HWND hWnd;
UINT uID;
UINT uFlags;
UINT uCallbackMessage;
HICON hIcon;
TCHAR szTip[64];
} NOTIFYICONDATA, *PNOTIFYICONDATA;
// Поля структуры:
// cbSize - размер структуры в байтах.
// hWnd - дескриптор окна, которое будет получать уведомляющие сообщения,
// ассоциированные с иконкой в трэе.
// uID - определенный приложением идентификатор иконки. Можно иметь
// множество иконок с одним hWnd и различными идентификаторами.
// uFlags - массив флагов, которые указывают какие из членов структуры
// содержат корректные значения:
// NIF_ICON - поле hIcon содержит корректное значение (позволяет создать
// иконку в трэе).
// NIF_MESSAGE - поле uCallbackMessage содержит корректное значение
// (позволяет получать сообщения от иконки в трэе).
// NIF_TIP - поле szTip содержит корректное значение (позволяет создать
// всплывающую подсказку для иконки в трэе).
// uCallbackMessage - определенный приложением идентификатор сообщения.
// Система использует этот идентификатор для посылки уведомляющих
// сообщений окну, дескриптор которого хранится в поле hWnd. Эти сообщения
// посылаются, когда происходит "мышиное" сообщение в прямоугольнике, где
// расположена иконка, или иконка выбирается или активизируется с помощью
// клавиатуры. Параметр сообщения wParam содержит при этом идентификатор
// иконки в трэе, где произошло событие, а параметр сообщения lParam -
// "мышиное" или клавиатурное сообщение, ассоциированное с событием.
// Пример события: щелчок мышки по иконке в трэе.
// hIcon - дескриптор иконки (иконку можно добавлять, заменять и удалять).
// szTip - указатель на завершающуюся нулем строку (char*) с текстом
// стандартной подсказки. Максимальный размер подсказки 64 символа,
// учитывая завершающий ноль.
И вообще читайте MSDN!!!!!
там все функции, структурки с опсаниями...иногда даже примеры...