Ejemplo n.º 1
0
INT_PTR CALLBACK DlgProcText(HWND hdlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	RECT rc, pos;
	HWND button;
	HMENU hMenu, hMenu1;
	TCHAR str[4096];
	switch (msg) {
	case WM_INITDIALOG:
		opt_startup = TRUE;
		// set windows position, make it top-most
		GetWindowRect(hdlg, &rc);
		SetWindowPos(hdlg, HWND_TOPMOST, rc.left, rc.top, 0, 0, SWP_NOSIZE);
		TranslateDialogDefault(hdlg);
		// generate the display text for variable list
		_tcsncpy(str, VAR_LIST_OPT, _countof(str) - 1);
		SetDlgItemText(hdlg, IDC_VARLIST, str);

		// make the more variable and other buttons flat
		SendDlgItemMessage(hdlg, IDC_MORE, BUTTONSETASFLATBTN, TRUE, 0);
		SendDlgItemMessage(hdlg, IDC_TM1, BUTTONSETASFLATBTN, TRUE, 0);
		SendDlgItemMessage(hdlg, IDC_TM2, BUTTONSETASFLATBTN, TRUE, 0);
		SendDlgItemMessage(hdlg, IDC_TM3, BUTTONSETASFLATBTN, TRUE, 0);
		SendDlgItemMessage(hdlg, IDC_TM4, BUTTONSETASFLATBTN, TRUE, 0);
		SendDlgItemMessage(hdlg, IDC_TM5, BUTTONSETASFLATBTN, TRUE, 0);
		SendDlgItemMessage(hdlg, IDC_TM6, BUTTONSETASFLATBTN, TRUE, 0);
		SendDlgItemMessage(hdlg, IDC_TM7, BUTTONSETASFLATBTN, TRUE, 0);
		SendDlgItemMessage(hdlg, IDC_TM8, BUTTONSETASFLATBTN, TRUE, 0);
		SendDlgItemMessage(hdlg, IDC_RESET, BUTTONSETASFLATBTN, TRUE, 0);
		// load the settings
		LoadTextSettings(hdlg);
		opt_startup = FALSE;
		return TRUE;

	case WM_COMMAND:
		if (opt_startup)	return TRUE;
		switch (LOWORD(wParam)) {
		case IDC_CTEXT:
		case IDC_BTITLE:
		case IDC_BTEXT:
		case IDC_NTEXT:
		case IDC_XTEXT:
		case IDC_ETEXT:
		case IDC_HTEXT:
		case IDC_BTITLE2:
			if (HIWORD(wParam) == EN_CHANGE)
				SendMessage(GetParent(hdlg), PSM_CHANGED, 0, 0);
			break;

		case IDC_MORE:
			// display custom variables list
			MoreVarList();
			break;

		case IDC_TM1:
		case IDC_TM2:
		case IDC_TM3:
		case IDC_TM4:
		case IDC_TM5:
		case IDC_TM6:
		case IDC_TM7:
		case IDC_TM8:
			// display the menu
			button = GetDlgItem(hdlg, LOWORD(wParam));
			GetWindowRect(button, &pos);
			hMenu = LoadMenu(hInst, MAKEINTRESOURCE(IDR_TMMENU));
			hMenu1 = GetSubMenu(hMenu, 0);
			TranslateMenu(hMenu1);
			switch (TrackPopupMenu(hMenu1, TPM_LEFTBUTTON | TPM_RETURNCMD, pos.left, pos.bottom, 0, hdlg, NULL)) {
			case ID_MPREVIEW:
				{
					// show the preview in a message box, using the weather data from the default station
					WEATHERINFO winfo = LoadWeatherInfo(opt.DefStn);
					GetDisplay(&winfo, *var[LOWORD(wParam) - IDC_TM1], str);
					MessageBox(NULL, str, TranslateT("Weather Protocol Text Preview"), MB_OK | MB_TOPMOST);
					break;
				}
			case ID_MRESET:
				unsigned varo = LOWORD(wParam) - IDC_TM1;
				// remove the old setting from db and free memory
				TCHAR* vartmp = *var[varo];
				wfree(&vartmp);
				SetTextDefault(varname[varo]);
				SetDlgItemText(hdlg, cname[varo], *var[varo]);
				break;
			}
			DestroyMenu(hMenu);
			break;

		case IDC_RESET:
			// left click action selection menu
			button = GetDlgItem(hdlg, IDC_RESET);
			GetWindowRect(button, &pos);
			hMenu = LoadMenu(hInst, MAKEINTRESOURCE(IDR_TMENU));
			hMenu1 = GetSubMenu(hMenu, 0);
			TranslateMenu(hMenu1);
			switch (TrackPopupMenu(hMenu1, TPM_LEFTBUTTON | TPM_RETURNCMD, pos.left, pos.bottom, 0, hdlg, NULL)) {
			case ID_T1:
				// reset to the strings in memory, discard all changes
				LoadTextSettings(hdlg);
				break;

			case ID_T2:
				// reset to the default setting
				FreeTextVar();
				SetTextDefault("CbBENHX");
				LoadTextSettings(hdlg);
				break;
			}
			DestroyMenu(hMenu);
			break;
		}
		return TRUE;
	case WM_NOTIFY:
		switch (((LPNMHDR)lParam)->code) {
		case PSN_APPLY:
			// save the option
			TCHAR textstr[MAX_TEXT_SIZE];
			// free memory for old settings
			FreeTextVar();
			// save new settings to memory
			GetDlgItemText(hdlg, IDC_CTEXT, textstr, _countof(textstr));
			wSetData(&opt.cText, textstr);
			GetDlgItemText(hdlg, IDC_BTEXT, textstr, _countof(textstr));
			wSetData(&opt.bText, textstr);
			GetDlgItemText(hdlg, IDC_BTITLE, textstr, _countof(textstr));
			wSetData(&opt.bTitle, textstr);
			GetDlgItemText(hdlg, IDC_ETEXT, textstr, _countof(textstr));
			wSetData(&opt.eText, textstr);
			GetDlgItemText(hdlg, IDC_NTEXT, textstr, _countof(textstr));
			wSetData(&opt.nText, textstr);
			GetDlgItemText(hdlg, IDC_HTEXT, textstr, _countof(textstr));
			wSetData(&opt.hText, textstr);
			GetDlgItemText(hdlg, IDC_XTEXT, textstr, _countof(textstr));
			wSetData(&opt.xText, textstr);
			GetDlgItemText(hdlg, IDC_BTITLE2, textstr, _countof(textstr));
			wSetData(&opt.sText, textstr);
			SaveOptions();
			UpdateAllInfo(0, 0);
			break;
		}
		break;
	}
	return FALSE;
}
Ejemplo n.º 2
0
//////////////////////////////////////////////////////////////////////////
//文件管理窗口过程
//////////////////////////////////////////////////////////////////////////
LRESULT CALLBACK FileDlgProc(HWND hDlg,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
	HWND hList = NULL;
	HWND hSBar = NULL;
	LPNMHDR lPnmhdr = NULL;
	switch (uMsg)
	{
	case WM_COMMAND:
		{
			switch(LOWORD(wParam))
			{
			case ID_POPUP_40001:
				{
					//打开(EXE运行)
					hList = GetDlgItem(hDlg,IDC_LIST1);
					int index = ListView_GetSelectionMark(hList);
					char szFile[NAMESIZE] = {0};
					char szType[10] = {0};
					ListView_GetItemText(hList,index,0,szType,sizeof(szType));
					ListView_GetItemText(hList,index,1,szFile,NAMESIZE);
					FileOpen(sockfd,szFile,szType);

				}
				break;
			case ID_POPUP_40002:
				{
					//返回
					FolderBack(sockfd);
				}
				break;
			case ID_POPUP_40004:
				{
					//下载
					hList = GetDlgItem(hDlg,IDC_LIST1);
					int index = ListView_GetSelectionMark(hList);
					char szFile[NAMESIZE] = {0};
					ListView_GetItemText(hList,index,1,szFile,NAMESIZE);
					sprintf(szFname,"%s",szFile);
					FileDownLoad(sockfd,szFile);
				}
				break;
			case ID_POPUP_40005:
				{
					//删除
					hList = GetDlgItem(hDlg,IDC_LIST1);
					int index = ListView_GetSelectionMark(hList);
					char szFile[NAMESIZE] = {0};
					ListView_GetItemText(hList,index,1,szFile,NAMESIZE);
					FileDelete(sockfd,szFile);
				}
				break;
			}
		}
		break;
	case WM_SOCKET:
		{
			switch(LOWORD(lParam))
			{
			case FD_WRITE:
				{
					//继续发送
					SendCmd(sockfd,NULL,NULL);
				}
				break;
			case FD_READ:
				{
					RecvCmd(sockfd);
				}
				break;
			case FD_CLOSE:
				{
					//SOCKET出错处理,MainFunc.H里 清理缓冲区
					SocketError(sockfd);
					EndDialog(hDlg,NULL);
				}
				break;
			}
		}
		break;
	case WM_NOTIFY:
		{
			lPnmhdr = (LPNMHDR)lParam;
			hList = GetDlgItem(hDlg,IDC_LIST1);
			if (lPnmhdr->hwndFrom==hList)
			{
				switch (lPnmhdr->code)
				{
				case NM_DBLCLK:
					{
						hList = GetDlgItem(hDlg,IDC_LIST1);
						int index = ListView_GetSelectionMark(hList);
						int count = ListView_GetItemCount(hList);
						char szType[10] = {0};
						ListView_GetItemText(hList,index,0,szType,sizeof(szType));
						if (strcmp(szType,"FILE")==0)
						{
							break;
						}
						if (index<count)
						{
							char szFile[NAMESIZE] = {0};
							char szType[10] = {0};
							ListView_GetItemText(hList,index,0,szType,sizeof(szType));
							ListView_GetItemText(hList,index,1,szFile,NAMESIZE);
							FileOpen(sockfd,szFile,szType);
						}
					}
					break;
				case NM_RCLICK:
					{
						HMENU hMenu = LoadMenu(hInst,MAKEINTRESOURCE(IDR_MENU1));
						hMenu = GetSubMenu(hMenu,0);
						POINT stPos;
						GetCursorPos(&stPos);
						TrackPopupMenu(hMenu,TPM_LEFTALIGN,stPos.x,stPos.y,NULL,hDlg,NULL);
					}
					break;
				}
			}
		}
		break;
	case WM_INITMENUPOPUP:
		{
			switch(LOWORD(lParam))
			{
			case 0:
				{
					//文件禁用:打开(EXE不禁用)
					//文件夹禁用:下载
					//盘符禁用:返回
					hList = GetDlgItem(hDlg,IDC_LIST1);
					int index = ListView_GetSelectionMark(hList);
					int count = ListView_GetItemCount(hList);
					if (index>=count && strlen(szTempPath)==0)
					{
						EnableMenuItem((HMENU)wParam,ID_POPUP_40001,MF_GRAYED);
						EnableMenuItem((HMENU)wParam,ID_POPUP_40002,MF_GRAYED);
						EnableMenuItem((HMENU)wParam,ID_POPUP_40004,MF_GRAYED);
						EnableMenuItem((HMENU)wParam,ID_POPUP_40005,MF_GRAYED);
					}
					else if (index>=count)
					{
						EnableMenuItem((HMENU)wParam,ID_POPUP_40001,MF_GRAYED);
						EnableMenuItem((HMENU)wParam,ID_POPUP_40002,MF_ENABLED);
						EnableMenuItem((HMENU)wParam,ID_POPUP_40004,MF_GRAYED);
						EnableMenuItem((HMENU)wParam,ID_POPUP_40005,MF_GRAYED);
					}
					else
					{
						char szType[NAMESIZE] = {0};
						ListView_GetItemText(hList,index,0,szType,NAMESIZE);
						if (strcmp(szType,"DRIVE")==0)
						{
							EnableMenuItem((HMENU)wParam,ID_POPUP_40001,MF_ENABLED);
							EnableMenuItem((HMENU)wParam,ID_POPUP_40002,MF_GRAYED);
							EnableMenuItem((HMENU)wParam,ID_POPUP_40004,MF_GRAYED);
							EnableMenuItem((HMENU)wParam,ID_POPUP_40005,MF_GRAYED);
						}
						else if (strcmp(szType,"FOLDER")==0)
						{
							EnableMenuItem((HMENU)wParam,ID_POPUP_40001,MF_ENABLED);
							EnableMenuItem((HMENU)wParam,ID_POPUP_40002,MF_ENABLED);
							EnableMenuItem((HMENU)wParam,ID_POPUP_40004,MF_GRAYED);
							EnableMenuItem((HMENU)wParam,ID_POPUP_40005,MF_ENABLED);
						}
						else if (strcmp(szType,"EXE")==0)
						{
							EnableMenuItem((HMENU)wParam,ID_POPUP_40001,MF_ENABLED);
							EnableMenuItem((HMENU)wParam,ID_POPUP_40002,MF_ENABLED);
							EnableMenuItem((HMENU)wParam,ID_POPUP_40004,MF_ENABLED);
							EnableMenuItem((HMENU)wParam,ID_POPUP_40005,MF_ENABLED);
						}
						else
						{
							EnableMenuItem((HMENU)wParam,ID_POPUP_40001,MF_GRAYED);
							EnableMenuItem((HMENU)wParam,ID_POPUP_40002,MF_ENABLED);
							EnableMenuItem((HMENU)wParam,ID_POPUP_40004,MF_ENABLED);
							EnableMenuItem((HMENU)wParam,ID_POPUP_40005,MF_ENABLED);
						}
					}
				}
			break;
			}
		}
		break;
	case WM_INITDIALOG:
		{
			sockfd = (SOCKET)lParam;
			//非拥塞模式
			WSAAsyncSelect(sockfd,hDlg,WM_SOCKET,FD_WRITE|FD_READ|FD_CLOSE);
			//获得远程主机盘符
			SendDriveList(sockfd);
			hList = GetDlgItem(hDlg,IDC_LIST1);
			//初始化ListControl
			InitFmgrList(hList);
			//初始化状态栏
			UpdataSBar(hDlg);
		}
		break;
	case WM_CLOSE:
		{
			EndDialog(hDlg,NULL);
		}
		break;
	default:
		break;
	}

	return FALSE;
}
Ejemplo n.º 3
0
LRESULT CALLBACK MenuDrawProc(HWND hwnd, UINT iMessage, WPARAM wParam,
    LPARAM lParam)
{
    static MENUITEM *start;
    static BOOL dragging;
    static HCURSOR oldcurs;
    static struct resRes *resData;
    static struct propertyFuncs *resFuncs;
    POINT mouse;
    RECT r;
    PAINTSTRUCT paint;
    HDC dc;
    LPCREATESTRUCT createStruct;
    struct resRes *menuData;
    int i;
    struct menuUndo *undo;
    switch (iMessage)
    {
        case WM_MDIACTIVATE:
            if ((HWND)lParam == hwnd)
            {
                doMaximize();
            }
            break;
        case WM_SETFOCUS:
            menuData = (struct resRes *)GetWindowLong(hwnd, 0);
            SetResourceProperties(resData, resFuncs);
            break;
        case EM_CANUNDO:
            menuData = (struct resRes *)GetWindowLong(hwnd, 0);
            return menuData->gd.undoData != NULL;
        case WM_KEYDOWN:
            menuData = (struct resRes *)GetWindowLong(hwnd, 0);
            switch (wParam)
            {
            case 'S':
                if (GetKeyState(VK_CONTROL) &0x80000000)
                {
                    PostMessage(hwnd, WM_COMMAND, IDM_SAVE, 0);
                }
                break;
            case 'Z':
                if (GetKeyState(VK_CONTROL) &0x80000000)
                {
                    PostMessage(hwnd, WM_COMMAND, IDM_UNDO, 0);
                }
                break;
            }
            break;
        case WM_CREATE:
            createStruct = (LPCREATESTRUCT)lParam;
            menuData = (struct resRes *)((LPMDICREATESTRUCT)(createStruct->lpCreateParams))->lParam;
            SetWindowLong(hwnd, 0, (long)menuData);
            menuData->activeHwnd = hwnd;
            resData = menuData;
            resFuncs = &menuFuncs;
            MarkUnexpanded(menuData->resource->u.menu->items);
            break;
        
        case WM_CLOSE:
            SendMessage(hwndSrcTab, TABM_REMOVE, 0, (LPARAM)hwnd);
            break;
        case WM_DESTROY:
            menuData = (struct resRes *)GetWindowLong(hwnd, 0);
            menuData->activeHwnd = NULL;
            undo = menuData->gd.undoData;
            menuData->gd.undoData = NULL;
            if (undo)
                menuData->gd.cantClearUndo = TRUE;
            while (undo)
            {
                struct menuUndo *next = undo->next;
                free(undo);
                undo = next;
            }
            break;
//        case WM_LBUTTONUP:
        case WM_MBUTTONUP:
        case WM_MBUTTONDOWN:
        case WM_RBUTTONDBLCLK:
        case WM_MBUTTONDBLCLK:
        case WM_RBUTTONUP:
            SetFocus(hwnd);
            return 1;
        case WM_PAINT:
            menuData = (struct resRes *)GetWindowLong(hwnd, 0);
            GetClientRect(hwnd, &r);
            dc = BeginPaint(hwnd, &paint);
            DoPaint(hwnd, dc, &paint, &r, menuData);
            EndPaint(hwnd, &paint);
            break;
        case WM_RBUTTONDOWN:
            menuData = (struct resRes *)GetWindowLong(hwnd, 0);
            SendMessage(hwnd, WM_COMMAND, ID_EDIT + (EN_KILLFOCUS << 16), 0);
            mouse.x = LOWORD(lParam);
            mouse.y = HIWORD(lParam);
            i = menuHitTest(hwnd, menuData, mouse);
            if (i)
            {
                HMENU menu, popup;
                SendMessage(hwnd, WM_COMMAND, MAKEWPARAM(ID_EDIT, CBN_KILLFOCUS), 0);
                menu = LoadMenuGeneric(hInstance, "RESMENUMENU");
                if (i & 2)
                    EnableMenuItem(menu, IDM_DELETE, MF_BYCOMMAND | MF_GRAYED);
                if (i & 4)
                    EnableMenuItem(menu, IDM_INSERT_SEPARATOR, MF_BYCOMMAND | MF_GRAYED);
                menuData->gd.selectedRow = mouse.y + menuData->gd.scrollPos.y;
                menuData->gd.selectedColumn = mouse.x + menuData->gd.scrollPos.x;
                popup = GetSubMenu(menu, 0);
                ClientToScreen(hwnd, &mouse);
                InsertBitmapsInMenu(popup);
                TrackPopupMenuEx(popup, TPM_TOPALIGN | TPM_LEFTALIGN | TPM_LEFTBUTTON, mouse.x,
                    mouse.y, hwnd, NULL);
                DestroyMenu(menu);
            }
            return 1;
        case WM_LBUTTONDBLCLK:
            SendMessage(hwnd, WM_COMMAND, ID_EDIT + (EN_KILLFOCUS << 16), 0);
            SetFocus(hwnd);
            menuData = (struct resRes *)GetWindowLong(hwnd, 0);
            mouse.x = LOWORD(lParam);
            mouse.y = HIWORD(lParam);
            SelectSubmenu(hwnd, menuData, mouse, TRUE);
            break;
        case WM_MOUSEMOVE:
            if (dragging)
            {
                menuData = (struct resRes *)GetWindowLong(hwnd, 0);
                mouse.x = LOWORD(lParam);
                mouse.y = HIWORD(lParam);
                menuData->gd.selectedMenu = start;
                i = menuHitTest(hwnd, menuData, mouse);
                if (!oldcurs)
                    oldcurs = GetCursor();
                SetCursor(i & 8 ? dragCur : noCur);
            }
            break;
        case WM_LBUTTONDOWN:
            SetFocus(hwnd);
            menuData = (struct resRes *)GetWindowLong(hwnd, 0);
            SendMessage(hwnd, WM_COMMAND, ID_EDIT + (EN_KILLFOCUS << 16), 0);
            mouse.x = LOWORD(lParam);
            mouse.y = HIWORD(lParam);
            i = menuHitTest(hwnd, menuData, mouse);
            if (i & 1)
            {
                resData = menuData;
                resFuncs = &menuItemFuncs;
                start = menuData->gd.selectedMenu;
                dragging = TRUE;
                SetCapture(hwnd);
            }
            else
            {
                resData = menuData;
                resFuncs = &menuFuncs;
            }
            SetResourceProperties(resData, resFuncs);
            break;
        case WM_LBUTTONUP:
            if (dragging)
            {
                dragging = FALSE;
                ReleaseCapture();
            }
            menuData = (struct resRes *)GetWindowLong(hwnd, 0);
            if (oldcurs)
            {
                if (GetCursor() == dragCur)
                {
                    mouse.x = LOWORD(lParam);
                    mouse.y = HIWORD(lParam);
                    i = menuHitTest(hwnd, menuData, mouse);
                    DoMove(menuData, start, menuData->gd.selectedMenu);
                }
                SetCursor(oldcurs);
                oldcurs = NULL;
            }
            else
            {
                SendMessage(hwnd, WM_COMMAND, ID_EDIT + (EN_KILLFOCUS << 16), 0);
                SetFocus(hwnd);
                mouse.x = LOWORD(lParam);
                mouse.y = HIWORD(lParam);
                SelectSubmenu(hwnd, menuData, mouse, FALSE);
            }
            break;
        case WM_COMMAND:
            menuData = (struct resRes *)GetWindowLong(hwnd, 0);
            switch (LOWORD(wParam))
            {
                case ID_EDIT:
                    if (HIWORD(wParam) == EN_KILLFOCUS)
                    {
                        static BOOL inKillFocus;
                        if (menuData->gd.editWindow && !inKillFocus)
                        {
                            char buf[256];
                            char buf2[256];
                            UndoChange(menuData, menuData->gd.selectedMenu);
                            buf[GetWindowText(menuData->gd.editWindow, buf, sizeof(buf))] = 0;
                            StringWToA(buf2, menuData->gd.selectedMenu->text, wcslen(menuData->gd.selectedMenu->text));
                            if (strcmp(buf, buf2))
                            {
                                ResGetHeap(workArea, menuData);
                                if (menuData->gd.selectedMenu->id)
                                    ResGetMenuItemName(menuData->gd.selectedMenu->id, buf);
                                StringAsciiToWChar(&menuData->gd.selectedMenu->text, buf, strlen(buf));
                                ResSetDirty(menuData);
                            }
                            InvalidateRect(hwnd, 0, FALSE);
                            inKillFocus = TRUE;
                            DestroyWindow(menuData->gd.editWindow);
                            inKillFocus = FALSE;
                            menuData->gd.editWindow = NULL;
                        }
                    }
                    break;
                case IDM_DELETE:
                case IDM_INSERT:
                case IDM_INSERT_SEPARATOR:
                    InsertDelete(hwnd, menuData, LOWORD(wParam));
                    break;
                case IDM_SAVE:
                    if (menuData->resource->changed)
                    {
                        ResSaveCurrent(workArea, menuData);
                    }
                    break;
                case IDM_UNDO:
                    DoUndo(menuData);
                    break;
            }
            break;
        case WM_VSCROLL:
            menuData = (struct resRes *)GetWindowLong(hwnd, 0);
            switch (LOWORD(wParam))
            {
            case SB_BOTTOM:
                menuData->gd.scrollPos.y = menuData->gd.scrollMax.y;
                break;
            case SB_TOP:
                menuData->gd.scrollPos.y = 0;
                break;
            case SB_LINEDOWN:
                menuData->gd.scrollPos.y += 8;
                break;
            case SB_LINEUP:
                menuData->gd.scrollPos.y -= 8;
                break;
            case SB_PAGEDOWN:
                menuData->gd.scrollPos.y += 64;
                break;
            case SB_PAGEUP:
                menuData->gd.scrollPos.y -= 64;
                break;
            case SB_ENDSCROLL:
                return 0;
            case SB_THUMBPOSITION:
            case SB_THUMBTRACK:
            {
                SCROLLINFO si;
                memset(&si, 0, sizeof(si));
                si.cbSize = sizeof(si);
                si.fMask = SIF_TRACKPOS;
                GetScrollInfo(hwnd, SB_VERT, &si);
                menuData->gd.scrollPos.y = si.nTrackPos;
            }
                break;
            default:
                return 0;
            }
            if (menuData->gd.scrollPos.y < 0)
                menuData->gd.scrollPos.y = 0;
            if (menuData->gd.scrollPos.y >= menuData->gd.scrollMax.y)
                menuData->gd.scrollPos.y = menuData->gd.scrollMax.y;
            SetScrollPos(hwnd, SB_VERT, menuData->gd.scrollPos.y, TRUE);
            InvalidateRect(hwnd,0,FALSE);
            return 0;
        case WM_HSCROLL:
            menuData = (struct resRes *)GetWindowLong(hwnd, 0);
            switch (LOWORD(wParam))
            {
            case SB_LEFT:
                menuData->gd.scrollPos.x = 0;
                break;
            case SB_RIGHT:
                menuData->gd.scrollPos.x = menuData->gd.scrollMax.x;
                break;
            case SB_LINELEFT:
                menuData->gd.scrollPos.x -= 8;
                break;
            case SB_LINERIGHT:
                menuData->gd.scrollPos.x += 8;
                break;
            case SB_PAGERIGHT:
                menuData->gd.scrollPos.x += 64;
                break;
            case SB_PAGELEFT:
                menuData->gd.scrollPos.x -= 64;
                break;
            case SB_ENDSCROLL:
                return 0;
            case SB_THUMBPOSITION:
            case SB_THUMBTRACK:
            {
                SCROLLINFO si;
                memset(&si, 0, sizeof(si));
                si.cbSize = sizeof(si);
                si.fMask = SIF_TRACKPOS;
                GetScrollInfo(hwnd, SB_HORZ, &si);
                menuData->gd.scrollPos.x = si.nTrackPos;
            }
                break;
            }
            if (menuData->gd.scrollPos.x < 0)
                menuData->gd.scrollPos.x = 0;
            if (menuData->gd.scrollPos.x >= menuData->gd.scrollMax.x)
                menuData->gd.scrollPos.x = menuData->gd.scrollMax.x;
            SetScrollPos(hwnd, SB_HORZ, menuData->gd.scrollPos.x, TRUE);
            SetWindowPos(menuData->gd.childWindow, NULL,
                         menuData->gd.origin.x - menuData->gd.scrollPos.x,
                         menuData->gd.origin.y - menuData->gd.scrollPos.y,
                         0,0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
                         
            InvalidateRect(hwnd,0,FALSE);
                       
            return 0;
        case WM_SIZE:
            InvalidateRect(hwnd, 0, FALSE);
            break;
        default:
            break;
    }
    return DefMDIChildProc(hwnd, iMessage, wParam, lParam);
}
Ejemplo n.º 4
0
INT_PTR CALLBACK WepWindowsDlgProc(
    _In_ HWND hwndDlg,
    _In_ UINT uMsg,
    _In_ WPARAM wParam,
    _In_ LPARAM lParam
    )
{
    PWINDOWS_CONTEXT context;

    if (uMsg == WM_INITDIALOG)
    {
        context = (PWINDOWS_CONTEXT)lParam;
        SetProp(hwndDlg, L"Context", (HANDLE)context);
    }
    else
    {
        context = (PWINDOWS_CONTEXT)GetProp(hwndDlg, L"Context");

        if (uMsg == WM_DESTROY)
            RemoveProp(hwndDlg, L"Context");
    }

    if (!context)
        return FALSE;

    switch (uMsg)
    {
    case WM_INITDIALOG:
        {
            PPH_STRING windowTitle;
            PH_RECTANGLE windowRectangle;

            context->TreeNewHandle = GetDlgItem(hwndDlg, IDC_LIST);
            WeInitializeWindowTree(hwndDlg, context->TreeNewHandle, &context->TreeContext);

            PhRegisterDialog(hwndDlg);

            PhInitializeLayoutManager(&context->LayoutManager, hwndDlg);
            PhAddLayoutItem(&context->LayoutManager, GetDlgItem(hwndDlg, IDC_LIST), NULL, PH_ANCHOR_ALL);

            if (MinimumSize.left == -1)
            {
                RECT rect;

                rect.left = 0;
                rect.top = 0;
                rect.right = 160;
                rect.bottom = 100;
                MapDialogRect(hwndDlg, &rect);
                MinimumSize = rect;
                MinimumSize.left = 0;
            }

            // Set up the window position and size.

            windowRectangle.Position = PhGetIntegerPairSetting(SETTING_NAME_WINDOWS_WINDOW_POSITION);
            windowRectangle.Size = PhGetIntegerPairSetting(SETTING_NAME_WINDOWS_WINDOW_SIZE);
            PhAdjustRectangleToWorkingArea(hwndDlg, &windowRectangle);

            MoveWindow(hwndDlg, windowRectangle.Left, windowRectangle.Top,
                windowRectangle.Width, windowRectangle.Height, FALSE);

            // Implement cascading by saving an offsetted rectangle.
            windowRectangle.Left += 20;
            windowRectangle.Top += 20;
            PhSetIntegerPairSetting(SETTING_NAME_WINDOWS_WINDOW_POSITION, windowRectangle.Position);

            windowTitle = WepGetWindowTitleForSelector(&context->Selector);
            SetWindowText(hwndDlg, windowTitle->Buffer);
            PhDereferenceObject(windowTitle);

            WepRefreshWindows(context);
        }
        break;
    case WM_DESTROY:
        {
            PhSaveWindowPlacementToSetting(SETTING_NAME_WINDOWS_WINDOW_POSITION, SETTING_NAME_WINDOWS_WINDOW_SIZE, hwndDlg);

            PhDeleteLayoutManager(&context->LayoutManager);
            PhUnregisterDialog(hwndDlg);

            WeDeleteWindowTree(&context->TreeContext);
            WepDeleteWindowSelector(&context->Selector);
            PhFree(context);
        }
        break;
    case WM_COMMAND:
        {
            switch (LOWORD(wParam))
            {
            case IDCANCEL:
            //case IDOK:
                DestroyWindow(hwndDlg);
                break;
            case IDC_REFRESH:
                WepRefreshWindows(context);
                break;
            case ID_SHOWCONTEXTMENU:
                {
                    POINT point;
                    PWE_WINDOW_NODE *windows;
                    ULONG numberOfWindows;
                    HMENU menu;
                    HMENU subMenu;

                    point.x = (SHORT)LOWORD(lParam);
                    point.y = (SHORT)HIWORD(lParam);

                    WeGetSelectedWindowNodes(
                        &context->TreeContext,
                        &windows,
                        &numberOfWindows
                        );

                    if (numberOfWindows != 0)
                    {
                        menu = LoadMenu(PluginInstance->DllBase, MAKEINTRESOURCE(IDR_WINDOW));
                        subMenu = GetSubMenu(menu, 0);
                        SetMenuDefaultItem(subMenu, ID_WINDOW_PROPERTIES, FALSE);

                        if (numberOfWindows == 1)
                        {
                            WINDOWPLACEMENT placement = { sizeof(placement) };
                            BYTE alpha;
                            ULONG flags;
                            ULONG i;
                            ULONG id;

                            // State

                            GetWindowPlacement(windows[0]->WindowHandle, &placement);

                            if (placement.showCmd == SW_MINIMIZE)
                                PhEnableMenuItem(subMenu, ID_WINDOW_MINIMIZE, FALSE);
                            else if (placement.showCmd == SW_MAXIMIZE)
                                PhEnableMenuItem(subMenu, ID_WINDOW_MAXIMIZE, FALSE);
                            else if (placement.showCmd == SW_NORMAL)
                                PhEnableMenuItem(subMenu, ID_WINDOW_RESTORE, FALSE);

                            // Visible

                            CheckMenuItem(subMenu, ID_WINDOW_VISIBLE,
                                (GetWindowLong(windows[0]->WindowHandle, GWL_STYLE) & WS_VISIBLE) ? MF_CHECKED : MF_UNCHECKED);

                            // Enabled

                            CheckMenuItem(subMenu, ID_WINDOW_ENABLED,
                                !(GetWindowLong(windows[0]->WindowHandle, GWL_STYLE) & WS_DISABLED) ? MF_CHECKED : MF_UNCHECKED);

                            // Always on Top

                            CheckMenuItem(subMenu, ID_WINDOW_ALWAYSONTOP,
                                (GetWindowLong(windows[0]->WindowHandle, GWL_EXSTYLE) & WS_EX_TOPMOST) ? MF_CHECKED : MF_UNCHECKED);

                            // Opacity

                            if (GetLayeredWindowAttributes(windows[0]->WindowHandle, NULL, &alpha, &flags))
                            {
                                if (!(flags & LWA_ALPHA))
                                    alpha = 255;
                            }
                            else
                            {
                                alpha = 255;
                            }

                            if (alpha == 255)
                            {
                                id = ID_OPACITY_OPAQUE;
                            }
                            else
                            {
                                id = 0;

                                // Due to integer division, we cannot use simple arithmetic to calculate which menu item to check.
                                for (i = 0; i < 10; i++)
                                {
                                    if (alpha == (BYTE)(255 * (i + 1) / 10))
                                    {
                                        id = ID_OPACITY_10 + i;
                                        break;
                                    }
                                }
                            }

                            if (id != 0)
                            {
                                CheckMenuRadioItem(subMenu, ID_OPACITY_10, ID_OPACITY_OPAQUE, id, MF_BYCOMMAND);
                            }
                        }
                        else
                        {
                            PhEnableAllMenuItems(subMenu, FALSE);
                            PhEnableMenuItem(subMenu, ID_WINDOW_COPY, TRUE);
                        }

                        TrackPopupMenu(
                            subMenu,
                            TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
                            point.x,
                            point.y,
                            0,
                            hwndDlg,
                            NULL
                            );

                        DestroyMenu(menu);
                    }
                }
                break;
            case ID_WINDOW_BRINGTOFRONT:
                {
                    PWE_WINDOW_NODE selectedNode;

                    if (selectedNode = WeGetSelectedWindowNode(&context->TreeContext))
                    {
                        WINDOWPLACEMENT placement = { sizeof(placement) };

                        GetWindowPlacement(selectedNode->WindowHandle, &placement);

                        if (placement.showCmd == SW_MINIMIZE)
                            ShowWindowAsync(selectedNode->WindowHandle, SW_RESTORE);
                        else
                            SetForegroundWindow(selectedNode->WindowHandle);
                    }
                }
                break;
            case ID_WINDOW_RESTORE:
                {
                    PWE_WINDOW_NODE selectedNode;

                    if (selectedNode = WeGetSelectedWindowNode(&context->TreeContext))
                    {
                        ShowWindowAsync(selectedNode->WindowHandle, SW_RESTORE);
                    }
                }
                break;
            case ID_WINDOW_MINIMIZE:
                {
                    PWE_WINDOW_NODE selectedNode;

                    if (selectedNode = WeGetSelectedWindowNode(&context->TreeContext))
                    {
                        ShowWindowAsync(selectedNode->WindowHandle, SW_MINIMIZE);
                    }
                }
                break;
            case ID_WINDOW_MAXIMIZE:
                {
                    PWE_WINDOW_NODE selectedNode;

                    if (selectedNode = WeGetSelectedWindowNode(&context->TreeContext))
                    {
                        ShowWindowAsync(selectedNode->WindowHandle, SW_MAXIMIZE);
                    }
                }
                break;
            case ID_WINDOW_CLOSE:
                {
                    PWE_WINDOW_NODE selectedNode;

                    if (selectedNode = WeGetSelectedWindowNode(&context->TreeContext))
                    {
                        PostMessage(selectedNode->WindowHandle, WM_CLOSE, 0, 0);
                    }
                }
                break;
            case ID_WINDOW_VISIBLE:
                {
                    PWE_WINDOW_NODE selectedNode;

                    if (selectedNode = WeGetSelectedWindowNode(&context->TreeContext))
                    {
                        if (IsWindowVisible(selectedNode->WindowHandle))
                        {
                            selectedNode->WindowVisible = FALSE;
                            ShowWindowAsync(selectedNode->WindowHandle, SW_HIDE);
                        }
                        else
                        {
                            selectedNode->WindowVisible = TRUE;
                            ShowWindowAsync(selectedNode->WindowHandle, SW_SHOW);
                        }

                        PhInvalidateTreeNewNode(&selectedNode->Node, TN_CACHE_COLOR);
                        TreeNew_InvalidateNode(context->TreeNewHandle, &selectedNode->Node);
                    }
                }
                break;
            case ID_WINDOW_ENABLED:
                {
                    PWE_WINDOW_NODE selectedNode;

                    if (selectedNode = WeGetSelectedWindowNode(&context->TreeContext))
                    {
                        EnableWindow(selectedNode->WindowHandle, !IsWindowEnabled(selectedNode->WindowHandle));
                    }
                }
                break;
            case ID_WINDOW_ALWAYSONTOP:
                {
                    PWE_WINDOW_NODE selectedNode;

                    if (selectedNode = WeGetSelectedWindowNode(&context->TreeContext))
                    {
                        LOGICAL topMost;

                        topMost = GetWindowLong(selectedNode->WindowHandle, GWL_EXSTYLE) & WS_EX_TOPMOST;
                        SetWindowPos(selectedNode->WindowHandle, topMost ? HWND_NOTOPMOST : HWND_TOPMOST,
                            0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
                    }
                }
                break;
            case ID_OPACITY_10:
            case ID_OPACITY_20:
            case ID_OPACITY_30:
            case ID_OPACITY_40:
            case ID_OPACITY_50:
            case ID_OPACITY_60:
            case ID_OPACITY_70:
            case ID_OPACITY_80:
            case ID_OPACITY_90:
            case ID_OPACITY_OPAQUE:
                {
                    PWE_WINDOW_NODE selectedNode;

                    if (selectedNode = WeGetSelectedWindowNode(&context->TreeContext))
                    {
                        ULONG opacity;

                        opacity = ((ULONG)LOWORD(wParam) - ID_OPACITY_10) + 1;

                        if (opacity == 10)
                        {
                            // Remove the WS_EX_LAYERED bit since it is not needed.
                            PhSetWindowExStyle(selectedNode->WindowHandle, WS_EX_LAYERED, 0);
                            RedrawWindow(selectedNode->WindowHandle, NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
                        }
                        else
                        {
                            // Add the WS_EX_LAYERED bit so opacity will work.
                            PhSetWindowExStyle(selectedNode->WindowHandle, WS_EX_LAYERED, WS_EX_LAYERED);
                            SetLayeredWindowAttributes(selectedNode->WindowHandle, 0, (BYTE)(255 * opacity / 10), LWA_ALPHA);
                        }
                    }
                }
                break;
            case ID_WINDOW_HIGHLIGHT:
                {
                    PWE_WINDOW_NODE selectedNode;

                    if (selectedNode = WeGetSelectedWindowNode(&context->TreeContext))
                    {
                        if (context->HighlightingWindow)
                        {
                            if (context->HighlightingWindowCount & 1)
                                WeInvertWindowBorder(context->HighlightingWindow);
                        }

                        context->HighlightingWindow = selectedNode->WindowHandle;
                        context->HighlightingWindowCount = 10;
                        SetTimer(hwndDlg, 9, 100, NULL);
                    }
                }
                break;
            case ID_WINDOW_GOTOTHREAD:
                {
                    PWE_WINDOW_NODE selectedNode;
                    PPH_PROCESS_ITEM processItem;
                    PPH_PROCESS_PROPCONTEXT propContext;

                    if (selectedNode = WeGetSelectedWindowNode(&context->TreeContext))
                    {
                        if (processItem = PhReferenceProcessItem(selectedNode->ClientId.UniqueProcess))
                        {
                            if (propContext = PhCreateProcessPropContext(WE_PhMainWndHandle, processItem))
                            {
                                PhSetSelectThreadIdProcessPropContext(propContext, selectedNode->ClientId.UniqueThread);
                                PhShowProcessProperties(propContext);
                                PhDereferenceObject(propContext);
                            }

                            PhDereferenceObject(processItem);
                        }
                        else
                        {
                            PhShowError(hwndDlg, L"The process does not exist.");
                        }
                    }
                }
                break;
            case ID_WINDOW_PROPERTIES:
                {
                    PWE_WINDOW_NODE selectedNode;

                    if (selectedNode = WeGetSelectedWindowNode(&context->TreeContext))
                        WeShowWindowProperties(WE_PhMainWndHandle, selectedNode->WindowHandle);
                }
                break;
            case ID_WINDOW_COPY:
                {
                    PPH_STRING text;

                    text = PhGetTreeNewText(context->TreeNewHandle, 0);
                    PhSetClipboardStringEx(hwndDlg, text->Buffer, text->Length);
                    PhDereferenceObject(text);
                }
                break;
            }
        }
        break;
    case WM_TIMER:
        {
            switch (wParam)
            {
            case 9:
                {
                    WeInvertWindowBorder(context->HighlightingWindow);

                    if (--context->HighlightingWindowCount == 0)
                        KillTimer(hwndDlg, 9);
                }
                break;
            }
        }
        break;
    case WM_SIZE:
        {
            PhLayoutManagerLayout(&context->LayoutManager);
        }
        break;
    case WM_SIZING:
        {
            PhResizingMinimumSize((PRECT)lParam, wParam, MinimumSize.right, MinimumSize.bottom);
        }
        break;
    case WM_WE_PLUSMINUS:
        {
            PWE_WINDOW_NODE node = (PWE_WINDOW_NODE)lParam;

            if (!node->Opened)
            {
                TreeNew_SetRedraw(context->TreeNewHandle, FALSE);
                WepAddChildWindows(context, node, node->WindowHandle, NULL, NULL);
                node->Opened = TRUE;
                TreeNew_SetRedraw(context->TreeNewHandle, TRUE);
            }
        }
        break;
    }

    return FALSE;
}
/*
================
rvGENavigator::WndProc

Window Procedure
================
*/
LRESULT CALLBACK rvGENavigator::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {
	rvGENavigator *nav = ( rvGENavigator * ) GetWindowLong( hWnd, GWL_USERDATA );
	switch( msg ) {
	case WM_INITMENUPOPUP:
		return SendMessage( gApp.GetMDIFrame( ), msg, wParam, lParam );
	case WM_ACTIVATE:
		common->ActivateTool( LOWORD( wParam ) != WA_INACTIVE );
		break;
	case WM_ERASEBKGND:
		return TRUE;
	case WM_DESTROY:
		gApp.GetOptions().SetWindowPlacement( "navigator", hWnd );
		break;
	case WM_CLOSE:
		gApp.GetOptions().SetNavigatorVisible( false );
		nav->Show( false );
		return 0;
	case WM_DRAWITEM: {
		DRAWITEMSTRUCT	*dis = ( DRAWITEMSTRUCT * ) lParam;
		idWindow		*window = ( idWindow * )dis->itemData;
		if( window ) {
			rvGEWindowWrapper	*wrapper	= rvGEWindowWrapper::GetWrapper( window );
			idStr				name    = window->GetName();
			RECT				rDraw;
			float				offset;
			bool				disabled;
			idWindow *parent = window;
			offset = 1;
			disabled = false;
			while( parent = parent->GetParent( ) ) {
				if( rvGEWindowWrapper::GetWrapper( parent )->IsHidden( ) ) {
					disabled = true;
				}
				offset += 10;
			}
			CopyRect( &rDraw, &dis->rcItem );
			rDraw.right = rDraw.left + GENAV_ITEMHEIGHT;
			rDraw.top ++;
			rDraw.right ++;
			FrameRect( dis->hDC, &rDraw, ( HBRUSH )GetStockObject( BLACK_BRUSH ) );
			rDraw.right --;
			FillRect( dis->hDC, &rDraw, GetSysColorBrush( COLOR_3DFACE ) );
			Draw3dRect( dis->hDC, &rDraw, GetSysColorBrush( COLOR_3DHILIGHT ), GetSysColorBrush( COLOR_3DSHADOW ) );
			InflateRect( &rDraw, -3, -3 );
			Draw3dRect( dis->hDC, &rDraw, GetSysColorBrush( COLOR_3DSHADOW ), GetSysColorBrush( COLOR_3DHILIGHT ) );
			if( !wrapper->IsHidden( ) ) {
				DrawIconEx( dis->hDC, rDraw.left, rDraw.top, disabled ? nav->mVisibleIconDisabled : nav->mVisibleIcon, 16, 16, 0, NULL, DI_NORMAL );
			}
			CopyRect( &rDraw, &dis->rcItem );
			rDraw.left += GENAV_ITEMHEIGHT;
			rDraw.left += 1;
			if( dis->itemState & ODS_SELECTED ) {
				FillRect( dis->hDC, &rDraw, GetSysColorBrush( COLOR_HIGHLIGHT ) );
			} else {
				FillRect( dis->hDC, &rDraw, GetSysColorBrush( COLOR_WINDOW ) );
			}
			if( wrapper->CanHaveChildren( ) && window->GetChildCount( ) ) {
				if( wrapper->IsExpanded( ) ) {
					DrawIconEx( dis->hDC, rDraw.left + offset, rDraw.top + 3, nav->mCollapseIcon, 16, 16, 0, NULL, DI_NORMAL );
				} else {
					DrawIconEx( dis->hDC, rDraw.left + offset, rDraw.top + 3, nav->mExpandIcon, 16, 16, 0, NULL, DI_NORMAL );
				}
			}
			HPEN pen = CreatePen( PS_SOLID, 1, GetSysColor( COLOR_3DSHADOW ) );
			HPEN oldpen = ( HPEN )SelectObject( dis->hDC, pen );
			MoveToEx( dis->hDC, rDraw.left, dis->rcItem.top, NULL );
			LineTo( dis->hDC, dis->rcItem.right, dis->rcItem.top );
			MoveToEx( dis->hDC, rDraw.left, dis->rcItem.bottom, NULL );
			LineTo( dis->hDC, dis->rcItem.right, dis->rcItem.bottom );
			SelectObject( dis->hDC, oldpen );
			DeleteObject( pen );
			rDraw.left += offset;
			rDraw.left += 20;
			int colorIndex = ( ( dis->itemState & ODS_SELECTED ) ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT );
			SetTextColor( dis->hDC, GetSysColor( colorIndex ) );
			DrawText( dis->hDC, name, name.Length(), &rDraw, DT_LEFT | DT_VCENTER | DT_SINGLELINE );
			if( wrapper->GetVariableDict().GetNumKeyVals( ) || wrapper->GetScriptDict().GetNumKeyVals( ) ) {
				DrawIconEx( dis->hDC, dis->rcItem.right - 16, ( dis->rcItem.bottom + dis->rcItem.top ) / 2 - 6, ( dis->itemState & ODS_SELECTED ) ? nav->mScriptsLightIcon : nav->mScriptsIcon, 13, 13, 0, NULL, DI_NORMAL );
			}
		}
		break;
	}
	case WM_MEASUREITEM: {
		MEASUREITEMSTRUCT *mis = ( MEASUREITEMSTRUCT * ) lParam;
		mis->itemHeight = 22;
		break;
	}
	case WM_CREATE: {
		LPCREATESTRUCT	cs;
		LVCOLUMN		col;
		// Attach the class to the window first
		cs = ( LPCREATESTRUCT ) lParam;
		nav = ( rvGENavigator * ) cs->lpCreateParams;
		SetWindowLong( hWnd, GWL_USERDATA, ( LONG )nav );
		// Create the List view
		nav->mTree = CreateWindowEx( 0, "SysListView32", "", WS_VSCROLL | WS_CHILD | WS_VISIBLE | LVS_REPORT | LVS_OWNERDRAWFIXED | LVS_NOCOLUMNHEADER | LVS_SHOWSELALWAYS, 0, 0, 0, 0, hWnd, ( HMENU )IDC_GUIED_WINDOWTREE, win32.hInstance, 0 );
		ListView_SetExtendedListViewStyle( nav->mTree, LVS_EX_FULLROWSELECT );
		ListView_SetBkColor( nav->mTree, GetSysColor( COLOR_3DFACE ) );
		ListView_SetTextBkColor( nav->mTree, GetSysColor( COLOR_3DFACE ) );
		nav->mListWndProc = ( WNDPROC )GetWindowLong( nav->mTree, GWL_WNDPROC );
		SetWindowLong( nav->mTree, GWL_USERDATA, ( LONG )nav );
		SetWindowLong( nav->mTree, GWL_WNDPROC, ( LONG )ListWndProc );
		// Insert the only column
		col.mask = 0;
		ListView_InsertColumn( nav->mTree, 0, &col );
		break;
	}
	case WM_SIZE: {
		RECT rClient;
		MoveWindow( nav->mTree, 0, 0, LOWORD( lParam ), HIWORD( lParam ), TRUE );
		GetClientRect( nav->mTree, &rClient );
		ListView_SetColumnWidth( nav->mTree, 0, rClient.right - rClient.left - 1 );
		break;
	}
	case WM_NCACTIVATE:
		return gApp.ToolWindowActivate( gApp.GetMDIFrame(), msg, wParam, lParam );
	case WM_NOTIFY: {
		LPNMHDR nh;
		nh = ( LPNMHDR ) lParam;
		switch( nh->code ) {
		case NM_CLICK:
		case NM_DBLCLK: {
			DWORD dwpos = GetMessagePos();
			LVHITTESTINFO info;
			info.pt.x = LOWORD( dwpos );
			info.pt.y = HIWORD( dwpos );
			MapWindowPoints( HWND_DESKTOP, nh->hwndFrom, &info.pt, 1 );
			int index = ListView_HitTest( nav->mTree, &info );
			if( index != -1 ) {
				RECT	rItem;
				int		offset;
				ListView_GetItemRect( nav->mTree, index, &rItem, LVIR_BOUNDS );
				LVITEM item;
				item.mask = LVIF_PARAM;
				item.iItem = index;
				ListView_GetItem( nav->mTree, &item );
				idWindow *window = ( idWindow * )item.lParam;
				rvGEWindowWrapper *wrapper = rvGEWindowWrapper::GetWrapper( window );
				offset = wrapper->GetDepth( ) * 10 + 1;
				if( info.pt.x < GENAV_ITEMHEIGHT ) {
					if( !rvGEWindowWrapper::GetWrapper( window )->IsHidden( ) ) {
						nav->mWorkspace->HideWindow( window );
					} else {
						nav->mWorkspace->UnhideWindow( window );
					}
				} else if( info.pt.x > GENAV_ITEMHEIGHT + offset && info.pt.x < GENAV_ITEMHEIGHT + offset + 16 ) {
					if( wrapper->CanHaveChildren( ) && window->GetChildCount( ) ) {
						if( wrapper->IsExpanded( ) ) {
							wrapper->Collapse( );
							nav->Update( );
						} else {
							wrapper->Expand( );
							nav->Update( );
						}
					}
				} else if( nh->code == NM_DBLCLK ) {
					SendMessage( gApp.GetMDIFrame( ), WM_COMMAND, MAKELONG( ID_GUIED_ITEM_PROPERTIES, 0 ), 0 );
				}
			}
			break;
		}
		case NM_RCLICK: {
			DWORD dwpos = GetMessagePos();
			LVHITTESTINFO info;
			info.pt.x = LOWORD( dwpos );
			info.pt.y = HIWORD( dwpos );
			MapWindowPoints( HWND_DESKTOP, nh->hwndFrom, &info.pt, 1 );
			int index = ListView_HitTest( nav->mTree, &info );
			if( index != -1 ) {
				ClientToScreen( hWnd, &info.pt );
				HMENU menu = GetSubMenu( LoadMenu( gApp.GetInstance(), MAKEINTRESOURCE( IDR_GUIED_ITEM_POPUP ) ), 0 );
				TrackPopupMenu( menu, TPM_RIGHTBUTTON | TPM_LEFTALIGN, info.pt.x, info.pt.y, 0, gApp.GetMDIFrame( ), NULL );
				DestroyMenu( menu );
			}
			break;
		}
		case LVN_ITEMCHANGED: {
			NMLISTVIEW *nml = ( NMLISTVIEW * ) nh;
			if( ( nml->uNewState & LVIS_SELECTED ) != ( nml->uOldState & LVIS_SELECTED ) ) {
				LVITEM item;
				item.iItem = nml->iItem;
				item.mask = LVIF_PARAM;
				ListView_GetItem( nav->mTree, &item );
				if( nml->uNewState & LVIS_SELECTED ) {
					nav->mWorkspace->GetSelectionMgr().Add( ( idWindow * )item.lParam, false );
				} else {
					nav->mWorkspace->GetSelectionMgr().Remove( ( idWindow * )item.lParam );
				}
			}
			break;
		}
		}
		break;
	}
	}
	return DefWindowProc( hWnd, msg, wParam, lParam );
}
Ejemplo n.º 6
0
bool CConEmuInside::TurnExplorerTipPane(wchar_t (&szAddMsg)[128])
{
	bool bRepeat = false;
	int nBtn = IDCANCEL;
	DWORD_PTR nRc;
	LRESULT lSendRc;

	if (gnOsVer < 0x600)
	{
		// WinXP, Win2k3
		nBtn = IDYES; // MessageBox(L"Tip pane is not found in Explorer window!\nThis pane is required for 'ConEmu Inside' mode.\nDo you want to show this pane?", MB_ICONQUESTION|MB_YESNO);
		if (nBtn == IDYES)
		{

		#if 0

			HWND hWorker = GetDlgItem(mh_InsideParentRoot, 0xA005);

			#ifdef _DEBUG
			if (hWorker)
			{
				HWND hReBar = FindWindowEx(hWorker, NULL, L"ReBarWindow32", NULL);
				if (hReBar)
				{
					POINT pt = {4,4};
					HWND hTool = ChildWindowFromPoint(hReBar, pt);
					if (hTool)
					{
						//TBBUTTON tb = {};
						//lSendRc = SendMessageTimeout(mh_InsideParentRoot, TB_GETBUTTON, 2, (LPARAM)&tb, SMTO_NOTIMEOUTIFNOTHUNG, 500, &nRc);
						//if (tb.idCommand)
						//{
						//	NMTOOLBAR nm = {{hTool, 0, TBN_DROPDOWN}, 32896/*tb.idCommand*/};
						//	lSendRc = SendMessageTimeout(mh_InsideParentRoot, WM_NOTIFY, 0, (LPARAM)&nm, SMTO_NOTIMEOUTIFNOTHUNG, 500, &nRc);
						//}
						lSendRc = SendMessageTimeout(mh_InsideParentRoot, WM_COMMAND, 32896, 0, SMTO_NOTIMEOUTIFNOTHUNG, 500, &nRc);
					}
				}
			}
			// There is no way to force "Tip pane" in WinXP
			// if popup menu "View -> Explorer bar" was not _shown_ at least once
			// In that case, Explorer ignores WM_COMMAND(41536) and does not reveal tip pane.
			HMENU hMenu1 = GetMenu(mh_InsideParentRoot), hMenu2 = NULL, hMenu3 = NULL;
			if (hMenu1)
			{
				hMenu2 = GetSubMenu(hMenu1, 2);
				//if (!hMenu2)
				//{
				//	lSendRc = SendMessageTimeout(mh_InsideParentRoot, WM_MENUSELECT, MAKELONG(2,MF_POPUP), (LPARAM)hMenu1, SMTO_NOTIMEOUTIFNOTHUNG, 1500, &nRc);
				//	hMenu2 = GetSubMenu(hMenu1, 2);
				//}

				if (hMenu2)
				{
					hMenu3 = GetSubMenu(hMenu2, 2);
				}
			}
			#endif
		#endif

			//INPUT keys[4] = {INPUT_KEYBOARD,INPUT_KEYBOARD,INPUT_KEYBOARD,INPUT_KEYBOARD};
			//keys[0].ki.wVk = VK_F10; keys[0].ki.dwFlags = 0; //keys[0].ki.wScan = MapVirtualKey(VK_F10,MAPVK_VK_TO_VSC);
			//keys[1].ki.wVk = VK_F10; keys[1].ki.dwFlags = KEYEVENTF_KEYUP; //keys[0].ki.wScan = MapVirtualKey(VK_F10,MAPVK_VK_TO_VSC);
			//keys[1].ki.wVk = 'V';
			//keys[2].ki.wVk = 'E';
			//keys[3].ki.wVk = 'T';

			//LRESULT lSentRc = 0;
			//SetForegroundWindow(mh_InsideParentRoot);
			//LRESULT lSentRc = SendInput(2/*countof(keys)*/, keys, sizeof(keys[0]));
			//lSentRc = SendMessageTimeout(mh_InsideParentRoot, WM_SYSKEYUP, 'V', 0, SMTO_NOTIMEOUTIFNOTHUNG, 5000, &nRc);

			lSendRc = SendMessageTimeout(mh_InsideParentRoot, WM_COMMAND, EMID_TIPOFDAY/*41536*/, 0, SMTO_NOTIMEOUTIFNOTHUNG, 5000, &nRc);
			UNREFERENCED_PARAMETER(lSendRc);

			mb_InsidePaneWasForced = true;
			// Подготовим сообщение если не удастся
			wcscpy_c(szAddMsg, L"Forcing Explorer to show Tip pane failed.\nShow pane yourself and recall ConEmu.\n\n");
		}
	}

	if (nBtn == IDYES)
	{
		// Первая проверка
		mh_InsideParentWND = mh_InsideParentRel = NULL;
		m_InsideIntegration = ii_Auto;
		InsideFindShellView(mh_InsideParentRoot);
		if (mh_InsideParentWND && mh_InsideParentRel)
		{
			bRepeat = true;
			goto wrap;
		}
		// Если не нашли - задержка и повторная проверка
		Sleep(500);
		mh_InsideParentWND = mh_InsideParentRel = NULL;
		m_InsideIntegration = ii_Auto;
		InsideFindShellView(mh_InsideParentRoot);
		if (mh_InsideParentWND && mh_InsideParentRel)
		{
			bRepeat = true;
			goto wrap;
		}

		// Last chance - try to post key sequence "F10 Left Left Down Down Down Left"
		// This will opens popup menu containing "Tip of the day" menuitem
		// "Esc Esc Esc" it and post {WM_COMMAND,EMID_TIPOFDAY} again
		WORD vkPostKeys[] = {VK_ESCAPE, VK_ESCAPE, VK_ESCAPE, VK_RIGHT, VK_RIGHT, VK_RIGHT, VK_DOWN, VK_DOWN, VK_DOWN, VK_RIGHT, VK_ESCAPE, VK_ESCAPE, VK_ESCAPE, 0};

		// Go
		if (SendVkKeySequence(mh_InsideParentRoot, vkPostKeys))
		{
			// Try again (Tip of the day)
			lSendRc = SendMessageTimeout(mh_InsideParentRoot, WM_COMMAND, EMID_TIPOFDAY/*41536*/, 0, SMTO_NOTIMEOUTIFNOTHUNG, 5000, &nRc);
			// Wait and check again
			Sleep(500);
			mh_InsideParentWND = mh_InsideParentRel = NULL;
			m_InsideIntegration = ii_Auto;
			InsideFindShellView(mh_InsideParentRoot);
			if (mh_InsideParentWND && mh_InsideParentRel)
			{
				bRepeat = true;
				goto wrap;
			}
		}
	}

wrap:
	if (bRepeat)
	{
		mb_TipPaneWasShown = true;
	}
	return bRepeat;
}
Ejemplo n.º 7
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine, int nCmdShow)
{
	char *pb;
	char *pe;
	WNDCLASS wc;
	HWND hWnd;
	HMENU hMainMenu;
	MSG msg;

	for (pb = lpCmdLine; *pb == ' ' || *pb == '\t'; pb++);
	for (pe = pb; *pe != '\0'; pe++);
	while (--pe > pb && (*pe == ' ' || *pe == '\t'));
	/* Now pb and pe point at respectively the first and last
	   non-blank character in lpCmdLine. If pb > pe then the command line
	   is blank. */
	if (*pb == '"' && *pe == '"')
		pb++;
	else
		pe++;
	*pe = '\0';
	/* Now pb contains the filename, if any, specified on the command line. */

	hWnd = FindWindow(WND_CLASS_NAME, NULL);
	if (hWnd != NULL) {
		/* as instance of WASAP is already running */
		if (*pb != '\0') {
			/* pass the filename */
			COPYDATASTRUCT cds = { 'O', (DWORD) (pe + 1 - pb), pb };
			SendMessage(hWnd, WM_COPYDATA, (WPARAM) NULL, (LPARAM) &cds);
		}
		else {
			/* bring the open dialog to top */
			HWND hChild = GetLastActivePopup(hWnd);
			if (hChild != hWnd)
				SetForegroundWindow(hChild);
		}
		return 0;
	}

	wc.style = CS_OWNDC | CS_VREDRAW | CS_HREDRAW;
	wc.lpfnWndProc = MainWndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = hInstance;
	wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APP));
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
	wc.lpszMenuName = NULL;
	wc.lpszClassName = WND_CLASS_NAME;
	RegisterClass(&wc);

	hWnd = CreateWindow(WND_CLASS_NAME,
		APP_TITLE,
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		CW_USEDEFAULT,
		NULL,
		NULL,
		hInstance,
		NULL
	);

	hStopIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_STOP));
	hPlayIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_PLAY));
	hMainMenu = LoadMenu(hInstance, MAKEINTRESOURCE(IDR_TRAYMENU));
	hTrayMenu = GetSubMenu(hMainMenu, 0);
	hSongMenu = CreatePopupMenu();
	InsertMenu(hTrayMenu, 1, MF_BYPOSITION | MF_ENABLED | MF_STRING | MF_POPUP,
	           (UINT_PTR) hSongMenu, "So&ng");
	hQualityMenu = GetSubMenu(hTrayMenu, 3);
	SetMenuDefaultItem(hTrayMenu, 0, TRUE);
	Tray_Add(hWnd, hStopIcon);
	SetQuality(hWnd, use_16bit, quality);
	if (*pb != '\0') {
		memcpy(strFile, pb, pe + 1 - pb);
		LoadFile(hWnd);
	}
	else
		SelectAndLoadFile(hWnd);
	while (GetMessage(&msg, NULL, 0, 0)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	WaveOut_Close();
	Tray_Delete(hWnd);
	DestroyMenu(hMainMenu);
	return 0;
}
Ejemplo n.º 8
0
void TrayIcon::OnContextMenu()
{
   HMENU hMenu, hmenuTrackPopup;
   POINT pt;
   HRESULT res;
   int i;
   Desktop * desk;

   //Get the "base" menu
   hMenu = Locale::GetInstance().LoadMenu(IDC_VIRTUALDIMENSION);
   if (hMenu == NULL)
      return;
   hmenuTrackPopup = GetSubMenu(hMenu, 0);

   //Append the list of desktops
   InsertMenu(hmenuTrackPopup, 0, MF_BYPOSITION | MF_SEPARATOR, 0, 0);

   i = 0;
   for( desk = deskMan->GetFirstDesktop();
        desk != NULL;
        desk = deskMan->GetNextDesktop())
   {
      MENUITEMINFO mii;

      mii.cbSize = sizeof(mii);
      mii.fMask = MIIM_STATE | MIIM_STRING | MIIM_ID | MIIM_DATA;
      if (desk->IsActive())
         mii.fState = MFS_CHECKED;
      else
         mii.fState = MFS_UNCHECKED;
      mii.dwItemData = (DWORD_PTR)desk;
      mii.dwTypeData = desk->GetText();
      mii.cch = (UINT)_tcslen(mii.dwTypeData);
      mii.wID = WM_USER + i++;
      InsertMenuItem(hmenuTrackPopup, 0, TRUE, &mii);
   }

   //And show the menu
   GetCursorPos(&pt);
   SetForegroundWindow(m_hWnd);
   res = TrackPopupMenu(hmenuTrackPopup, TPM_RIGHTBUTTON | TPM_RETURNCMD, pt.x, pt.y, 0, m_hWnd, NULL);

   //Process the resulting message
   if (res >= WM_USER)
   {
      Desktop * desk;
      MENUITEMINFO mii;

      mii.cbSize = sizeof(mii);
      mii.fMask = MIIM_DATA;
      GetMenuItemInfo(hmenuTrackPopup, res, FALSE, &mii);
      desk = (Desktop*)mii.dwItemData;

      deskMan->SwitchToDesktop(desk);
      InvalidateRect(m_hWnd, NULL, TRUE);
   }
   else
      PostMessage(m_hWnd, WM_COMMAND, res, 0);

   //Do not forget to destroy the menu
   DestroyMenu(hMenu);
}
Ejemplo n.º 9
0
static BOOL OnCreate(HWND hWnd)
{
    HMENU   hMenu;
    HMENU   hEditMenu;
    HMENU   hViewMenu;
    HMENU   hUpdateSpeedMenu;
    HMENU   hCPUHistoryMenu;
    int     nActivePage;
    int     nParts[3];
    RECT    rc;
    TCITEMW item;

    static WCHAR wszApplications[255];
    static WCHAR wszProcesses[255];
    static WCHAR wszPerformance[255];

    LoadStringW(hInst, IDS_APPLICATIONS, wszApplications, sizeof(wszApplications)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_PROCESSES, wszProcesses, sizeof(wszProcesses)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_PERFORMANCE, wszPerformance, sizeof(wszPerformance)/sizeof(WCHAR));

    SendMessageW(hMainWnd, WM_SETICON, ICON_BIG, (LPARAM)LoadIconW(hInst, MAKEINTRESOURCEW(IDI_TASKMANAGER)));
    SendMessageW(hMainWnd, WM_SETICON, ICON_SMALL,
                 (LPARAM)LoadImageW(hInst, MAKEINTRESOURCEW(IDI_TASKMANAGER), IMAGE_ICON,
                                    GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON),
                                    LR_SHARED));

    /* Initialize the Windows Common Controls DLL */
    InitCommonControls();

    /* Get the minimum window sizes */
    GetWindowRect(hWnd, &rc);
    nMinimumWidth = (rc.right - rc.left);
    nMinimumHeight = (rc.bottom - rc.top);

    /* Create the status bar */
    hStatusWnd = CreateStatusWindowW(WS_VISIBLE|WS_CHILD|WS_CLIPSIBLINGS|SBT_NOBORDERS, NULL, hWnd, STATUS_WINDOW);
    if(!hStatusWnd)
        return FALSE;

    /* Create the status bar panes */
    nParts[0] = 100;
    nParts[1] = 210;
    nParts[2] = 400;
    SendMessageW(hStatusWnd, SB_SETPARTS, 3, (LPARAM)nParts);

    /* Create tab pages */
    hTabWnd = GetDlgItem(hWnd, IDC_TAB);
#if 1
    hApplicationPage = CreateDialogW(hInst, MAKEINTRESOURCEW(IDD_APPLICATION_PAGE), hWnd, ApplicationPageWndProc);
    hProcessPage = CreateDialogW(hInst, MAKEINTRESOURCEW(IDD_PROCESS_PAGE), hWnd, ProcessPageWndProc);
    hPerformancePage = CreateDialogW(hInst, MAKEINTRESOURCEW(IDD_PERFORMANCE_PAGE), hWnd, PerformancePageWndProc);
#else
    hApplicationPage = CreateDialogW(hInst, MAKEINTRESOURCEW(IDD_APPLICATION_PAGE), hTabWnd, ApplicationPageWndProc);
    hProcessPage = CreateDialogW(hInst, MAKEINTRESOURCEW(IDD_PROCESS_PAGE), hTabWnd, ProcessPageWndProc);
    hPerformancePage = CreateDialogW(hInst, MAKEINTRESOURCEW(IDD_PERFORMANCE_PAGE), hTabWnd, PerformancePageWndProc);
#endif

    /* Insert tabs */
    memset(&item, 0, sizeof(TCITEMW));
    item.mask = TCIF_TEXT;
    item.pszText = wszApplications;
    SendMessageW(hTabWnd, TCM_INSERTITEMW, 0, (LPARAM)&item);
    memset(&item, 0, sizeof(TCITEMW));
    item.mask = TCIF_TEXT;
    item.pszText = wszProcesses;
    SendMessageW(hTabWnd, TCM_INSERTITEMW, 1, (LPARAM)&item);
    memset(&item, 0, sizeof(TCITEMW));
    item.mask = TCIF_TEXT;
    item.pszText = wszPerformance;
    SendMessageW(hTabWnd, TCM_INSERTITEMW, 2, (LPARAM)&item);

    /* Size everything correctly */
    GetClientRect(hWnd, &rc);
    nOldWidth = rc.right;
    nOldHeight = rc.bottom;
    /* nOldStartX = rc.left; */
    /*nOldStartY = rc.top;  */

#define PAGE_OFFSET_LEFT    17
#define PAGE_OFFSET_TOP     72
#define PAGE_OFFSET_WIDTH   (PAGE_OFFSET_LEFT*2)
#define PAGE_OFFSET_HEIGHT  (PAGE_OFFSET_TOP+32)

    if ((TaskManagerSettings.Left != 0) ||
        (TaskManagerSettings.Top != 0) ||
        (TaskManagerSettings.Right != 0) ||
        (TaskManagerSettings.Bottom != 0))
    {
        MoveWindow(hWnd, TaskManagerSettings.Left, TaskManagerSettings.Top, TaskManagerSettings.Right - TaskManagerSettings.Left, TaskManagerSettings.Bottom - TaskManagerSettings.Top, TRUE);
#ifdef __GNUC__TEST__
        MoveWindow(hApplicationPage, TaskManagerSettings.Left + PAGE_OFFSET_LEFT, TaskManagerSettings.Top + PAGE_OFFSET_TOP, TaskManagerSettings.Right - TaskManagerSettings.Left - PAGE_OFFSET_WIDTH, TaskManagerSettings.Bottom - TaskManagerSettings.Top - PAGE_OFFSET_HEIGHT, FALSE);
        MoveWindow(hProcessPage, TaskManagerSettings.Left + PAGE_OFFSET_LEFT, TaskManagerSettings.Top + PAGE_OFFSET_TOP, TaskManagerSettings.Right - TaskManagerSettings.Left - PAGE_OFFSET_WIDTH, TaskManagerSettings.Bottom - TaskManagerSettings.Top - PAGE_OFFSET_HEIGHT, FALSE);
        MoveWindow(hPerformancePage, TaskManagerSettings.Left + PAGE_OFFSET_LEFT, TaskManagerSettings.Top + PAGE_OFFSET_TOP, TaskManagerSettings.Right - TaskManagerSettings.Left - PAGE_OFFSET_WIDTH, TaskManagerSettings.Bottom - TaskManagerSettings.Top - PAGE_OFFSET_HEIGHT, FALSE);
#endif
    }
    if (TaskManagerSettings.Maximized)
        ShowWindow(hWnd, SW_MAXIMIZE);

    /* Set the always on top style */
    hMenu = GetMenu(hWnd);
    hEditMenu = GetSubMenu(hMenu, 1);
    hViewMenu = GetSubMenu(hMenu, 2);
    hUpdateSpeedMenu = GetSubMenu(hViewMenu, 1);
    hCPUHistoryMenu = GetSubMenu(hViewMenu, 7);

    /* Check or uncheck the always on top menu item */
    if (TaskManagerSettings.AlwaysOnTop) {
        CheckMenuItem(hEditMenu, ID_OPTIONS_ALWAYSONTOP, MF_BYCOMMAND|MF_CHECKED);
        SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
    } else {
        CheckMenuItem(hEditMenu, ID_OPTIONS_ALWAYSONTOP, MF_BYCOMMAND|MF_UNCHECKED);
        SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
    }

    /* Check or uncheck the minimize on use menu item */
    if (TaskManagerSettings.MinimizeOnUse)
        CheckMenuItem(hEditMenu, ID_OPTIONS_MINIMIZEONUSE, MF_BYCOMMAND|MF_CHECKED);
    else
        CheckMenuItem(hEditMenu, ID_OPTIONS_MINIMIZEONUSE, MF_BYCOMMAND|MF_UNCHECKED);

    /* Check or uncheck the hide when minimized menu item */
    if (TaskManagerSettings.HideWhenMinimized)
        CheckMenuItem(hEditMenu, ID_OPTIONS_HIDEWHENMINIMIZED, MF_BYCOMMAND|MF_CHECKED);
    else
        CheckMenuItem(hEditMenu, ID_OPTIONS_HIDEWHENMINIMIZED, MF_BYCOMMAND|MF_UNCHECKED);

    /* Check or uncheck the show 16-bit tasks menu item */
    if (TaskManagerSettings.Show16BitTasks)
        CheckMenuItem(hEditMenu, ID_OPTIONS_SHOW16BITTASKS, MF_BYCOMMAND|MF_CHECKED);
    else
        CheckMenuItem(hEditMenu, ID_OPTIONS_SHOW16BITTASKS, MF_BYCOMMAND|MF_UNCHECKED);

    if (TaskManagerSettings.View_LargeIcons)
        CheckMenuRadioItem(hViewMenu, ID_VIEW_LARGE, ID_VIEW_DETAILS, ID_VIEW_LARGE, MF_BYCOMMAND);
    else if (TaskManagerSettings.View_SmallIcons)
        CheckMenuRadioItem(hViewMenu, ID_VIEW_LARGE, ID_VIEW_DETAILS, ID_VIEW_SMALL, MF_BYCOMMAND);
    else
        CheckMenuRadioItem(hViewMenu, ID_VIEW_LARGE, ID_VIEW_DETAILS, ID_VIEW_DETAILS, MF_BYCOMMAND);

    if (TaskManagerSettings.ShowKernelTimes)
        CheckMenuItem(hViewMenu, ID_VIEW_SHOWKERNELTIMES, MF_BYCOMMAND|MF_CHECKED);
    else
        CheckMenuItem(hViewMenu, ID_VIEW_SHOWKERNELTIMES, MF_BYCOMMAND|MF_UNCHECKED);

    if (TaskManagerSettings.UpdateSpeed == 1)
        CheckMenuRadioItem(hUpdateSpeedMenu, ID_VIEW_UPDATESPEED_HIGH, ID_VIEW_UPDATESPEED_PAUSED, ID_VIEW_UPDATESPEED_HIGH, MF_BYCOMMAND);
    else if (TaskManagerSettings.UpdateSpeed == 2)
        CheckMenuRadioItem(hUpdateSpeedMenu, ID_VIEW_UPDATESPEED_HIGH, ID_VIEW_UPDATESPEED_PAUSED, ID_VIEW_UPDATESPEED_NORMAL, MF_BYCOMMAND);
    else if (TaskManagerSettings.UpdateSpeed == 4)
        CheckMenuRadioItem(hUpdateSpeedMenu, ID_VIEW_UPDATESPEED_HIGH, ID_VIEW_UPDATESPEED_PAUSED, ID_VIEW_UPDATESPEED_LOW, MF_BYCOMMAND);
    else
        CheckMenuRadioItem(hUpdateSpeedMenu, ID_VIEW_UPDATESPEED_HIGH, ID_VIEW_UPDATESPEED_PAUSED, ID_VIEW_UPDATESPEED_PAUSED, MF_BYCOMMAND);

    if (TaskManagerSettings.CPUHistory_OneGraphPerCPU)
        CheckMenuRadioItem(hCPUHistoryMenu, ID_VIEW_CPUHISTORY_ONEGRAPHALL, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, MF_BYCOMMAND);
    else
        CheckMenuRadioItem(hCPUHistoryMenu, ID_VIEW_CPUHISTORY_ONEGRAPHALL, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, ID_VIEW_CPUHISTORY_ONEGRAPHALL, MF_BYCOMMAND);

    nActivePage = TaskManagerSettings.ActiveTabPage;
    SendMessageW(hTabWnd, TCM_SETCURFOCUS, 0, 0);
    SendMessageW(hTabWnd, TCM_SETCURFOCUS, 1, 0);
    SendMessageW(hTabWnd, TCM_SETCURFOCUS, 2, 0);
    SendMessageW(hTabWnd, TCM_SETCURFOCUS, nActivePage, 0);

    if (TaskManagerSettings.UpdateSpeed == 1)
        SetTimer(hWnd, 1, 1000, NULL);
    else if (TaskManagerSettings.UpdateSpeed == 2)
        SetTimer(hWnd, 1, 2000, NULL);
    else if (TaskManagerSettings.UpdateSpeed == 4)
        SetTimer(hWnd, 1, 4000, NULL);

    /*
     * Refresh the performance data
     * Sample it twice so we can establish
     * the delta values & cpu usage
     */
    PerfDataRefresh();
    PerfDataRefresh();

    RefreshApplicationPage();
    RefreshProcessPage();
    RefreshPerformancePage();

    TrayIcon_ShellAddTrayIcon();

    return TRUE;
}
Ejemplo n.º 10
0
INT_PTR CALLBACK DlgProcDisplayData(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	DBVARIANT dbv;
	RECT rc;
	TCHAR url[300];
	MCONTACT hContact;

	switch (msg) {
	case WM_INITDIALOG:
		TranslateDialogDefault(hwndDlg);
		{
			MCONTACT hContact2 = lParam;

			SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) hContact2);
			WindowList_Add(hWindowList, hwndDlg, hContact2);

			url[0] = '\0';
			if (!db_get_ts(hContact2, MODULENAME, URL_KEY, &dbv)) {
				_tcsncpy_s(url, dbv.ptszVal, _TRUNCATE);
				db_free(&dbv);
			}
			SetDlgItemText(hwndDlg, IDC_OPEN_URL, FixButtonText(url, _countof(url)));

			char preservename[100];
			if (!db_get_s(hContact2, MODULENAME, PRESERVE_NAME_KEY, &dbv)) {
				strncpy_s(preservename, _countof(preservename), dbv.pszVal, _TRUNCATE);
				db_free(&dbv);
			}
			else preservename[0] = 0;
			SetWindowTextA(hwndDlg, preservename);

			SendMessage(hwndDlg, WM_SETICON, ICON_SMALL, (LPARAM) LoadIcon(hInst, MAKEINTRESOURCE(IDI_SITE)));

			// //////
			COLORREF colour = BackgoundClr;
			COLORREF txtcolor;
			SendDlgItemMessage(hwndDlg, IDC_DATA, EM_SETBKGNDCOLOR, 0, colour);

			SendDlgItemMessage(hwndDlg, IDC_UPDATE_BUTTON, BM_SETIMAGE, IMAGE_ICON, (LPARAM) LoadImage(hInst, MAKEINTRESOURCE(IDI_UPDATE), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0));
			SendDlgItemMessage(hwndDlg, IDC_UPDATE_BUTTON, BUTTONADDTOOLTIP, (WPARAM) TranslateT("Update data"), BATF_TCHAR);

			SendDlgItemMessage(hwndDlg, IDC_FIND_BUTTON, BM_SETIMAGE, IMAGE_ICON, (LPARAM) LoadImage(hInst, MAKEINTRESOURCE(IDI_FIND), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0));
			SendDlgItemMessage(hwndDlg, IDC_FIND_BUTTON, BUTTONADDTOOLTIP, (WPARAM) TranslateT("Find"), BATF_TCHAR);

			SendDlgItemMessage(hwndDlg, IDC_OPTIONS_BUTTON, BM_SETIMAGE, IMAGE_ICON, (LPARAM) LoadImage(hInst, MAKEINTRESOURCE(IDI_OPTIONS), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0));
			SendDlgItemMessage(hwndDlg, IDC_OPTIONS_BUTTON, BUTTONADDTOOLTIP, (WPARAM) TranslateT("Contact options"), BATF_TCHAR);

			SendDlgItemMessage(hwndDlg, IDC_ALERT_BUTTON, BM_SETIMAGE, IMAGE_ICON, (LPARAM) LoadImage(hInst, MAKEINTRESOURCE(IDI_ALERT), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0));
			SendDlgItemMessage(hwndDlg, IDC_ALERT_BUTTON, BUTTONADDTOOLTIP, (WPARAM) TranslateT("Alert options"), BATF_TCHAR);

			SendDlgItemMessage(hwndDlg, IDC_STOP, BM_SETIMAGE, IMAGE_ICON, (LPARAM) LoadImage(hInst, MAKEINTRESOURCE(IDI_STOP), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0));
			SendDlgItemMessage(hwndDlg, IDC_STOP, BUTTONADDTOOLTIP, (WPARAM) TranslateT("Stop processing"), BATF_TCHAR);

			SendDlgItemMessage(hwndDlg, IDC_OPEN_URL, BUTTONADDTOOLTIP, (WPARAM) TranslateT("Click here to open this URL in a browser window."), BATF_TCHAR);

			if (!db_get_b(hContact2, MODULENAME, ON_TOP_KEY, 0)) {
				SendDlgItemMessage(hwndDlg, IDC_STICK_BUTTON, BM_SETIMAGE, IMAGE_ICON, (LPARAM) LoadImage(hInst, MAKEINTRESOURCE(IDI_UNSTICK), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0));
				SendDlgItemMessage(hwndDlg, IDC_STICK_BUTTON, BUTTONADDTOOLTIP, (WPARAM) TranslateT("Stick to the front"), BATF_TCHAR);
			}
			else {
				SendDlgItemMessage(hwndDlg, IDC_STICK_BUTTON, BM_SETIMAGE, IMAGE_ICON, (LPARAM) LoadImage(hInst, MAKEINTRESOURCE(IDI_STICK), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0));
				SendDlgItemMessage(hwndDlg, IDC_STICK_BUTTON, BUTTONADDTOOLTIP, (WPARAM) TranslateT("Disable stick to the front"), BATF_TCHAR);
			}

			SendDlgItemMessage(hwndDlg, IDC_DATA, WM_SETFONT, (WPARAM) h_font, 1);

			txtcolor = TextClr;

			SetDlgItemText(hwndDlg, IDC_DATA, _T(""));

			InvalidateRect(hwndDlg, NULL, 1);

			SendDlgItemMessage(hwndDlg, IDC_DATA, EM_AUTOURLDETECT, 1, 0);
			int mask = (int)SendDlgItemMessage(hwndDlg, IDC_DATA, EM_GETEVENTMASK, 0, 0);

			SendDlgItemMessage(hwndDlg, IDC_DATA, EM_SETEVENTMASK, 0, mask | ENM_LINK | ENM_MOUSEEVENTS);

			SendDlgItemMessage(hwndDlg, IDC_STICK_BUTTON, BUTTONSETASFLATBTN, 0, 0);
			SendDlgItemMessage(hwndDlg, IDC_UPDATE_BUTTON, BUTTONSETASFLATBTN, 0, 0);
			SendDlgItemMessage(hwndDlg, IDC_FIND_BUTTON, BUTTONSETASFLATBTN, 0, 0);
			SendDlgItemMessage(hwndDlg, IDC_OPTIONS_BUTTON, BUTTONSETASFLATBTN, 0, 0);
			SendDlgItemMessage(hwndDlg, IDC_ALERT_BUTTON, BUTTONSETASFLATBTN, 0, 0);
			SendDlgItemMessage(hwndDlg, IDC_STOP, BUTTONSETASFLATBTN, 0, 0);

			SendDlgItemMessage(hwndDlg, IDC_OPEN_URL, BUTTONSETASFLATBTN, 0, 0);

			HDC hdc = GetDC(GetDlgItem(hwndDlg, IDC_STATUSBAR));
			SelectObject(hdc, (HFONT) SendDlgItemMessage(hwndDlg, IDC_STATUSBAR, WM_GETFONT, 0, 0));
			SIZE textSize;
			GetTextExtentPoint32(hdc, tszSizeString, _countof(tszSizeString), &textSize);
			int partWidth[2] = { textSize.cx, -1 };
			ReleaseDC(GetDlgItem(hwndDlg, IDC_STATUSBAR), hdc);

			SendDlgItemMessage(hwndDlg, IDC_STATUSBAR, SB_SETPARTS, _countof(partWidth), (LPARAM)partWidth);
			SendDlgItemMessage(hwndDlg, IDC_STATUSBAR, SB_SETTEXT, 1 | SBT_OWNERDRAW, 0);

			if ( db_get_b(NULL, MODULENAME, SAVE_INDIVID_POS_KEY, 0))
				Utils_RestoreWindowPosition(hwndDlg, hContact2, MODULENAME, "WV");
		}
		break;

	case WM_NOTIFY:
		switch (((NMHDR *) lParam)->code) {
		case EN_MSGFILTER:
			switch (((MSGFILTER *) lParam)->msg) {
			case WM_RBUTTONUP:
				{
					POINT  pt;
					CHARRANGE sel, all = {0, -1};

					HMENU hSubMenu = GetSubMenu(hMenu, 0);
					TranslateMenu(hSubMenu);
					SendMessage(((NMHDR *) lParam)->hwndFrom, EM_EXGETSEL, 0, (LPARAM) & sel);

					EnableMenuItem(hSubMenu, IDM_COPY, MF_ENABLED);
					EnableMenuItem(hSubMenu, IDM_CUT, MF_ENABLED);
					EnableMenuItem(hSubMenu, IDM_DELETE, MF_ENABLED);

					if (sel.cpMin == sel.cpMax) {
						EnableMenuItem(hSubMenu, IDM_COPY, MF_BYCOMMAND | MF_GRAYED);
						EnableMenuItem(hSubMenu, IDM_CUT, MF_BYCOMMAND | MF_GRAYED);
						EnableMenuItem(hSubMenu, IDM_DELETE, MF_BYCOMMAND | MF_GRAYED);
					}
					pt.x = (short) LOWORD(((ENLINK *) lParam)->lParam);
					pt.y = (short) HIWORD(((ENLINK *) lParam)->lParam);
					ClientToScreen(((NMHDR *) lParam)->hwndFrom, &pt);
					switch (TrackPopupMenu(hSubMenu, TPM_RETURNCMD, pt.x, pt.y, 0, hwndDlg, NULL)) {
					case IDM_COPY:
						SendMessage(((NMHDR *) lParam)->hwndFrom, WM_COPY, 0, 0);
						break;

					case IDM_COPYALL:
						SendMessage(((NMHDR *) lParam)->hwndFrom, EM_EXSETSEL, 0, (LPARAM) & all);
						SendMessage(((NMHDR *) lParam)->hwndFrom, WM_COPY, 0, 0);
						SendMessage(((NMHDR *) lParam)->hwndFrom, EM_EXSETSEL, 0, (LPARAM) & sel);
						break;

					case IDM_SELECTALL:
						SendMessage(((NMHDR *) lParam)->hwndFrom, EM_EXSETSEL, 0, (LPARAM) & all);
						break;

					case IDM_CUT:
						SendMessage(((NMHDR *) lParam)->hwndFrom, WM_CUT, 0, 0);
						break;

					case IDM_PASTE:
						SendMessage(((NMHDR *) lParam)->hwndFrom, WM_PASTE, 0, 0);
						break;

					case IDM_DELETE:
						SendMessage(((NMHDR *) lParam)->hwndFrom, WM_CLEAR, 0, 0);
						break;

					case IDM_CLEAR_ALL:
						SetDlgItemTextA(hwndDlg, IDC_DATA, "");
						SetFocus(GetDlgItem(hwndDlg, IDC_DATA));
						break;
					}
				}
			}
			break;

		case EN_LINK:
			switch (((ENLINK *) lParam)->msg) {
			case WM_RBUTTONDOWN:
			case WM_LBUTTONUP:
				CHARRANGE sel;
				SendDlgItemMessage(hwndDlg, IDC_DATA, EM_EXGETSEL, 0, (LPARAM) & sel);
				if (sel.cpMin != sel.cpMax)
					break;

				TEXTRANGEA tr;
				tr.chrg = ((ENLINK *) lParam)->chrg;
				tr.lpstrText = (char*)malloc(tr.chrg.cpMax - tr.chrg.cpMin + 8);

				SendDlgItemMessage(hwndDlg, IDC_DATA, EM_GETTEXTRANGE, 0, (LPARAM) & tr);
				if (strchr(tr.lpstrText, '@') != NULL && strchr(tr.lpstrText, ':') == NULL && strchr(tr.lpstrText, '/') == NULL) {
					memmove(tr.lpstrText + 7, tr.lpstrText, tr.chrg.cpMax - tr.chrg.cpMin + 1);
					memcpy(tr.lpstrText, "mailto:", 7);
				}

				Utils_OpenUrl(tr.lpstrText);
				SetFocus(GetDlgItem(hwndDlg, IDC_DATA));

				free(tr.lpstrText);
				break;
			}
		}
		break; // notify

	case WM_COMMAND:
		switch (LOWORD(wParam)) {
		case IDC_OPEN_URL:
			GetDlgItemText(hwndDlg, IDC_OPEN_URL, url, _countof(url));
			Utils_OpenUrlT(url);  
			db_set_w(wParam, MODULENAME, "Status", ID_STATUS_ONLINE); 
			break;

		case IDC_UPDATE_BUTTON:
			if (hContact = FindContactByUrl(hwndDlg)) {
				EnableWindow(GetDlgItem(hwndDlg, IDC_UPDATE_BUTTON), 0);
				UpdateMenuCommand(wParam, lParam, hContact);
			}
			break;

		case IDC_STOP:
			if (hContact = FindContactByUrl(hwndDlg))
				db_set_b(hContact, MODULENAME, STOP_KEY, 1); 
			break;

		case IDC_STICK_BUTTON:
			if (hContact = FindContactByUrl(hwndDlg))
				OnTopMenuCommand(wParam, lParam, hContact);
			{
				TCHAR *ptszToolTip;
				HWND hTopmost;
				if (!db_get_b(hContact, MODULENAME, ON_TOP_KEY, 0)) {
					hTopmost = HWND_NOTOPMOST;
					ptszToolTip = TranslateT("Stick to the front");
				}
				else {
					hTopmost = HWND_TOPMOST;
					ptszToolTip = TranslateT("Disable stick to the front");
				}
				SendDlgItemMessage(hwndDlg, IDC_STICK_BUTTON, BM_SETIMAGE, IMAGE_ICON, (LPARAM)LoadImage(hInst, MAKEINTRESOURCE(IDI_UNSTICK), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0));
				SendDlgItemMessage(hwndDlg, IDC_STICK_BUTTON, BUTTONADDTOOLTIP, (WPARAM)ptszToolTip, BATF_TCHAR);
				SetWindowPos(hwndDlg, hTopmost, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
			}
			break;

		case IDC_FIND_BUTTON:
			{
				HWND hwndFind = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_FIND), hwndDlg, DlgProcFind, (LPARAM) wParam);
				ShowWindow(hwndFind, SW_SHOW);
				EnableWindow(GetDlgItem(hwndDlg, IDC_FIND_BUTTON), 0);
			}
			break;

		case IDC_OPTIONS_BUTTON:
			if (hContact = FindContactByUrl(hwndDlg)) {
				ContactHwnd = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_CONTACT_OPT), hwndDlg, DlgProcContactOpt, (LPARAM) hContact);
				ShowWindow(ContactHwnd, SW_SHOW);
				SetActiveWindow(ContactHwnd);
				EnableWindow(GetDlgItem(hwndDlg, IDC_OPTIONS_BUTTON), 0);
				EnableWindow(GetDlgItem(hwndDlg, IDC_ALERT_BUTTON), 0);
			}
			break;

		case IDC_ALERT_BUTTON:
			if (hContact = FindContactByUrl(hwndDlg)) {
				HWND hwndAlertOpt = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_ALRT_OPT), hwndDlg, DlgProcAlertOpt, (LPARAM) hContact);
				ShowWindow(hwndAlertOpt, SW_SHOW);
				SetActiveWindow(hwndAlertOpt);
				EnableWindow(GetDlgItem(hwndDlg, IDC_ALERT_BUTTON), 0);
				EnableWindow(GetDlgItem(hwndDlg, IDC_OPTIONS_BUTTON), 0);
			}
			break;

		case IDOK:
		case IDCANCEL:
			if (hwndDlg != NULL)
				DestroyWindow(hwndDlg);
			return TRUE;
		}
		break;

	case WM_CLOSE:
		if (Yposition == -32000)
			Yposition = 100;

		if (Xposition == -32000)
			Xposition = 100;

		SavewinSettings();

		if (hContact = FindContactByUrl(hwndDlg))
			Utils_SaveWindowPosition(hwndDlg, hContact, MODULENAME, "WV");

		if (hwndDlg != NULL)
			DestroyWindow(hwndDlg);
		return 0;

	case WM_DESTROY:
		WindowList_Remove(hWindowList, hwndDlg);
		return 0;

	case WM_SIZE:
		Utils_ResizeDialog(hwndDlg, hInst, MAKEINTRESOURCEA(IDD_DISPLAY_DATA), DataDialogResize);
		InvalidateRect(hwndDlg, NULL, TRUE);

		// global
		GetWindowRect(hwndDlg, &rc);
		Xposition = rc.left;
		Yposition = rc.top;
		WindowHeight = rc.bottom - rc.top;
		WindowWidth = rc.right - rc.left;
		break;

	case WM_MOVE:
		if (!IsIconic(hwndDlg) && !IsZoomed(hwndDlg)) {
			GetWindowRect(hwndDlg, &rc);
			// global
			Xposition = rc.left;
			Yposition = rc.top;
			WindowHeight = rc.bottom - rc.top;
			WindowWidth = rc.right - rc.left;

			if ((GetAsyncKeyState(VK_CONTROL) & 0x8000))
				break;

			ValidatePosition(hwndDlg);
		}
	}
	return FALSE;
}
Ejemplo n.º 11
0
LONG WINAPI __glutWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{ 
  POINT         point;			/* Point structure. */
  PAINTSTRUCT   ps;			/* Paint structure. */
  LPMINMAXINFO  minmax;			/* Minimum/maximum info structure. */
  GLUTwindow*   window;			/* GLUT window associated with message. */
  GLUTmenu*     menu;			/* GLUT menu associated with message. */
  int x, y, width, height, key;
  int button = -1;

  switch(msg) {
  case WM_CREATE:
    return 0;

  case WM_CLOSE:
    PostQuitMessage(0);
    return 0;

  case WM_DESTROY:
#if 0
    /* TODO: need to add this. */
    purgeStaleWindow(hwnd);
#endif
    return 0;

  case WM_PAINT:
    window = __glutGetWindow(hwnd);
    if (window) {
      BeginPaint(hwnd, &ps);		/* Must have this for some Win32 reason. */
#if TAKE_THIS_OUT
      if (window->colormap) {
	SelectPalette(window->hdc, window->colormap->cmap, FORCE_FOREGROUND);
	RealizePalette(window->hdc);	       /* Remap the custom palette. */
      }
#endif
      EndPaint(hwnd, &ps);
      if (window->win == hwnd) {
	__glutPostRedisplay(window, GLUT_REPAIR_WORK);
      } else if (window->overlay && window->overlay->win == hwnd) {
	__glutPostRedisplay(window, GLUT_OVERLAY_REPAIR_WORK);
      }
    }
    return 0;

  case WM_SYSCHAR:
  case WM_CHAR:
    window = __glutGetWindow(hwnd);
    if (!window) {
      break;
    }
    /* Win32 is dumb and sends these messages only to the parent
       window.  Therefore, find out if we're in a child window and
       call the child windows keyboard callback if we are. */
    if (window->parent) {
	GetCursorPos(&point);
	ScreenToClient(hwnd, &point);
	hwnd = ChildWindowFromPoint(hwnd, point);
	window = __glutGetWindow(hwnd);
    }
    if (window->keyboard) {
      GetCursorPos(&point);
      ScreenToClient(window->win, &point);
      __glutSetWindow(window);
      __glutModifierMask = 0;
      if (GetKeyState(VK_SHIFT) < 0)	/* < 0 = high order bit is on */
	__glutModifierMask |= ShiftMask;
      if (GetKeyState(VK_CONTROL) < 0)
	__glutModifierMask |= ControlMask;
      if (GetKeyState(VK_MENU) < 0)
	__glutModifierMask |= Mod1Mask;
      window->keyboard((char)wParam, point.x, point.y);
      __glutModifierMask = (unsigned int) ~0;
    }
    return 0;

  case WM_SYSKEYDOWN:
  case WM_KEYDOWN:
    window = __glutGetWindow(hwnd);
    if (!window) {
      break;
    }
    /* Win32 is dumb and sends these messages only to the parent
       window.  Therefore, find out if we're in a child window and
       call the child windows keyboard callback if we are. */
    if (window->parent) {
	GetCursorPos(&point);
	ScreenToClient(hwnd, &point);
	hwnd = ChildWindowFromPoint(hwnd, point);
	window = __glutGetWindow(hwnd);
    }
    if (window->special) {
      switch (wParam) {
	/* *INDENT-OFF* */
	/* function keys */
	case VK_F1:     key = GLUT_KEY_F1; break;
	case VK_F2:     key = GLUT_KEY_F2; break;
	case VK_F3:     key = GLUT_KEY_F3; break;
	case VK_F4:     key = GLUT_KEY_F4; break;
	case VK_F5:     key = GLUT_KEY_F5; break;
	case VK_F6:     key = GLUT_KEY_F6; break;
	case VK_F7:     key = GLUT_KEY_F7; break;
	case VK_F8:     key = GLUT_KEY_F8; break;
	case VK_F9:     key = GLUT_KEY_F9; break;
	case VK_F10:    key = GLUT_KEY_F10; break;
	case VK_F11:    key = GLUT_KEY_F11; break;
	case VK_F12:    key = GLUT_KEY_F12; break;
	/* directional keys */
	case VK_LEFT:   key = GLUT_KEY_LEFT; break;
	case VK_UP:     key = GLUT_KEY_UP; break;
	case VK_RIGHT:  key = GLUT_KEY_RIGHT; break;
	case VK_DOWN:   key = GLUT_KEY_DOWN; break;
	/* *INDENT-ON* */

	case VK_PRIOR:
	  /* VK_PRIOR is Win32's Page Up */
	  key = GLUT_KEY_PAGE_UP;
	  break;
	case VK_NEXT:
	  /* VK_NEXT is Win32's Page Down */
	  key = GLUT_KEY_PAGE_DOWN;
	  break;
	case VK_HOME:
	  key = GLUT_KEY_HOME;
	  break;
	case VK_END:
	  key = GLUT_KEY_END;
	  break;
	case VK_INSERT:
	  key = GLUT_KEY_INSERT;
	  break;
	default:
	  goto defproc;
      }
      GetCursorPos(&point);
      ScreenToClient(window->win, &point);
      __glutSetWindow(window);
      __glutModifierMask = 0;
      if (GetKeyState(VK_SHIFT) < 0)	/* < 0 = high order bit is on */
	__glutModifierMask |= ShiftMask;
      if (GetKeyState(VK_CONTROL) < 0)
	__glutModifierMask |= ControlMask;
      if (GetKeyState(VK_MENU) < 0)
	__glutModifierMask |= Mod1Mask;
      window->special(key, point.x, point.y);
      __glutModifierMask = (unsigned int) ~0;
    }
    return 0;

  case WM_LBUTTONDOWN:
    button = GLUT_LEFT_BUTTON;
  case WM_MBUTTONDOWN:
    if (button < 0)
      button = GLUT_MIDDLE_BUTTON;
  case WM_RBUTTONDOWN:
    if (button < 0)
      button = GLUT_RIGHT_BUTTON;
    
    /* finish the menu if we get a button down message (user must have
       cancelled the menu). */
    if (__glutMappedMenu) {
      /* TODO: take this out once the menu on middle mouse stuff works
	 properly. */
      if (button == GLUT_MIDDLE_BUTTON)
	return 0;
      GetCursorPos(&point);
      ScreenToClient(hwnd, &point);
      __glutItemSelected = NULL;
      __glutFinishMenu(hwnd, point.x, point.y);
      return 0;
    }

    /* set the capture so we can get mouse events outside the window */
    SetCapture(hwnd);

    /* Win32 doesn't return the same numbers as X does when the mouse
       goes beyond the upper or left side of the window.  roll the
       Win32's 0..2^16 pointer co-ord range to 0 +/- 2^15. */
    x = LOWORD(lParam);
    y = HIWORD(lParam);
    if(x & 1 << 15) x -= (1 << 16);
    if(y & 1 << 15) y -= (1 << 16);
	
    window = __glutGetWindow(hwnd);
    if (window) {
      menu = __glutGetMenuByNum(window->menu[button]);
      if (menu) {
	point.x = LOWORD(lParam); point.y = HIWORD(lParam);
	ClientToScreen(window->win, &point);
	__glutMenuButton = button == GLUT_RIGHT_BUTTON ? TPM_RIGHTBUTTON :
                           button == GLUT_LEFT_BUTTON  ? TPM_LEFTBUTTON :
                           0x0001;
	__glutStartMenu(menu, window, point.x, point.y, x, y);
      } else if (window->mouse) {
	
        __glutSetWindow(window);
	__glutModifierMask = 0;
	if (GetKeyState(VK_SHIFT) < 0)	/* < 0 = high order bit is on. */
	  __glutModifierMask |= ShiftMask;
	if (GetKeyState(VK_CONTROL) < 0)
	  __glutModifierMask |= ControlMask;
	if (GetKeyState(VK_MENU) < 0)
	  __glutModifierMask |= Mod1Mask;
	window->mouse(button, GLUT_DOWN, x, y);
	__glutModifierMask = (unsigned int)~0;
      } else {
	/* Stray mouse events.  Ignore. */
      }
    }
    return 0;

  case WM_LBUTTONUP:
    button = GLUT_LEFT_BUTTON;
  case WM_MBUTTONUP:
    if (button < 0)
      button = GLUT_MIDDLE_BUTTON;
  case WM_RBUTTONUP:
    if (button < 0)
      button = GLUT_RIGHT_BUTTON;

    /* Bail out if we're processing a menu. */
    if (__glutMappedMenu) {
      GetCursorPos(&point);
      ScreenToClient(hwnd, &point);
      /* if we're getting the middle button up signal, then something
	 on the menu was selected. */
      if (button == GLUT_MIDDLE_BUTTON) {
	return 0;
	/* For some reason, the code below always returns -1 even
	   though the point IS IN THE ITEM!  Therefore, just bail out if
	   we get a middle mouse up.  The user must select using the
	   left mouse button.  Stupid Win32. */
#if 0
 	int item = MenuItemFromPoint(hwnd, __glutHMenu, point);
 	printf("item = %d %d %d\n", item, point.x, point.y);
 	if (item != -1)
 	  __glutItemSelected = (GLUTmenuItem*)GetMenuItemID(__glutHMenu, item);
 	else
 	  __glutItemSelected = NULL;
 	__glutFinishMenu(hwnd, point.x, point.y);
#endif
      } else {
	__glutItemSelected = NULL;
	__glutFinishMenu(hwnd, point.x, point.y);
      }
      return 0;
    }

    /* Release the mouse capture. */
    ReleaseCapture();

    window = __glutGetWindow(hwnd);
    if (window && window->mouse) {
      /* Win32 doesn't return the same numbers as X does when the
	 mouse goes beyond the upper or left side of the window.  roll
	 the Win32's 0..2^16 pointer co-ord range to 0 +/- 2^15. */
      x = LOWORD(lParam);
      y = HIWORD(lParam);
      if(x & 1 << 15) x -= (1 << 16);
      if(y & 1 << 15) y -= (1 << 16);
      
      __glutSetWindow(window);
      __glutModifierMask = 0;
      if (GetKeyState(VK_SHIFT) < 0)	/* < 0 = high order bit is on */
	__glutModifierMask |= ShiftMask;
      if (GetKeyState(VK_CONTROL) < 0)
	__glutModifierMask |= ControlMask;
      if (GetKeyState(VK_MENU) < 0)
	__glutModifierMask |= Mod1Mask;
      window->mouse(button, GLUT_UP, x, y);
      __glutModifierMask = (unsigned int)~0;
    } else {
      /* Window might have been destroyed and all the 
	 events for the window may not yet be received. */
    }
    return 0;

  case WM_ENTERMENULOOP:
    /* KLUDGE: create a timer that fires every 100 ms when we start a
       menu so that we can still process the idle & timer events (that
       way, the timers will fire during a menu pick and so will the
       idle func. */
    SetTimer(hwnd, 1, 1, NULL);
    return 0;

  case WM_TIMER:
#if 0
    /* if the timer id is 2, then this is the timer that is set up in
       the main glut message processing loop, and we don't want to do
       anything but acknowledge that we got it.  It is used to prevent
       CPU spiking when an idle function is installed. */
    if (wParam == 2)
      return 0;
#endif

    /* only worry about the idle function and the timeouts, since
       these are the only events we expect to process during
       processing of a menu. */
    /* we no longer process the idle functions (as outlined in the
       README), since drawing can't be done until the menu has
       finished...it's pretty lame when the animation goes on, but
       doesn't update, so you get this weird jerkiness. */
#if 0    
     if (__glutIdleFunc)
       __glutIdleFunc();
#endif
    if (__glutTimerList)
      handleTimeouts();
    return 0;

  case WM_EXITMENULOOP:
    /* nuke the above created timer...we don't need it anymore, since
       the menu is gone now. */
    KillTimer(hwnd, 1);
    return 0;

  case WM_MENUSELECT:
    if (lParam != 0)
      __glutHMenu = (HMENU)lParam;
    return 0;

  case WM_COMMAND:
    if (__glutMappedMenu) {
      if (GetSubMenu(__glutHMenu, LOWORD(wParam)))
	__glutItemSelected = NULL;
      else
	__glutItemSelected = 
	  __glutGetUniqueMenuItem(__glutMappedMenu, LOWORD(wParam));
      GetCursorPos(&point);
      ScreenToClient(hwnd, &point);
      __glutFinishMenu(hwnd, point.x, point.y);
    } 
    return 0;

  case WM_MOUSEMOVE:
    if (!__glutMappedMenu) {
      window = __glutGetWindow(hwnd);
      if (window) {
          /* If motion function registered _and_ buttons held *
             down, call motion function...  */
	x = LOWORD(lParam);
	y = HIWORD(lParam);

	/* Win32 doesn't return the same numbers as X does when the
	   mouse goes beyond the upper or left side of the window.
	   roll the Win32's 0..2^16 pointer co-ord range to 0..+/-2^15. */
	if(x & 1 << 15) x -= (1 << 16);
	if(y & 1 << 15) y -= (1 << 16);

	if (window->motion && wParam &
            (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)) {
	  __glutSetWindow(window);
	  window->motion(x, y);
	}
	/* If passive motion function registered _and_
	   buttons not held down, call passive motion
	   function...  */
	else if (window->passive &&
		 ((wParam &
		   (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)) ==
		  0)) {
	  __glutSetWindow(window);
	  window->passive(x, y);
	}
      }
    } else {
      /* Motion events are thrown away when a pop up menu is
	 active. */
    }
    return 0;

  case WM_GETMINMAXINFO:
    /* this voodoo is brought to you by Win32 (again).  It allows the
       window to be bigger than the screen, and smaller than 100x100
       (although it doesn't seem to help the y minimum). */
    minmax = (LPMINMAXINFO)lParam;
    minmax->ptMaxSize.x = __glutScreenWidth;
    minmax->ptMaxSize.y = __glutScreenHeight;
    minmax->ptMinTrackSize.x = 0;
    minmax->ptMinTrackSize.y = 0;
    minmax->ptMaxTrackSize.x = __glutScreenWidth + 
      GetSystemMetrics(SM_CXSIZE) * 2;
    minmax->ptMaxTrackSize.y = __glutScreenHeight + 
      GetSystemMetrics(SM_CXSIZE) * 2 + GetSystemMetrics(SM_CYCAPTION);
    return 0;

  case WM_SIZE:
    window = __glutGetWindow(hwnd);
    if (window) {
#if 0
      if (window->win != hwnd) {
	/* Ignore ConfigureNotify sent to the overlay planes.
	   GLUT could get here because overlays select for
	   StructureNotify events to receive DestroyNotify. */
	break;
      }
#endif
      width = LOWORD(lParam);
      height = HIWORD(lParam);
      if (width != window->width || height != window->height) {
#if 0
 	if (window->overlay) {
 	  XResizeWindow(__glutDisplay, window->overlay->win, width, height);
 	}
#endif
	window->width = width;
	window->height = height;
	__glutSetWindow(window);
	/* Do not execute OpenGL out of sequence with respect
	   to the SetWindowPos request! */
	GdiFlush();
	window->reshape(width, height);
	window->forceReshape = FALSE;
	/* A reshape should be considered like posting a
	   repair request. */
	__glutPostRedisplay(window, GLUT_REPAIR_WORK);
      }
    }
    return 0;

  case WM_SETCURSOR:
    /* If the cursor is not in the client area, then we want to send
       this message to the default window procedure ('cause its
       probably in the border or title, and we don't handle that
       cursor.  otherwise, set our cursor.  Win32 makes us set the
       cursor every time the mouse moves (DUMB!). */
    if(LOWORD(lParam) != HTCLIENT)
      goto defproc;
    window = __glutGetWindow(hwnd);
    if (window) {
      /* Since Win32 allows the parent to control a child windows
	 cursor, if the cursor is in a child of this window, bail
	 out. */
      GetCursorPos(&point);
      ScreenToClient(hwnd, &point);
      if (hwnd != ChildWindowFromPoint(hwnd, point))
	break;
      __glutCurrentWindow = window;
      glutSetCursor(window->cursor);
    }
    /* TODO: check out the info in DevStudio on WM_SETCURSOR in the
       DefaultAction section. */
    return 1;

  case WM_SETFOCUS:
    window = __glutGetWindow(hwnd);
    if (window) {
      if (window->entry) {
	window->entryState = WM_SETFOCUS;
	__glutSetWindow(window);
	window->entry(GLUT_ENTERED);
	/* XXX Generation of fake passive notify?  See how    much
	   work the X11 code does to support fake passive    notify
	   callbacks. */
      }
    }
    return 0;

  case WM_KILLFOCUS:
    window = __glutGetWindow(hwnd);
    if (window) {
      if (window->entry) {
	window->entryState = WM_KILLFOCUS;
	__glutSetWindow(window);
	window->entry(GLUT_LEFT);
      }
    }
    return 0;

  case WM_ACTIVATE:
    window = __glutGetWindow(hwnd);
    /* make sure we re-select the correct palette if needed */
    if (LOWORD(wParam)) {
      PostMessage(hwnd, WM_PALETTECHANGED, 0, 0);
    }
    if (window) {
      GLUTwindow* child;
      int visState;
      visState = !IsIconic(window->win);
      if (visState) {			/* Not iconic. */
	visState = IsWindowVisible(window->win);
      }
      if (visState != window->visState) {
	if (window->windowStatus) {
	  window->visState = visState;
	  __glutSetWindow(window);
	  window->windowStatus(visState);
	}
	/* Since Win32 only sends an activate for the toplevel window,
	   update the visibility for all the child windows. */
	child = window->children;
	while (child) {
	  child->visState = visState;
	  if (child->windowStatus) {
	    child->visState = visState;
	    __glutSetWindow(child);
	    child->windowStatus(visState);
	  }
	  child = child->siblings;
	}
      }
    }
    return 0;

  /* Colour Palette Management */
  case WM_PALETTECHANGED:
    if (hwnd == (HWND)wParam)  /* don't respond to the message that we sent! */
      break;
    /* fall through to WM_QUERYNEWPALETTE */

  case WM_QUERYNEWPALETTE:
    window = __glutGetWindow(hwnd);
    if (window && window->colormap) {
      UnrealizeObject(window->colormap->cmap);
      SelectPalette(window->hdc, window->colormap->cmap, FALSE);
      RealizePalette(window->hdc);
      return TRUE;
    }
    return FALSE;

#if 0
  /* Miscellaneous messages (don't really need to enumerate them,
     but it's good to know what you're not getting sometimes.) */
  case WM_NCHITTEST:
    /* this event is generated by every mouse move event. */
    goto defproc;
  case WM_NCMOUSEMOVE:
    goto defproc;
  case WM_NCACTIVATE:
    goto defproc;
  case WM_NCPAINT:
    goto defproc;
  case WM_NCCALCSIZE:
    goto defproc;
  case WM_NCCREATE:
    goto defproc;
  case WM_NCDESTROY:
    goto defproc;
  case WM_NCLBUTTONDOWN:
    goto defproc;
  case WM_SETTEXT:
    goto defproc;
  case WM_GETTEXT:
    goto defproc;
  case WM_ACTIVATEAPP:
    goto defproc;
  case WM_GETICON:
    goto defproc;
  case WM_ERASEBKGND:
    goto defproc;
  case WM_WINDOWPOSCHANGING:
    goto defproc;
  case WM_WINDOWPOSCHANGED:
    goto defproc;
  case WM_MOUSEACTIVATE:
    goto defproc;
  case WM_SHOWWINDOW:
    goto defproc;
  case WM_MOVING:
    goto defproc;
  case WM_MOVE:
    goto defproc;
  case WM_KEYUP:
    goto defproc;
  case WM_CAPTURECHANGED:
    goto defproc;
  case WM_SYSCOMMAND:
    goto defproc;
  case WM_ENTERSIZEMOVE:
    goto defproc;
  case WM_ENTERIDLE:
    goto defproc;
#endif

  default: 
    goto defproc;
  }

defproc:    
  return DefWindowProc(hwnd, msg, wParam, lParam); 
} 
Ejemplo n.º 12
0
/*
* WinObjExMain
*
* Purpose:
*
* Actual program entry point.
*
*/
void WinObjExMain()
{
    MSG                     msg1;
    WNDCLASSEX              wincls;
    BOOL                    IsFullAdmin = FALSE, IsWine = FALSE, rv = TRUE, cond = FALSE;
    ATOM                    class_atom = 0;
    INITCOMMONCONTROLSEX    icc;   
    LVCOLUMN                col;
    SHSTOCKICONINFO         sii;
    HMENU                   hMenu;
    HACCEL                  hAccTable = 0;
    WCHAR                   szWindowTitle[100];
    HANDLE                  hIcon;
    HIMAGELIST              TreeViewImages;

    if (!WinObjInitGlobals())
        return;

    // do not move anywhere
    IsFullAdmin = supUserIsFullAdmin();

    // check compatibility
    IsWine = supIsWine();
    if (IsWine != FALSE) {
        IsFullAdmin = FALSE;
    }

    supInit(IsFullAdmin, IsWine);

    // do not move anywhere
    // g_kdctx variable initialized BEFORE this.
    // if you move these lines anywhere above they will be zeroed during kdInit
    g_kdctx.IsWine = IsWine;
    g_kdctx.IsFullAdmin = IsFullAdmin;

#ifdef _DEBUG
    TestStart();
#endif

    do {
        //
        // Create main window and it components.
        //
        wincls.cbSize = sizeof(WNDCLASSEX);
        wincls.style = 0;
        wincls.lpfnWndProc = &MainWindowProc;
        wincls.cbClsExtra = 0;
        wincls.cbWndExtra = 0;
        wincls.hInstance = g_WinObj.hInstance;
        wincls.hIcon = (HICON)LoadImage(g_WinObj.hInstance, MAKEINTRESOURCE(IDI_ICON_MAIN), IMAGE_ICON, 0, 0, LR_SHARED);
        wincls.hCursor = (HCURSOR)LoadImage(NULL, MAKEINTRESOURCE(OCR_SIZEWE), IMAGE_CURSOR, 0, 0, LR_SHARED);
        wincls.hbrBackground = NULL;
        wincls.lpszMenuName = MAKEINTRESOURCE(IDR_MENU1);
        wincls.lpszClassName = MAINWINDOWCLASSNAME;
        wincls.hIconSm = 0;

        class_atom = RegisterClassEx(&wincls);
        if (class_atom == 0)
            break;
        
        RtlSecureZeroMemory(szWindowTitle, sizeof(szWindowTitle));
        _strcpy(szWindowTitle, PROGRAM_NAME);
        if (IsFullAdmin != FALSE) {
            _strcat(szWindowTitle, L" (Administrator)");
        }

        if (IsWine != FALSE) {
            _strcat(szWindowTitle, L" (Wine emulation)");
        }

        MainWindow = CreateWindowEx(0, MAKEINTATOM(class_atom), szWindowTitle,
            WS_VISIBLE | WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 800, 600, NULL, NULL, g_WinObj.hInstance, NULL);
        if (MainWindow == NULL)
            break;

        icc.dwSize = sizeof(icc);
        icc.dwICC = ICC_LISTVIEW_CLASSES | ICC_TREEVIEW_CLASSES | ICC_BAR_CLASSES | ICC_TAB_CLASSES;
        if (!InitCommonControlsEx(&icc))
            break;

        hwndStatusBar = CreateWindowEx(0, STATUSCLASSNAME, NULL,
            WS_VISIBLE | WS_CHILD, 0, 0, 0, 0, MainWindow, NULL, g_WinObj.hInstance, NULL);

        g_hwndObjectTree = CreateWindowEx(WS_EX_CLIENTEDGE, WC_TREEVIEW, NULL,
            WS_VISIBLE | WS_CHILD | WS_TABSTOP | TVS_DISABLEDRAGDROP | TVS_HASBUTTONS |
            TVS_HASLINES | TVS_LINESATROOT, 0, 0, 0, 0, MainWindow, (HMENU)1002, g_WinObj.hInstance, NULL);

        if (g_hwndObjectTree == NULL)
            break;

        g_hwndObjectList = CreateWindowEx(WS_EX_CLIENTEDGE, WC_LISTVIEW, NULL,
            WS_VISIBLE | WS_CHILD | WS_TABSTOP | LVS_AUTOARRANGE | LVS_REPORT |
            LVS_SHOWSELALWAYS | LVS_SINGLESEL | LVS_SHAREIMAGELISTS, 0, 0, 0, 0,
            MainWindow, (HMENU)1003, g_WinObj.hInstance, NULL);

        if (g_hwndObjectList == NULL)
            break;

        hwndToolBar = CreateWindowEx(0, TOOLBARCLASSNAME, NULL,
            WS_VISIBLE | WS_CHILD | CCS_TOP | TBSTYLE_FLAT | TBSTYLE_TRANSPARENT |
            TBSTYLE_TOOLTIPS, 0, 0, 0, 0, MainWindow, (HMENU)1004, g_WinObj.hInstance, NULL);

        if (hwndToolBar == NULL)
            break;

        hwndSplitter = CreateWindowEx(0, WC_STATIC, NULL,
            WS_VISIBLE | WS_CHILD, 0, 0, 0, 0, MainWindow, (HMENU)1005, g_WinObj.hInstance, NULL);

        // initialization of views
        SendMessage(MainWindow, WM_SIZE, 0, 0);
        ListView_SetExtendedListViewStyle(g_hwndObjectList,
            LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVS_EX_LABELTIP | LVS_EX_DOUBLEBUFFER);

        // set tree imagelist
        TreeViewImages = supLoadImageList(g_WinObj.hInstance, IDI_ICON_VIEW_DEFAULT, IDI_ICON_VIEW_SELECTED);
        if (TreeViewImages) {
            TreeView_SetImageList(g_hwndObjectTree, TreeViewImages, TVSIL_NORMAL);
        }

        //not enough user rights, insert run as admin menu entry and hide admin only stuff
        if ((IsFullAdmin == FALSE) && (g_kdctx.IsWine == FALSE)) {
            hMenu = GetSubMenu(GetMenu(MainWindow), 0);
            InsertMenu(hMenu, 0, MF_BYPOSITION, ID_FILE_RUNASADMIN, T_RUNASADMIN);
            InsertMenu(hMenu, 1, MF_BYPOSITION | MF_SEPARATOR, 0, NULL);
            //set menu shield icon
            RtlSecureZeroMemory(&sii, sizeof(sii));
            sii.cbSize = sizeof(sii);
            if (SHGetStockIconInfo(SIID_SHIELD, SHGSI_ICON | SHGFI_SMALLICON, &sii) == S_OK) {
                supSetMenuIcon(hMenu, ID_FILE_RUNASADMIN, (ULONG_PTR)sii.hIcon);
            }
        }

        if (g_kdctx.hDevice == NULL) {
            //require driver usage, remove
            DeleteMenu(GetSubMenu(GetMenu(MainWindow), 4), ID_EXTRAS_SSDT, MF_BYCOMMAND);
            DeleteMenu(GetSubMenu(GetMenu(MainWindow), 4), ID_EXTRAS_PRIVATENAMESPACES, MF_BYCOMMAND);
        }

        //unsupported
        if (g_WinObj.osver.dwBuildNumber > 10240) {
            DeleteMenu(GetSubMenu(GetMenu(MainWindow), 4), ID_EXTRAS_PRIVATENAMESPACES, MF_BYCOMMAND);
        }

        //wine unsupported
        if (g_kdctx.IsWine != FALSE) {
            DeleteMenu(GetSubMenu(GetMenu(MainWindow), 4), ID_EXTRAS_DRIVERS, MF_BYCOMMAND);
        }

        //load listview images
        g_ListViewImages = supLoadImageList(g_WinObj.hInstance, IDI_ICON_DEVICE, IDI_ICON_UNKNOWN);
        if (g_ListViewImages) {
            hIcon = LoadImage(g_WinObj.hInstance, MAKEINTRESOURCE(IDI_ICON_SORTUP), IMAGE_ICON, 0, 0, LR_DEFAULTCOLOR);
            if (hIcon) {
                ImageList_ReplaceIcon(g_ListViewImages, -1, hIcon);
                DestroyIcon(hIcon);
            }
            hIcon = LoadImage(g_WinObj.hInstance, MAKEINTRESOURCE(IDI_ICON_SORTDOWN), IMAGE_ICON, 0, 0, LR_DEFAULTCOLOR);
            if (hIcon) {
                ImageList_ReplaceIcon(g_ListViewImages, -1, hIcon);
                DestroyIcon(hIcon);
            }
            ListView_SetImageList(g_hwndObjectList, g_ListViewImages, LVSIL_SMALL);
        }

        //load toolbar images
        g_ToolBarMenuImages = ImageList_LoadImage(g_WinObj.hInstance, MAKEINTRESOURCE(IDB_BITMAP1),
            16, 7, CLR_DEFAULT, IMAGE_BITMAP, LR_CREATEDIBSECTION);

        if (g_ToolBarMenuImages) {

            supCreateToolbarButtons(hwndToolBar);

            //set menu icons
            hMenu = GetSubMenu(GetMenu(MainWindow), 1);
            if (hMenu) {
                supSetMenuIcon(hMenu, ID_VIEW_REFRESH,
                    (ULONG_PTR)ImageList_ExtractIcon(g_WinObj.hInstance, g_ToolBarMenuImages, 1));
            }
            hMenu = GetSubMenu(GetMenu(MainWindow), 2);
            if (hMenu && g_ListViewImages) {
                supSetMenuIcon(hMenu, ID_OBJECT_PROPERTIES,
                    (ULONG_PTR)ImageList_ExtractIcon(g_WinObj.hInstance, g_ToolBarMenuImages, 0));
                supSetMenuIcon(hMenu, ID_OBJECT_GOTOLINKTARGET,
                    (ULONG_PTR)ImageList_ExtractIcon(g_WinObj.hInstance, g_ListViewImages,
                        ID_FROM_VALUE(IDI_ICON_SYMLINK)));
            }

            //set object -> find object menu image
            hMenu = GetSubMenu(GetMenu(MainWindow), 3);
            if (hMenu) {
                supSetMenuIcon(hMenu, ID_FIND_FINDOBJECT,
                    (ULONG_PTR)ImageList_ExtractIcon(g_WinObj.hInstance, g_ToolBarMenuImages, 2));
            }

            //set extras-mailslots/pipes menu image
            hMenu = GetSubMenu(GetMenu(MainWindow), 4);
            if (hMenu) {
                supSetMenuIcon(hMenu, ID_EXTRAS_MAILSLOTS,
                    (ULONG_PTR)ImageList_ExtractIcon(g_WinObj.hInstance, g_ToolBarMenuImages, 5));
                supSetMenuIcon(hMenu, ID_EXTRAS_PIPES,
                    (ULONG_PTR)ImageList_ExtractIcon(g_WinObj.hInstance, g_ToolBarMenuImages, 6));
            }

            //set help menu image
            hMenu = GetSubMenu(GetMenu(MainWindow), 5);
            if (hMenu) {
                supSetMenuIcon(hMenu, ID_HELP_HELP,
                    (ULONG_PTR)ImageList_ExtractIcon(g_WinObj.hInstance, g_ToolBarMenuImages, 3));
            }

        }

        hAccTable = LoadAccelerators(g_WinObj.hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR1));

        //create ObjectList columns
        RtlSecureZeroMemory(&col, sizeof(col));
        col.mask = LVCF_TEXT | LVCF_SUBITEM | LVCF_FMT | LVCF_WIDTH | LVCF_ORDER | LVCF_IMAGE;
        col.iSubItem = 1;
        col.pszText = TEXT("Name");
        col.fmt = LVCFMT_LEFT | LVCFMT_BITMAP_ON_RIGHT;
        col.iOrder = 0;
        col.iImage = -1;
        if (g_ListViewImages) {
            col.iImage = ImageList_GetImageCount(g_ListViewImages) - 1;
        }
        col.cx = 300;
        ListView_InsertColumn(g_hwndObjectList, 1, &col);

        col.iSubItem = 2;
        col.pszText = TEXT("Type");
        col.iOrder = 1;
        col.iImage = -1;
        col.cx = 100;
        ListView_InsertColumn(g_hwndObjectList, 2, &col);

        col.iSubItem = 3;
        col.pszText = TEXT("Additional Information");
        col.iOrder = 2;
        col.iImage = -1;
        col.cx = 170;
        ListView_InsertColumn(g_hwndObjectList, 3, &col);

        ListObjectDirectoryTree(L"\\", NULL, NULL);

        TreeView_SelectItem(g_hwndObjectTree, TreeView_GetRoot(g_hwndObjectTree));
        SetFocus(g_hwndObjectTree);

        do {
            rv = GetMessage(&msg1, NULL, 0, 0);

            if (rv == -1)
                break;

            if (MainDlgMsgHandler(msg1))
                continue;

            if (IsDialogMessage(MainWindow, &msg1)) {
                TranslateAccelerator(MainWindow, hAccTable, &msg1);
                continue;
            }

            TranslateMessage(&msg1);
            DispatchMessage(&msg1);
        } while (rv != 0);

    } while (cond);

    if (class_atom != 0)
        UnregisterClass(MAKEINTATOM(class_atom), g_WinObj.hInstance);

    //do not move anywhere

    supShutdown();

#ifdef _DEBUG
    TestStop();
#endif

}
Ejemplo n.º 13
0
static INT_PTR CALLBACK PhpFindObjectsDlgProc(
    __in HWND hwndDlg,
    __in UINT uMsg,
    __in WPARAM wParam,
    __in LPARAM lParam
    )
{
    switch (uMsg)
    {
    case WM_INITDIALOG:
        {
            HWND lvHandle;

            PhCenterWindow(hwndDlg, GetParent(hwndDlg));
            PhFindObjectsListViewHandle = lvHandle = GetDlgItem(hwndDlg, IDC_RESULTS);

            PhInitializeLayoutManager(&WindowLayoutManager, hwndDlg);
            PhAddLayoutItem(&WindowLayoutManager, GetDlgItem(hwndDlg, IDC_FILTER),
                NULL, PH_ANCHOR_LEFT | PH_ANCHOR_TOP | PH_ANCHOR_RIGHT);
            PhAddLayoutItem(&WindowLayoutManager, GetDlgItem(hwndDlg, IDOK),
                NULL, PH_ANCHOR_TOP | PH_ANCHOR_RIGHT);
            PhAddLayoutItem(&WindowLayoutManager, lvHandle,
                NULL, PH_ANCHOR_ALL);

            MinimumSize.left = 0;
            MinimumSize.top = 0;
            MinimumSize.right = 150;
            MinimumSize.bottom = 100;
            MapDialogRect(hwndDlg, &MinimumSize);

            PhRegisterDialog(hwndDlg);

            PhLoadWindowPlacementFromSetting(L"FindObjWindowPosition", L"FindObjWindowSize", hwndDlg);

            PhSetListViewStyle(lvHandle, TRUE, TRUE);
            PhSetControlTheme(lvHandle, L"explorer");
            PhAddListViewColumn(lvHandle, 0, 0, 0, LVCFMT_LEFT, 100, L"Process");
            PhAddListViewColumn(lvHandle, 1, 1, 1, LVCFMT_LEFT, 100, L"Type");
            PhAddListViewColumn(lvHandle, 2, 2, 2, LVCFMT_LEFT, 200, L"Name");
            PhAddListViewColumn(lvHandle, 3, 3, 3, LVCFMT_LEFT, 80, L"Handle");

            PhSetExtendedListView(lvHandle);
            ExtendedListView_SetSortFast(lvHandle, TRUE);
            ExtendedListView_SetCompareFunction(lvHandle, 0, PhpObjectProcessCompareFunction);
            ExtendedListView_SetCompareFunction(lvHandle, 1, PhpObjectTypeCompareFunction);
            ExtendedListView_SetCompareFunction(lvHandle, 2, PhpObjectNameCompareFunction);
            ExtendedListView_SetCompareFunction(lvHandle, 3, PhpObjectHandleCompareFunction);
            PhLoadListViewColumnsFromSetting(L"FindObjListViewColumns", lvHandle);
        }
        break;
    case WM_DESTROY:
        {
            PhSaveWindowPlacementToSetting(L"FindObjWindowPosition", L"FindObjWindowSize", hwndDlg);
            PhSaveListViewColumnsToSetting(L"FindObjListViewColumns", PhFindObjectsListViewHandle);
        }
        break;
    case WM_SHOWWINDOW:
        {
            SetFocus(GetDlgItem(hwndDlg, IDC_FILTER));
            Edit_SetSel(GetDlgItem(hwndDlg, IDC_FILTER), 0, -1);
        }
        break;
    case WM_CLOSE:
        {
            ShowWindow(hwndDlg, SW_HIDE);
            // IMPORTANT
            // Set the result to 0 so the default dialog message
            // handler doesn't invoke IDCANCEL, which will send
            // WM_CLOSE, creating an infinite loop.
            SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, 0);
        }
        return TRUE;
    case WM_SETCURSOR:
        {
            if (SearchThreadHandle)
            {
                SetCursor(LoadCursor(NULL, IDC_WAIT));
                SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, TRUE);
                return TRUE;
            }
        }
        break;
    case WM_COMMAND:
        {
            switch (LOWORD(wParam))
            {
            case IDOK:
                {
                    // Don't continue if the user requested cancellation.
                    if (SearchStop)
                        break;

                    if (!SearchThreadHandle)
                    {
                        ULONG i;

                        // Cleanup previous results.

                        ListView_DeleteAllItems(PhFindObjectsListViewHandle);

                        if (SearchResults)
                        {
                            for (i = 0; i < SearchResults->Count; i++)
                            {
                                PPHP_OBJECT_SEARCH_RESULT searchResult = SearchResults->Items[i];

                                PhDereferenceObject(searchResult->TypeName);
                                PhDereferenceObject(searchResult->Name);

                                if (searchResult->ProcessName)
                                    PhDereferenceObject(searchResult->ProcessName);

                                PhFree(searchResult);
                            }

                            PhDereferenceObject(SearchResults);
                        }

                        // Start the search.

                        SearchString = PhGetWindowText(GetDlgItem(hwndDlg, IDC_FILTER));
                        SearchResults = PhCreateList(128);
                        SearchResultsAddIndex = 0;

                        SearchThreadHandle = PhCreateThread(0, PhpFindObjectsThreadStart, NULL);

                        if (!SearchThreadHandle)
                            break;

                        SetDlgItemText(hwndDlg, IDOK, L"Cancel");

                        SetCursor(LoadCursor(NULL, IDC_WAIT));
                    }
                    else
                    {
                        SearchStop = TRUE;
                        EnableWindow(GetDlgItem(hwndDlg, IDOK), FALSE);
                    }
                }
                break;
            case IDCANCEL:
                {
                    SendMessage(hwndDlg, WM_CLOSE, 0, 0);
                }
                break;
            case ID_OBJECT_CLOSE:
                {
                    PPHP_OBJECT_SEARCH_RESULT *results;
                    ULONG numberOfResults;
                    ULONG i;

                    PhGetSelectedListViewItemParams(
                        PhFindObjectsListViewHandle,
                        &results,
                        &numberOfResults
                        );

                    if (numberOfResults != 0 && PhShowConfirmMessage(
                        hwndDlg,
                        L"close",
                        numberOfResults == 1 ? L"the selected handle" : L"the selected handles",
                        L"Closing handles may cause system instability and data corruption.",
                        FALSE
                        ))
                    {
                        for (i = 0; i < numberOfResults; i++)
                        {
                            NTSTATUS status;
                            HANDLE processHandle;

                            if (results[i]->ResultType != HandleSearchResult)
                                continue;

                            if (NT_SUCCESS(status = PhOpenProcess(
                                &processHandle,
                                PROCESS_DUP_HANDLE,
                                results[i]->ProcessId
                                )))
                            {
                                if (NT_SUCCESS(status = PhDuplicateObject(
                                    processHandle,
                                    results[i]->Handle,
                                    NULL,
                                    NULL,
                                    0,
                                    0,
                                    DUPLICATE_CLOSE_SOURCE
                                    )))
                                {
                                    PhRemoveListViewItem(PhFindObjectsListViewHandle,
                                        PhFindListViewItemByParam(PhFindObjectsListViewHandle, 0, results[i]));
                                }

                                NtClose(processHandle);
                            }

                            if (!NT_SUCCESS(status))
                            {
                                if (!PhShowContinueStatus(hwndDlg,
                                    PhaFormatString(L"Unable to close \"%s\"", results[i]->Name->Buffer)->Buffer,
                                    status,
                                    0
                                    ))
                                    break;
                            }
                        }
                    }

                    PhFree(results);
                }
                break;
            case ID_OBJECT_PROCESSPROPERTIES:
                {
                    PPHP_OBJECT_SEARCH_RESULT result =
                        PhGetSelectedListViewItemParam(PhFindObjectsListViewHandle);

                    if (result)
                    {
                        PPH_PROCESS_ITEM processItem;

                        if (processItem = PhReferenceProcessItem(result->ProcessId))
                        {
                            ProcessHacker_ShowProcessProperties(PhMainWndHandle, processItem);
                            PhDereferenceObject(processItem);
                        }
                    }
                }
                break;
            case ID_OBJECT_PROPERTIES:
                {
                    PPHP_OBJECT_SEARCH_RESULT result =
                        PhGetSelectedListViewItemParam(PhFindObjectsListViewHandle);

                    if (result)
                    {
                        if (result->ResultType == HandleSearchResult)
                        {
                            PPH_HANDLE_ITEM handleItem;

                            handleItem = PhCreateHandleItem(&result->Info);

                            handleItem->BestObjectName = handleItem->ObjectName = result->Name;
                            PhReferenceObjectEx(result->Name, 2);

                            handleItem->TypeName = result->TypeName;
                            PhReferenceObject(result->TypeName);

                            PhShowHandleProperties(
                                hwndDlg,
                                result->ProcessId,
                                handleItem
                                );
                            PhDereferenceObject(handleItem);
                        }
                        else
                        {
                            // DLL or Mapped File. Just show file properties.
                            PhShellProperties(hwndDlg, result->Name->Buffer);
                        }
                    }
                }
                break;
            case ID_OBJECT_COPY:
                {
                    PhCopyListView(PhFindObjectsListViewHandle);
                }
                break;
            }
        }
        break;
    case WM_NOTIFY:
        {
            LPNMHDR header = (LPNMHDR)lParam;

            switch (header->code)
            {
            case NM_DBLCLK:
                {
                    if (header->hwndFrom == PhFindObjectsListViewHandle)
                    {
                        SendMessage(hwndDlg, WM_COMMAND, ID_OBJECT_PROPERTIES, 0);
                    }
                }
                break;
            case LVN_KEYDOWN:
                {
                    if (header->hwndFrom == PhFindObjectsListViewHandle)
                    {
                        LPNMLVKEYDOWN keyDown = (LPNMLVKEYDOWN)header;

                        switch (keyDown->wVKey)
                        {
                        case 'C':
                            if (GetKeyState(VK_CONTROL) < 0)
                                SendMessage(hwndDlg, WM_COMMAND, ID_OBJECT_COPY, 0);
                            break;
                        case VK_DELETE:
                            SendMessage(hwndDlg, WM_COMMAND, ID_OBJECT_CLOSE, 0);
                            break;
                        }
                    }
                }
                break;
            }
        }
        break;
    case WM_CONTEXTMENU:
        {
            if ((HWND)wParam == PhFindObjectsListViewHandle)
            {
                POINT point;
                PPHP_OBJECT_SEARCH_RESULT *results;
                ULONG numberOfResults;

                point.x = (SHORT)LOWORD(lParam);
                point.y = (SHORT)HIWORD(lParam);

                if (point.x == -1 && point.y == -1)
                    PhGetListViewContextMenuPoint((HWND)wParam, &point);

                PhGetSelectedListViewItemParams(PhFindObjectsListViewHandle, &results, &numberOfResults);

                if (numberOfResults != 0)
                {
                    HMENU menu;
                    HMENU subMenu;

                    menu = LoadMenu(PhInstanceHandle, MAKEINTRESOURCE(IDR_FINDOBJ));
                    subMenu = GetSubMenu(menu, 0);

                    SetMenuDefaultItem(subMenu, ID_OBJECT_PROPERTIES, FALSE);
                    PhpInitializeFindObjMenu(
                        subMenu,
                        results,
                        numberOfResults
                        );

                    PhShowContextMenu(
                        hwndDlg,
                        PhFindObjectsListViewHandle,
                        subMenu,
                        point
                        );
                    DestroyMenu(menu);
                }

                PhFree(results);
            }
        }
        break;
    case WM_SIZE:
        {
            PhLayoutManagerLayout(&WindowLayoutManager);
        }
        break;
    case WM_SIZING:
        {
            PhResizingMinimumSize((PRECT)lParam, wParam, MinimumSize.right, MinimumSize.bottom);
        }
        break;
    case WM_PH_SEARCH_UPDATE:
        {
            HWND lvHandle;
            ULONG i;

            lvHandle = GetDlgItem(hwndDlg, IDC_RESULTS);

            ExtendedListView_SetRedraw(lvHandle, FALSE);

            PhAcquireQueuedLockExclusive(&SearchResultsLock);

            for (i = SearchResultsAddIndex; i < SearchResults->Count; i++)
            {
                PPHP_OBJECT_SEARCH_RESULT searchResult = SearchResults->Items[i];
                CLIENT_ID clientId;
                PPH_PROCESS_ITEM processItem;
                PPH_STRING clientIdName;
                INT lvItemIndex;

                clientId.UniqueProcess = searchResult->ProcessId;
                clientId.UniqueThread = NULL;

                processItem = PhReferenceProcessItem(clientId.UniqueProcess);
                clientIdName = PhGetClientIdNameEx(&clientId, processItem ? processItem->ProcessName : NULL);

                lvItemIndex = PhAddListViewItem(
                    lvHandle,
                    MAXINT,
                    clientIdName->Buffer,
                    searchResult
                    );

                PhDereferenceObject(clientIdName);

                if (processItem)
                {
                    searchResult->ProcessName = processItem->ProcessName;
                    PhReferenceObject(searchResult->ProcessName);
                    PhDereferenceObject(processItem);
                }
                else
                {
                    searchResult->ProcessName = NULL;
                }

                PhSetListViewSubItem(lvHandle, lvItemIndex, 1, searchResult->TypeName->Buffer);
                PhSetListViewSubItem(lvHandle, lvItemIndex, 2, searchResult->Name->Buffer);
                PhSetListViewSubItem(lvHandle, lvItemIndex, 3, searchResult->HandleString);
            }

            SearchResultsAddIndex = i;

            PhReleaseQueuedLockExclusive(&SearchResultsLock);

            ExtendedListView_SetRedraw(lvHandle, TRUE);
        }
        break;
    case WM_PH_SEARCH_FINISHED:
        {
            // Add any un-added items.
            SendMessage(hwndDlg, WM_PH_SEARCH_UPDATE, 0, 0);

            PhDereferenceObject(SearchString);

            NtWaitForSingleObject(SearchThreadHandle, FALSE, NULL);
            NtClose(SearchThreadHandle);
            SearchThreadHandle = NULL;
            SearchStop = FALSE;

            ExtendedListView_SortItems(GetDlgItem(hwndDlg, IDC_RESULTS));

            SetDlgItemText(hwndDlg, IDOK, L"Find");
            EnableWindow(GetDlgItem(hwndDlg, IDOK), TRUE);

            SetCursor(LoadCursor(NULL, IDC_ARROW));
        }
        break;
    }

    return FALSE;
}
void
CMSWindowsClientTaskBarReceiver::runMenu(int x, int y)
{
	// do popup menu.  we need a window to pass to TrackPopupMenu().
	// the SetForegroundWindow() and SendMessage() calls around
	// TrackPopupMenu() are to get the menu to be dismissed when
	// another window gets activated and are just one of those
	// win32 weirdnesses.
	createWindow();
	SetForegroundWindow(m_window);
	HMENU menu = GetSubMenu(m_menu, 0);
	SetMenuDefaultItem(menu, IDC_TASKBAR_STATUS, FALSE);
	HMENU logLevelMenu = GetSubMenu(menu, 3);
	CheckMenuRadioItem(logLevelMenu, 0, 6,
							CLOG->getFilter() - kERROR, MF_BYPOSITION);
	int n = TrackPopupMenu(menu,
							TPM_NONOTIFY |
							TPM_RETURNCMD |
							TPM_LEFTBUTTON |
							TPM_RIGHTBUTTON,
							x, y, 0, m_window, NULL);
	SendMessage(m_window, WM_NULL, 0, 0);

	// perform the requested operation
	switch (n) {
	case IDC_TASKBAR_STATUS:
		showStatus();
		break;

	case IDC_TASKBAR_LOG:
		copyLog();
		break;

	case IDC_TASKBAR_SHOW_LOG:
		ARCH->showConsole(true);
		break;

	case IDC_TASKBAR_LOG_LEVEL_ERROR:
		CLOG->setFilter(kERROR);
		break;

	case IDC_TASKBAR_LOG_LEVEL_WARNING:
		CLOG->setFilter(kWARNING);
		break;

	case IDC_TASKBAR_LOG_LEVEL_NOTE:
		CLOG->setFilter(kNOTE);
		break;

	case IDC_TASKBAR_LOG_LEVEL_INFO:
		CLOG->setFilter(kINFO);
		break;

	case IDC_TASKBAR_LOG_LEVEL_DEBUG:
		CLOG->setFilter(kDEBUG);
		break;

	case IDC_TASKBAR_LOG_LEVEL_DEBUG1:
		CLOG->setFilter(kDEBUG1);
		break;

	case IDC_TASKBAR_LOG_LEVEL_DEBUG2:
		CLOG->setFilter(kDEBUG2);
		break;

	case IDC_TASKBAR_QUIT:
		quit();
		break;
	}
}
void
CMSWindowsServerTaskBarReceiver::runMenu(int x, int y)
{
	// do popup menu.  we need a window to pass to TrackPopupMenu().
	// the SetForegroundWindow() and SendMessage() calls around
	// TrackPopupMenu() are to get the menu to be dismissed when
	// another window gets activated and are just one of those
	// win32 weirdnesses.
	createWindow();
	SetForegroundWindow(m_window);
	HMENU menu = GetSubMenu(m_menu, 0);
	SetMenuDefaultItem(menu, IDC_TASKBAR_STATUS, FALSE);
	HMENU logLevelMenu = GetSubMenu(menu, 3);
	CheckMenuRadioItem(logLevelMenu, 0, 6,
							CLOG->getFilter() - CLog::kERROR, MF_BYPOSITION);
	int n = TrackPopupMenu(menu,
							TPM_NONOTIFY |
							TPM_RETURNCMD |
							TPM_LEFTBUTTON |
							TPM_RIGHTBUTTON,
							x, y, 0, m_window, NULL);
	SendMessage(m_window, WM_NULL, 0, 0);

	// perform the requested operation
	switch (n) {
	case IDC_TASKBAR_STATUS:
		showStatus();
		break;

	case IDC_TASKBAR_LOG:
		copyLog();
		break;

	case IDC_TASKBAR_SHOW_LOG:
		ARCH->showConsole(true);
		break;

	case IDC_RELOAD_CONFIG:
		EVENTQUEUE->addEvent(CEvent(getReloadConfigEvent(),
							IEventQueue::getSystemTarget()));
		break;

	case IDC_FORCE_RECONNECT:
		EVENTQUEUE->addEvent(CEvent(getForceReconnectEvent(),
							IEventQueue::getSystemTarget()));
		break;

	case ID_SYNERGY_RESETSERVER:
		EVENTQUEUE->addEvent(CEvent(getResetServerEvent(),
							IEventQueue::getSystemTarget()));
		break;

	case IDC_TASKBAR_LOG_LEVEL_ERROR:
		CLOG->setFilter(CLog::kERROR);
		break;

	case IDC_TASKBAR_LOG_LEVEL_WARNING:
		CLOG->setFilter(CLog::kWARNING);
		break;

	case IDC_TASKBAR_LOG_LEVEL_NOTE:
		CLOG->setFilter(CLog::kNOTE);
		break;

	case IDC_TASKBAR_LOG_LEVEL_INFO:
		CLOG->setFilter(CLog::kINFO);
		break;

	case IDC_TASKBAR_LOG_LEVEL_DEBUG:
		CLOG->setFilter(CLog::kDEBUG);
		break;

	case IDC_TASKBAR_LOG_LEVEL_DEBUG1:
		CLOG->setFilter(CLog::kDEBUG1);
		break;

	case IDC_TASKBAR_LOG_LEVEL_DEBUG2:
		CLOG->setFilter(CLog::kDEBUG2);
		break;

	case IDC_TASKBAR_QUIT:
		quit();
		break;
	}
}
Ejemplo n.º 16
0
static void TaskManager_OnTabWndSelChange(void)
{
    int   i;
    HMENU hMenu;
    HMENU hOptionsMenu;
    HMENU hViewMenu;
    HMENU hSubMenu;

    WCHAR wszLargeIcons[255];
    WCHAR wszSmallIcons[255];
    WCHAR wszDetails[255];
    WCHAR wszWindows[255];
    WCHAR wszSelectColumns[255];
    WCHAR wszShow16bTasks[255];
    WCHAR wszOneGraphAllCPU[255];
    WCHAR wszOneGraphPerCPU[255];
    WCHAR wszCPUHistory[255];
    WCHAR wszShowKernelTimes[255];

    LoadStringW(hInst, IDS_VIEW_LARGE, wszLargeIcons, sizeof(wszLargeIcons)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_VIEW_SMALL, wszSmallIcons, sizeof(wszSmallIcons)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_VIEW_DETAILS, wszDetails, sizeof(wszDetails)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_WINDOWS, wszWindows, sizeof(wszWindows)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_VIEW_SELECTCOLUMNS, wszSelectColumns, sizeof(wszSelectColumns)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_OPTIONS_SHOW16BITTASKS, wszShow16bTasks, sizeof(wszShow16bTasks)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_VIEW_CPUHISTORY_ONEGRAPHALL, wszOneGraphAllCPU, sizeof(wszOneGraphAllCPU)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_VIEW_CPUHISTORY_ONEGRAPHPERCPU, wszOneGraphPerCPU, sizeof(wszOneGraphPerCPU)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_VIEW_CPUHISTORY, wszCPUHistory, sizeof(wszCPUHistory)/sizeof(WCHAR));
    LoadStringW(hInst, IDS_VIEW_SHOWKERNELTIMES, wszShowKernelTimes, sizeof(wszShowKernelTimes)/sizeof(WCHAR));

    hMenu = GetMenu(hMainWnd);
    hViewMenu = GetSubMenu(hMenu, 2);
    hOptionsMenu = GetSubMenu(hMenu, 1);
    TaskManagerSettings.ActiveTabPage = SendMessageW(hTabWnd, TCM_GETCURSEL, 0, 0);
    for (i = GetMenuItemCount(hViewMenu) - 1; i > 2; i--) {
        hSubMenu = GetSubMenu(hViewMenu, i);
        if (hSubMenu)
            DestroyMenu(hSubMenu);
        RemoveMenu(hViewMenu, i, MF_BYPOSITION);
    }
    RemoveMenu(hOptionsMenu, 3, MF_BYPOSITION);
    switch (TaskManagerSettings.ActiveTabPage) {
    case 0:
        ShowWindow(hApplicationPage, SW_SHOW);
        ShowWindow(hProcessPage, SW_HIDE);
        ShowWindow(hPerformancePage, SW_HIDE);
        BringWindowToTop(hApplicationPage);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_LARGE, wszLargeIcons);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_SMALL, wszSmallIcons);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_DETAILS, wszDetails);

        if (GetMenuItemCount(hMenu) <= 4) {
            hSubMenu = LoadMenuW(hInst, MAKEINTRESOURCEW(IDR_WINDOWSMENU));
            InsertMenuW(hMenu, 3, MF_BYPOSITION|MF_POPUP, (UINT_PTR)hSubMenu, wszWindows);
            DrawMenuBar(hMainWnd);
        }
        if (TaskManagerSettings.View_LargeIcons)
            CheckMenuRadioItem(hViewMenu, ID_VIEW_LARGE, ID_VIEW_DETAILS, ID_VIEW_LARGE, MF_BYCOMMAND);
        else if (TaskManagerSettings.View_SmallIcons)
            CheckMenuRadioItem(hViewMenu, ID_VIEW_LARGE, ID_VIEW_DETAILS, ID_VIEW_SMALL, MF_BYCOMMAND);
        else
            CheckMenuRadioItem(hViewMenu, ID_VIEW_LARGE, ID_VIEW_DETAILS, ID_VIEW_DETAILS, MF_BYCOMMAND);
        /*
         * Give the application list control focus
         */
        SetFocus(hApplicationPageListCtrl);
        break;

    case 1:
        ShowWindow(hApplicationPage, SW_HIDE);
        ShowWindow(hProcessPage, SW_SHOW);
        ShowWindow(hPerformancePage, SW_HIDE);
        BringWindowToTop(hProcessPage);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_SELECTCOLUMNS, wszSelectColumns);
        AppendMenuW(hOptionsMenu, MF_STRING, ID_OPTIONS_SHOW16BITTASKS, wszShow16bTasks);
        if (TaskManagerSettings.Show16BitTasks)
            CheckMenuItem(hOptionsMenu, ID_OPTIONS_SHOW16BITTASKS, MF_BYCOMMAND|MF_CHECKED);
        if (GetMenuItemCount(hMenu) > 4)
        {
            RemoveMenu(hMenu, 3, MF_BYPOSITION);
            DrawMenuBar(hMainWnd);
        }
        /*
         * Give the process list control focus
         */
        SetFocus(hProcessPageListCtrl);
        break;

    case 2:
        ShowWindow(hApplicationPage, SW_HIDE);
        ShowWindow(hProcessPage, SW_HIDE);
        ShowWindow(hPerformancePage, SW_SHOW);
        BringWindowToTop(hPerformancePage);
        if (GetMenuItemCount(hMenu) > 4) {
            RemoveMenu(hMenu, 3, MF_BYPOSITION);
            DrawMenuBar(hMainWnd);
        }
        hSubMenu = CreatePopupMenu();
        AppendMenuW(hSubMenu, MF_STRING, ID_VIEW_CPUHISTORY_ONEGRAPHALL, wszOneGraphAllCPU);
        AppendMenuW(hSubMenu, MF_STRING, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, wszOneGraphPerCPU);
        AppendMenuW(hViewMenu, MF_STRING|MF_POPUP, (UINT_PTR)hSubMenu, wszCPUHistory);
        AppendMenuW(hViewMenu, MF_STRING, ID_VIEW_SHOWKERNELTIMES, wszShowKernelTimes);
        if (TaskManagerSettings.ShowKernelTimes)
            CheckMenuItem(hViewMenu, ID_VIEW_SHOWKERNELTIMES, MF_BYCOMMAND|MF_CHECKED);
        else
            CheckMenuItem(hViewMenu, ID_VIEW_SHOWKERNELTIMES, MF_BYCOMMAND|MF_UNCHECKED);
        if (TaskManagerSettings.CPUHistory_OneGraphPerCPU)
            CheckMenuRadioItem(hSubMenu, ID_VIEW_CPUHISTORY_ONEGRAPHALL, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, MF_BYCOMMAND);
        else
            CheckMenuRadioItem(hSubMenu, ID_VIEW_CPUHISTORY_ONEGRAPHALL, ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU, ID_VIEW_CPUHISTORY_ONEGRAPHALL, MF_BYCOMMAND);
        /*
         * Give the tab control focus
         */
        SetFocus(hTabWnd);
        break;
    }
}
Ejemplo n.º 17
0
void	THelp :: ProcessHelpRequest  ( TOrigin		Origin,
				       THotkeyType	Type,
				       HWND		hwnd,
				       uint		message,
				       WPARAM		wparam,
				       LPARAM		lparam )
    {
	THelpQueryContext		Context ;
	register int			i, depth, found, nesting ;
	register THelpDefinition *	HelpDef ;
	register THelpEntry *		Entry		=  NULL ,
			    *		ep,
			    *		sp ;
	HWND				ControlHwnd ;
	HMENU				hMenu ;
	register char *			p ;
	TWindow *			OwlWindow	=  GetWindowPtr ( hwnd ) ;




// La fenêtre veut-elle nous donner son contexte d'aide ?	
	Context. hwnd		=  hwnd ;
	Context. message	=  message ;
	Context. wparam		=  wparam ;
	Context. lparam		=  lparam ;
	Context. Origin		=  Origin ;
	Context. Type		=  Type ;
	memset ( & Context. Entry, 0, sizeof ( Context. Entry ) ) ;

	SendMessage ( hwnd, WM_QUERYHELPCONTEXT, 0, ( LPARAM ) & Context ) ;


	if  ( Context. Entry. ContextParam )
	   {
		Entry = & Context. Entry ;
		goto  GotHelpEntry ;
	    }


// Rechercher si cette fenêtre n'est pas déjà déclarée dans notre liste
	for  ( i = 0 ; i < MAX_HELP_ENTRIES ;  i ++ )
	   {
		if  ( HelpTable [i]. HelpFileIndex  ==  -1 )
			continue ;

		if  ( HelpTable [i]. AppliesTo  ==  WindowObject  &&
			HelpTable [i]. WindowHwnd  ==  hwnd )
		   {
			HelpDef = HelpTable + i ;
			goto  GotHelpDef ;
		    }
	     }


// Pas trouvée dans la table : s'agit-il d'une fenêtre OWL ?
// Si le focus est sur un contrôle, faudrait peut-être mieux prendre la
// boîte de dialogue parent...
	if  ( OwlWindow  ==  NULL  ||  OwlWindow -> GetDlgCtrlID ( ) )
		OwlWindow = GetWindowPtr ( GetParent ( hwnd ) ) ;

	if  ( OwlWindow  !=  NULL )
	   {
		const char *  zz = typeid ( * OwlWindow ). name ( ) ;


		for  ( i = 0 ; i < MAX_HELP_ENTRIES ; i ++ )
		    {
			if  ( HelpTable [i]. HelpFileIndex  ==  -1 )
				continue ;


			if  ( HelpTable [i]. AppliesTo  ==  ClassObject  &&
				! strcmp ( HelpTable [i]. ClassName, zz ) ) 
			   {
				HelpDef = HelpTable + i ;
				goto  GotHelpDef ;
			    }
		      }
	     }


// C'est la fin des haricots...
	NotFound ( TRUE, NULL, Origin, Type, hwnd, message, wparam, lparam ) ;
	return ;


GotHelpDef :
	// L'entrée dans la table d'aide a été trouvée ; il s'agit maintenant
	// de retrouver le contexte adéquat
	if  ( Origin  ==  WindowHelp  ||  Origin  ==  DialogBoxHelp )
	   {
		if  ( Type  ==  Contextual )
		   {
			ControlHwnd  =  GetFocus ( ) ;
			i = GetDlgCtrlID ( ControlHwnd ) ;

			for  ( ep = HelpDef -> ControlEntries ; 
					ep  !=  NULL  &&
					ep -> Type  !=  EndOfTable  &&
					ep -> Type  !=  WindowEnd ; ep ++ )
			   {
				if  ( i  ==  ep -> Id )
				   {
					Entry = ep ;
					break ;
				     }
			     }
		     }


	//  L'aide demandée n'est pas contextuelle OU 
	//  le contrôle qui a le focus n'appartient pas à cette fenêtre OU
	//  aucun contexte n'a été trouvé dans les contrôles pour cette
	// fenêtre
		if  ( Entry  ==  NULL )
		   {

		// Si la fenêtre est une boîte de dialogue, on va essayer de
		// voir s'il existe un contexte spécifique.
		// Note : cela ne sera possible que si l'aide est relative à une
		// classe OWL
			TWindow *	W = GetWindowPtr ( hwnd ) ;
			TDialog *	D = NULL ;


			if  ( W  !=  NULL )
				D = dynamic_cast <TDialog *> ( W ) ;


			if  ( D  ==  NULL )
			   {
				Entry = HelpDef -> WindowEntries ;
				goto  GotHelpEntry ;
			    }

		// Ca ne marche que si le nom de la ressource dialogue est
		// défini comme un nombre entier !!!
			i = ( int ) D -> Attr. Name ;				


		// Recherche de la WindowEntry ayant le bon numéro de boîte
		// ou, à défaut, de celle qui possède un id à 0.
			for  ( ep = HelpDef -> WindowEntries, sp = NULL ;
					ep  !=  NULL		&&	
					ep -> Type  !=  WindowEnd  &&
					ep -> Type  !=  EndOfTable ; ep ++ )
			  {
				if  ( ! ep -> Id  &&  sp  == NULL )
					sp = ep ; 	// 1er id à zéro
				else if  ( ep -> Id  ==  i )
				   {
					sp = ep ;
					break ;
				    }
			    }

			ep = ( sp  ==  NULL ) ?  HelpDef -> WindowEntries : sp ;
			goto  GotHelpDef ;
		    }
	      }	
		
	
	
// Cas des menus
	if  ( Origin  ==  MenuHelp )
	   {
		if  ( Type  ==  Normal )		// le cas le plus simple
		   {
			Entry = HelpDef -> MenuEntries ;
			goto  GotHelpEntry ;
		    }
			

	// Menu popup : on va  recherche son entrée dans la table en se basant
	// sur l'identificateur de son premier élément
		if  ( LastSelectedMenuType  & MF_SYSMENU )
		   {
			Entry = HelpDef -> MenuEntries ;
			goto  GotHelpEntry ;
		    }


		if  ( LastSelectedMenuType  & MF_POPUP )
		   {
			hMenu = LastSelectedMenuHandle ;
			depth = 0 ;
			i = -1 ;

			while  ( i  ==  -1 )
			   {
				i = GetMenuItemID ( hMenu, 0 ) ;
				hMenu = GetSubMenu ( hMenu, 0 ) ;
				depth ++ ;

				if  ( hMenu  ==  NULL )
					break ;
			     }
				

		// Aucun sous-élément n'a été trouvé !
			if  ( i  ==  -1 )
			   {
				Entry = HelpDef -> MenuEntries ;
				goto  GotHelpEntry ;
			    }

		// Un élément a été trouvé : on le cherche dans les entrées
			nesting = 0 ;

			for  ( sp = NULL, ep  =  HelpDef -> MenuEntries, found = 0 ; 
					ep  !=  NULL  &&
					ep -> Type !=  EndOfTable  &&  
					( ep  -> Type  != MenuEnd  ||  nesting ) ; ep ++ )
			   {
				if  ( ! ep -> Id )	
					sp = ep ;	// Dernier élément nul
				else if  ( ep -> Id  ==  i )
				   {
					found = 1 ;
					break ;
				    }

				if  ( ep -> Type  ==   MenuStart )
					nesting ++ ;
				else if  ( ep -> Type  !=  MenuEnd )
					nesting -- ;
			     }

		// Pas trouvé : on mettra l'aide en ligne sur le 1er élément
			if  ( ! found  ||  sp  ==  NULL )
			   {
				Entry = HelpDef -> MenuEntries ;
				goto  GotHelpEntry ;
			    }


		// Trouvé : dans le do...while, on a été susceptibles de descendre
		// plusieurs niveau de menu (si le 1er élément du menu est un
		// popup, dont le 1er élément est un popup, etc..)
		// On va essayer de remonter à partir de sp pour retrouver 
		// l'index du 1er popup
			while  ( depth  &&  sp  >=  HelpDef -> MenuEntries )
			   {
				depth -- ; 

				if  ( ! sp -> Id  &&  ! depth )
				   {
					Entry = sp ;
					goto   GotHelpEntry ;
				    }

				sp -- ;
			     }

			Entry = HelpDef -> MenuEntries ;
			goto  GotHelpEntry ;
		    }
		else
		   {
		// L'élément de menu n'est pas un popup
			nesting = 0 ;

			for  ( ep = HelpDef -> MenuEntries ; 
						ep  !=  NULL  &&
						ep -> Type  !=  EndOfTable  &&
						( ep -> Type  !=  MenuEnd || nesting ) ; ep ++ )
			   {
				if  ( ep -> Id  ==  LastSelectedMenu )
				   {
					Entry = ep ;
					goto  GotHelpEntry ;
				    }
				
				if  ( ep -> Type  ==  MenuStart )
					nesting ++ ;
				else if  ( ep -> Type  ==  MenuEnd )
					nesting -- ;
			    }
		     }
	    }



GotHelpEntry :

// On arrive ici avec Entry qui est peut-être nul; dans ce cas, on appelle l'index
	p = HelpFileNames [ HelpDef -> HelpFileIndex ] ;

// Si le pointeur est nul, on essaie de prendre par défaut l'aide relative à
// la fenêtre
	if  ( Entry  ==  NULL )
		Entry = HelpDef -> WindowEntries ;

	if  ( Entry  ==  NULL )
	   {
		NotFound ( FALSE, p, Origin, Type, hwnd, message, wparam, lparam ) ;
		Help ( p ) ;
	    }
	else
	   {
:: MessageBox ( NULL, "HELP", MB_OK, "ID = %d, KeyValue = [%s]",
Entry -> Id, Entry -> ContextParam ) ;

		if  ( Entry -> Type  ==  ByID )
			Help ( p, Entry -> ContextParam ) ;
		else
			Help ( p, ( char * ) Entry -> ContextParam ) ;
	    }

// Ouf, c'est fini ! j'en ferai pas tous les jours, des comme ça
     }
Ejemplo n.º 18
0
/* Message handler for dialog box. */
static INT_PTR CALLBACK
TaskManagerWndProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    static const WCHAR wszTaskmgr[] = {'t','a','s','k','m','g','r',0};
    HDC             hdc;
    PAINTSTRUCT     ps;
    LPRECT          pRC;
    RECT            rc;
    LPNMHDR         pnmh;
    WINDOWPLACEMENT wp;

    switch (message) {
    case WM_INITDIALOG:
        hMainWnd = hDlg;
        return OnCreate(hDlg);

    case WM_COMMAND:
        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) {
            EndDialog(hDlg, LOWORD(wParam));
            return TRUE;
        }
        /* Process menu commands */
        switch (LOWORD(wParam))
        {
        case ID_FILE_NEW:
            TaskManager_OnFileNew();
            break;
        case ID_OPTIONS_ALWAYSONTOP:
            TaskManager_OnOptionsAlwaysOnTop();
            break;
        case ID_OPTIONS_MINIMIZEONUSE:
            TaskManager_OnOptionsMinimizeOnUse();
            break;
        case ID_OPTIONS_HIDEWHENMINIMIZED:
            TaskManager_OnOptionsHideWhenMinimized();
            break;
        case ID_OPTIONS_SHOW16BITTASKS:
            TaskManager_OnOptionsShow16BitTasks();
            break;
        case ID_RESTORE:
            TaskManager_OnRestoreMainWindow();
            break;
        case ID_VIEW_LARGE:
            ApplicationPage_OnViewLargeIcons();
            break;
        case ID_VIEW_SMALL:
            ApplicationPage_OnViewSmallIcons();
            break;
        case ID_VIEW_DETAILS:
            ApplicationPage_OnViewDetails();
            break;
        case ID_VIEW_SHOWKERNELTIMES:
            PerformancePage_OnViewShowKernelTimes();
            break;
        case ID_VIEW_CPUHISTORY_ONEGRAPHALL:
            PerformancePage_OnViewCPUHistoryOneGraphAll();
            break;
        case ID_VIEW_CPUHISTORY_ONEGRAPHPERCPU:
            PerformancePage_OnViewCPUHistoryOneGraphPerCPU();
            break;
        case ID_VIEW_UPDATESPEED_HIGH:
            TaskManager_OnViewUpdateSpeedHigh();
            break;
        case ID_VIEW_UPDATESPEED_NORMAL:
            TaskManager_OnViewUpdateSpeedNormal();
            break;
        case ID_VIEW_UPDATESPEED_LOW:
            TaskManager_OnViewUpdateSpeedLow();
            break;
        case ID_VIEW_UPDATESPEED_PAUSED:
            TaskManager_OnViewUpdateSpeedPaused();
            break;
        case ID_VIEW_SELECTCOLUMNS:
            ProcessPage_OnViewSelectColumns();
            break;
        case ID_VIEW_REFRESH:
            PostMessageW(hDlg, WM_TIMER, 0, 0);
            break;
        case ID_WINDOWS_TILEHORIZONTALLY:
            ApplicationPage_OnWindowsTileHorizontally();
            break;
        case ID_WINDOWS_TILEVERTICALLY:
            ApplicationPage_OnWindowsTileVertically();
            break;
        case ID_WINDOWS_MINIMIZE:
            ApplicationPage_OnWindowsMinimize();
            break;
        case ID_WINDOWS_MAXIMIZE:
            ApplicationPage_OnWindowsMaximize();
            break;
        case ID_WINDOWS_CASCADE:
            ApplicationPage_OnWindowsCascade();
            break;
        case ID_WINDOWS_BRINGTOFRONT:
            ApplicationPage_OnWindowsBringToFront();
            break;
        case ID_APPLICATION_PAGE_SWITCHTO:
            ApplicationPage_OnSwitchTo();
            break;
        case ID_APPLICATION_PAGE_ENDTASK:
            ApplicationPage_OnEndTask();
            break;
        case ID_APPLICATION_PAGE_GOTOPROCESS:
            ApplicationPage_OnGotoProcess();
            break;
        case ID_PROCESS_PAGE_ENDPROCESS:
            ProcessPage_OnEndProcess();
            break;
        case ID_PROCESS_PAGE_ENDPROCESSTREE:
            ProcessPage_OnEndProcessTree();
            break;
        case ID_PROCESS_PAGE_DEBUG:
            ProcessPage_OnDebug();
            break;
        case ID_PROCESS_PAGE_SETAFFINITY:
            ProcessPage_OnSetAffinity();
            break;
        case ID_PROCESS_PAGE_SETPRIORITY_REALTIME:
            ProcessPage_OnSetPriorityRealTime();
            break;
        case ID_PROCESS_PAGE_SETPRIORITY_HIGH:
            ProcessPage_OnSetPriorityHigh();
            break;
        case ID_PROCESS_PAGE_SETPRIORITY_ABOVENORMAL:
            ProcessPage_OnSetPriorityAboveNormal();
            break;
        case ID_PROCESS_PAGE_SETPRIORITY_NORMAL:
            ProcessPage_OnSetPriorityNormal();
            break;
        case ID_PROCESS_PAGE_SETPRIORITY_BELOWNORMAL:
            ProcessPage_OnSetPriorityBelowNormal();
            break;
        case ID_PROCESS_PAGE_SETPRIORITY_LOW:
            ProcessPage_OnSetPriorityLow();
            break;
        case ID_PROCESS_PAGE_DEBUGCHANNELS:
            ProcessPage_OnDebugChannels();
            break;
        case ID_HELP_TOPICS:
            WinHelpW(hDlg, wszTaskmgr, HELP_FINDER, 0);
            break;
        case ID_HELP_ABOUT:
            OnAbout();
            break;
        case ID_FILE_EXIT:
            EndDialog(hDlg, IDOK);
            break;
        }     
        break;

    case WM_ONTRAYICON:
        switch(lParam)
        {
        case WM_RBUTTONDOWN:
            {
            POINT pt;
            BOOL OnTop;
            HMENU hMenu, hPopupMenu;
            
            GetCursorPos(&pt);
            
            OnTop = (GetWindowLongW(hMainWnd, GWL_EXSTYLE) & WS_EX_TOPMOST) != 0;
            
            hMenu = LoadMenuW(hInst, MAKEINTRESOURCEW(IDR_TRAY_POPUP));
            hPopupMenu = GetSubMenu(hMenu, 0);
            
            if(IsWindowVisible(hMainWnd))
            {
              DeleteMenu(hPopupMenu, ID_RESTORE, MF_BYCOMMAND);
            }
            else
            {
              SetMenuDefaultItem(hPopupMenu, ID_RESTORE, FALSE);
            }
            
            if(OnTop)
            {
              CheckMenuItem(hPopupMenu, ID_OPTIONS_ALWAYSONTOP, MF_BYCOMMAND | MF_CHECKED);
            }
            
            SetForegroundWindow(hMainWnd);
            TrackPopupMenuEx(hPopupMenu, 0, pt.x, pt.y, hMainWnd, NULL);
            
            DestroyMenu(hMenu);
            break;
            }
        case WM_LBUTTONDBLCLK:
            TaskManager_OnRestoreMainWindow();
            break;
        }
        break;

    case WM_NOTIFY:
        pnmh = (LPNMHDR)lParam;
        if ((pnmh->hwndFrom == hTabWnd) &&
            (pnmh->idFrom == IDC_TAB) &&
            (pnmh->code == TCN_SELCHANGE))
        {
            TaskManager_OnTabWndSelChange();
        }
        break;

    case WM_NCPAINT:
        hdc = GetDC(hDlg);
        GetClientRect(hDlg, &rc);
        Draw3dRect(hdc, rc.left, rc.top, rc.right, rc.top + 2, GetSysColor(COLOR_3DSHADOW), GetSysColor(COLOR_3DHILIGHT));
        ReleaseDC(hDlg, hdc);
        break;

    case WM_PAINT:
        hdc = BeginPaint(hDlg, &ps);
        GetClientRect(hDlg, &rc);
        Draw3dRect(hdc, rc.left, rc.top, rc.right, rc.top + 2, GetSysColor(COLOR_3DSHADOW), GetSysColor(COLOR_3DHILIGHT));
        EndPaint(hDlg, &ps);
        break;

    case WM_SIZING:
        /* Make sure the user is sizing the dialog */
        /* in an acceptable range */
        pRC = (LPRECT)lParam;
        if ((wParam == WMSZ_LEFT) || (wParam == WMSZ_TOPLEFT) || (wParam == WMSZ_BOTTOMLEFT)) {
            /* If the width is too small enlarge it to the minimum */
            if (nMinimumWidth > (pRC->right - pRC->left))
                pRC->left = pRC->right - nMinimumWidth;
        } else {
            /* If the width is too small enlarge it to the minimum */
            if (nMinimumWidth > (pRC->right - pRC->left))
                pRC->right = pRC->left + nMinimumWidth;
        }
        if ((wParam == WMSZ_TOP) || (wParam == WMSZ_TOPLEFT) || (wParam == WMSZ_TOPRIGHT)) {
            /* If the height is too small enlarge it to the minimum */
            if (nMinimumHeight > (pRC->bottom - pRC->top))
                pRC->top = pRC->bottom - nMinimumHeight;
        } else {
            /* If the height is too small enlarge it to the minimum */
            if (nMinimumHeight > (pRC->bottom - pRC->top))
                pRC->bottom = pRC->top + nMinimumHeight;
        }
        return TRUE;

    case WM_SIZE:
        /* Handle the window sizing in it's own function */
        OnSize(wParam, LOWORD(lParam), HIWORD(lParam));
        break;

    case WM_MOVE:
        /* Handle the window moving in it's own function */
        OnMove(wParam, LOWORD(lParam), HIWORD(lParam));
        break;

    case WM_DESTROY:
        ShowWindow(hDlg, SW_HIDE);
        TrayIcon_ShellRemoveTrayIcon();
        wp.length = sizeof(WINDOWPLACEMENT);
        GetWindowPlacement(hDlg, &wp);
        TaskManagerSettings.Left = wp.rcNormalPosition.left;
        TaskManagerSettings.Top = wp.rcNormalPosition.top;
        TaskManagerSettings.Right = wp.rcNormalPosition.right;
        TaskManagerSettings.Bottom = wp.rcNormalPosition.bottom;
        if (IsZoomed(hDlg) || (wp.flags & WPF_RESTORETOMAXIMIZED))
            TaskManagerSettings.Maximized = TRUE;
        else
            TaskManagerSettings.Maximized = FALSE;
        return DefWindowProcW(hDlg, message, wParam, lParam);

    case WM_TIMER:
        /* Refresh the performance data */
        PerfDataRefresh();
        RefreshApplicationPage();
        RefreshProcessPage();
        RefreshPerformancePage();
        TrayIcon_ShellUpdateTrayIcon();
        break;

    case WM_ENTERMENULOOP:
        TaskManager_OnEnterMenuLoop(hDlg);
        break;
    case WM_EXITMENULOOP:
        TaskManager_OnExitMenuLoop(hDlg);
        break;
    case WM_MENUSELECT:
        TaskManager_OnMenuSelect(hDlg, LOWORD(wParam), HIWORD(wParam), (HMENU)lParam);
        break;
    }

    return 0;
}
Ejemplo n.º 19
0
/*******************************************************************************
 *
 *  FUNCTION: ChildWndProc(HWND, unsigned, WORD, LONG)
 *
 *  PURPOSE:  Processes messages for the child windows.
 *
 *  WM_COMMAND  - process the application menu
 *  WM_PAINT    - Paint the main window
 *  WM_DESTROY  - post a quit message and return
 *
 */
LRESULT CALLBACK ChildWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    BOOL Result;

    switch (message)
    {
    case WM_CREATE:
    {
        WNDPROC oldproc;
        HFONT hFont;
        WCHAR buffer[MAX_PATH];

        /* Load "My Computer" string */
        LoadStringW(hInst, IDS_MY_COMPUTER, buffer, COUNT_OF(buffer));

        g_pChildWnd = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(ChildWnd));
        if (!g_pChildWnd) return 0;

        wcsncpy(g_pChildWnd->szPath, buffer, MAX_PATH);
        g_pChildWnd->nSplitPos = 250;
        g_pChildWnd->hWnd = hWnd;
        g_pChildWnd->hAddressBarWnd = CreateWindowExW(WS_EX_CLIENTEDGE, L"Edit", NULL, WS_CHILD | WS_VISIBLE | WS_CHILDWINDOW | WS_TABSTOP,
                                                      CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
                                                      hWnd, (HMENU)0, hInst, 0);
        g_pChildWnd->hAddressBtnWnd = CreateWindowExW(0, L"Button", L"\x00BB", WS_CHILD | WS_VISIBLE | WS_CHILDWINDOW | WS_TABSTOP | BS_TEXT | BS_CENTER | BS_VCENTER | BS_FLAT | BS_DEFPUSHBUTTON,
                                                      CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
                                                      hWnd, (HMENU)0, hInst, 0);
        g_pChildWnd->hTreeWnd = CreateTreeView(hWnd, g_pChildWnd->szPath, (HMENU) TREE_WINDOW);
        g_pChildWnd->hListWnd = CreateListView(hWnd, (HMENU) LIST_WINDOW/*, g_pChildWnd->szPath*/);
        SetFocus(g_pChildWnd->hTreeWnd);

        /* set the address bar and button font */
        if ((g_pChildWnd->hAddressBarWnd) && (g_pChildWnd->hAddressBtnWnd))
        {
            hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
            SendMessageW(g_pChildWnd->hAddressBarWnd,
                         WM_SETFONT,
                         (WPARAM)hFont,
                         0);
            SendMessageW(g_pChildWnd->hAddressBtnWnd,
                         WM_SETFONT,
                         (WPARAM)hFont,
                         0);
        }
        /* Subclass the AddressBar */
        oldproc = (WNDPROC)GetWindowLongPtr(g_pChildWnd->hAddressBarWnd, GWLP_WNDPROC);
        SetWindowLongPtr(g_pChildWnd->hAddressBarWnd, GWLP_USERDATA, (DWORD_PTR)oldproc);
        SetWindowLongPtr(g_pChildWnd->hAddressBarWnd, GWLP_WNDPROC, (DWORD_PTR)AddressBarProc);
        break;
    }
    case WM_COMMAND:
        if(HIWORD(wParam) == BN_CLICKED)
        {
            PostMessageW(g_pChildWnd->hAddressBarWnd, WM_KEYUP, VK_RETURN, 0);
        }

        if (!_CmdWndProc(hWnd, message, wParam, lParam))
        {
            goto def;
        }
        break;
    case WM_PAINT:
        OnPaint(hWnd);
        return 0;
    case WM_SETCURSOR:
        if (LOWORD(lParam) == HTCLIENT)
        {
            POINT pt;
            GetCursorPos(&pt);
            ScreenToClient(hWnd, &pt);
            if (pt.x>=g_pChildWnd->nSplitPos-SPLIT_WIDTH/2 && pt.x<g_pChildWnd->nSplitPos+SPLIT_WIDTH/2+1)
            {
                SetCursor(LoadCursorW(0, IDC_SIZEWE));
                return TRUE;
            }
        }
        goto def;
    case WM_DESTROY:
        DestroyListView(g_pChildWnd->hListWnd);
        DestroyTreeView(g_pChildWnd->hTreeWnd);
        DestroyMainMenu();
        HeapFree(GetProcessHeap(), 0, g_pChildWnd);
        g_pChildWnd = NULL;
        PostQuitMessage(0);
        break;
    case WM_LBUTTONDOWN:
    {
        RECT rt;
        int x = (short)LOWORD(lParam);
        GetClientRect(hWnd, &rt);
        if (x>=g_pChildWnd->nSplitPos-SPLIT_WIDTH/2 && x<g_pChildWnd->nSplitPos+SPLIT_WIDTH/2+1)
        {
            last_split = g_pChildWnd->nSplitPos;
            draw_splitbar(hWnd, last_split);
            SetCapture(hWnd);
        }
        break;
    }

    case WM_LBUTTONUP:
    case WM_RBUTTONDOWN:
        if (GetCapture() == hWnd)
        {
            finish_splitbar(hWnd, LOWORD(lParam));
        }
        break;

    case WM_CAPTURECHANGED:
        if (GetCapture()==hWnd && last_split>=0)
            draw_splitbar(hWnd, last_split);
        break;

    case WM_KEYDOWN:
        if (wParam == VK_ESCAPE)
            if (GetCapture() == hWnd)
            {
                RECT rt;
                draw_splitbar(hWnd, last_split);
                GetClientRect(hWnd, &rt);
                ResizeWnd(rt.right, rt.bottom);
                last_split = -1;
                ReleaseCapture();
                SetCursor(LoadCursorW(0, IDC_ARROW));
            }
        break;

    case WM_MOUSEMOVE:
        if (GetCapture() == hWnd)
        {
            HDC hdc;
            RECT rt;
            HGDIOBJ OldObj;
            int x = LOWORD(lParam);
            if(!SizingPattern)
            {
                const DWORD Pattern[4] = {0x5555AAAA, 0x5555AAAA, 0x5555AAAA, 0x5555AAAA};
                SizingPattern = CreateBitmap(8, 8, 1, 1, Pattern);
            }
            if(!SizingBrush)
            {
                SizingBrush = CreatePatternBrush(SizingPattern);
            }

            GetClientRect(hWnd, &rt);
            x = (SHORT) min(max(x, SPLIT_MIN), rt.right - SPLIT_MIN);
            if(last_split != x)
            {
                rt.left = last_split-SPLIT_WIDTH/2;
                rt.right = last_split+SPLIT_WIDTH/2+1;
                hdc = GetDC(hWnd);
                OldObj = SelectObject(hdc, SizingBrush);
                PatBlt(hdc, rt.left, rt.top, rt.right - rt.left, rt.bottom - rt.top, PATINVERT);
                last_split = x;
                rt.left = x-SPLIT_WIDTH/2;
                rt.right = x+SPLIT_WIDTH/2+1;
                PatBlt(hdc, rt.left, rt.top, rt.right - rt.left, rt.bottom - rt.top, PATINVERT);
                SelectObject(hdc, OldObj);
                ReleaseDC(hWnd, hdc);
            }
        }
        break;

    case WM_SETFOCUS:
        if (g_pChildWnd != NULL)
        {
            SetFocus(g_pChildWnd->nFocusPanel? g_pChildWnd->hListWnd: g_pChildWnd->hTreeWnd);
        }
        break;

    case WM_TIMER:
        break;

    case WM_NOTIFY:
        if ((int)wParam == TREE_WINDOW && g_pChildWnd != NULL)
        {
            switch (((LPNMHDR)lParam)->code)
            {
            case TVN_ITEMEXPANDING:
                return !OnTreeExpanding(g_pChildWnd->hTreeWnd, (NMTREEVIEW*)lParam);
            case TVN_SELCHANGED:
            {
                NMTREEVIEW* pnmtv = (NMTREEVIEW*)lParam;
                /* Get the parent of the current item */
                HTREEITEM hParentItem = TreeView_GetParent(g_pChildWnd->hTreeWnd, pnmtv->itemNew.hItem);

                UpdateAddress(pnmtv->itemNew.hItem, NULL, NULL);

                /*
                 * Disable Delete/Rename menu options for 'My Computer' (first item so doesn't have any parent)
                 * and HKEY_* keys (their parent is 'My Computer' and the previous remark applies).
                 */
                if (!hParentItem || !TreeView_GetParent(g_pChildWnd->hTreeWnd, hParentItem))
                {
                    EnableMenuItem(hMenuFrame , ID_EDIT_DELETE, MF_BYCOMMAND | MF_GRAYED);
                    EnableMenuItem(hMenuFrame , ID_EDIT_RENAME, MF_BYCOMMAND | MF_GRAYED);
                    EnableMenuItem(hPopupMenus, ID_TREE_DELETE, MF_BYCOMMAND | MF_GRAYED);
                    EnableMenuItem(hPopupMenus, ID_TREE_RENAME, MF_BYCOMMAND | MF_GRAYED); 
                }
                else
                {
                    EnableMenuItem(hMenuFrame , ID_EDIT_DELETE, MF_BYCOMMAND | MF_ENABLED);
                    EnableMenuItem(hMenuFrame , ID_EDIT_RENAME, MF_BYCOMMAND | MF_ENABLED);
                    EnableMenuItem(hPopupMenus, ID_TREE_DELETE, MF_BYCOMMAND | MF_ENABLED);
                    EnableMenuItem(hPopupMenus, ID_TREE_RENAME, MF_BYCOMMAND | MF_ENABLED);
                }

                break;
            }
            case NM_SETFOCUS:
                g_pChildWnd->nFocusPanel = 0;
                break;
            case TVN_BEGINLABELEDIT:
            {
                LPNMTVDISPINFO ptvdi;
                /* cancel label edit for rootkeys  */
                ptvdi = (LPNMTVDISPINFO) lParam;
                if (!TreeView_GetParent(g_pChildWnd->hTreeWnd, ptvdi->item.hItem) ||
                    !TreeView_GetParent(g_pChildWnd->hTreeWnd, TreeView_GetParent(g_pChildWnd->hTreeWnd, ptvdi->item.hItem)))
                    return TRUE;
                break;
            }
            case TVN_ENDLABELEDIT:
            {
                LPCWSTR keyPath;
                HKEY hRootKey;
                HKEY hKey = NULL;
                LPNMTVDISPINFO ptvdi;
                LONG lResult = TRUE;
                WCHAR szBuffer[MAX_PATH];

                ptvdi = (LPNMTVDISPINFO) lParam;
                if (ptvdi->item.pszText)
                {
                    keyPath = GetItemPath(g_pChildWnd->hTreeWnd, TreeView_GetParent(g_pChildWnd->hTreeWnd, ptvdi->item.hItem), &hRootKey);
                    _snwprintf(szBuffer, COUNT_OF(szBuffer), L"%s\\%s", keyPath, ptvdi->item.pszText);
                    keyPath = GetItemPath(g_pChildWnd->hTreeWnd, ptvdi->item.hItem, &hRootKey);
                    if (RegOpenKeyExW(hRootKey, szBuffer, 0, KEY_READ, &hKey) == ERROR_SUCCESS)
                    {
                        lResult = FALSE;
                        RegCloseKey(hKey);
                        (void)TreeView_EditLabel(g_pChildWnd->hTreeWnd, ptvdi->item.hItem);
                    }
                    else
                    {
                        if (RenameKey(hRootKey, keyPath, ptvdi->item.pszText) != ERROR_SUCCESS)
                            lResult = FALSE;
                        else
                            UpdateAddress(ptvdi->item.hItem, hRootKey, szBuffer);
                    }
                    return lResult;
                }
            }
            default:
                return 0;
            }
        }
        else
        {
            if ((int)wParam == LIST_WINDOW && g_pChildWnd != NULL)
            {
                switch (((LPNMHDR)lParam)->code)
                {
                case NM_SETFOCUS:
                    g_pChildWnd->nFocusPanel = 1;
                    break;
                default:
                    if(!ListWndNotifyProc(g_pChildWnd->hListWnd, wParam, lParam, &Result))
                    {
                        goto def;
                    }
                    return Result;
                    break;
                }
            }
        }
        break;

    case WM_CONTEXTMENU:
    {
        POINT pt;
        if((HWND)wParam == g_pChildWnd->hListWnd)
        {
            int i, cnt;
            BOOL IsDefault;
            pt.x = (short) LOWORD(lParam);
            pt.y = (short) HIWORD(lParam);
            cnt = ListView_GetSelectedCount(g_pChildWnd->hListWnd);
            i = ListView_GetNextItem(g_pChildWnd->hListWnd, -1, LVNI_FOCUSED | LVNI_SELECTED);
            if (pt.x == -1 && pt.y == -1)
            {
                RECT rc;
                if (i != -1)
                {
                    rc.left = LVIR_BOUNDS;
                    SendMessageW(g_pChildWnd->hListWnd, LVM_GETITEMRECT, i, (LPARAM) &rc);
                    pt.x = rc.left + 8;
                    pt.y = rc.top + 8;
                }
                else
                    pt.x = pt.y = 0;
                ClientToScreen(g_pChildWnd->hListWnd, &pt);
            }
            if(i == -1)
            {
                TrackPopupMenu(GetSubMenu(hPopupMenus, PM_NEW), TPM_RIGHTBUTTON, pt.x, pt.y, 0, hFrameWnd, NULL);
            }
            else
            {
                HMENU mnu = GetSubMenu(hPopupMenus, PM_MODIFYVALUE);
                SetMenuDefaultItem(mnu, ID_EDIT_MODIFY, MF_BYCOMMAND);
                IsDefault = IsDefaultValue(g_pChildWnd->hListWnd, i);
                if(cnt == 1)
                    EnableMenuItem(mnu, ID_EDIT_RENAME, MF_BYCOMMAND | (IsDefault ? MF_DISABLED | MF_GRAYED : MF_ENABLED));
                else
                    EnableMenuItem(mnu, ID_EDIT_RENAME, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
                EnableMenuItem(mnu, ID_EDIT_MODIFY, MF_BYCOMMAND | (cnt == 1 ? MF_ENABLED : MF_DISABLED | MF_GRAYED));
                EnableMenuItem(mnu, ID_EDIT_MODIFY_BIN, MF_BYCOMMAND | (cnt == 1 ? MF_ENABLED : MF_DISABLED | MF_GRAYED));

                TrackPopupMenu(mnu, TPM_RIGHTBUTTON, pt.x, pt.y, 0, hFrameWnd, NULL);
            }
        }
        else if ((HWND)wParam == g_pChildWnd->hTreeWnd)
        {
            TVHITTESTINFO hti;
            HMENU hContextMenu;
            TVITEMW item;
            MENUITEMINFOW mii;
            WCHAR resource[256];
            WCHAR buffer[256];
            LPWSTR s;
            LPCWSTR keyPath;
            HKEY hRootKey;
            int iLastPos;
            WORD wID;

            pt.x = (short) LOWORD(lParam);
            pt.y = (short) HIWORD(lParam);

            if (pt.x == -1 && pt.y == -1)
            {
                RECT rc;
                hti.hItem = TreeView_GetSelection(g_pChildWnd->hTreeWnd);
                if (hti.hItem != NULL)
                {
                    TreeView_GetItemRect(g_pChildWnd->hTreeWnd, hti.hItem, &rc, TRUE);
                    pt.x = rc.left + 8;
                    pt.y = rc.top + 8;
                    ClientToScreen(g_pChildWnd->hTreeWnd, &pt);
                    hti.flags = TVHT_ONITEM;
                }
                else
                    hti.flags = 0;
            }
            else
            {
                hti.pt.x = pt.x;
                hti.pt.y = pt.y;
                ScreenToClient(g_pChildWnd->hTreeWnd, &hti.pt);
                (void)TreeView_HitTest(g_pChildWnd->hTreeWnd, &hti);
            }

            if (hti.flags & TVHT_ONITEM)
            {
                hContextMenu = GetSubMenu(hPopupMenus, PM_TREECONTEXT);
                (void)TreeView_SelectItem(g_pChildWnd->hTreeWnd, hti.hItem);

                memset(&item, 0, sizeof(item));
                item.mask = TVIF_STATE | TVIF_CHILDREN;
                item.hItem = hti.hItem;
                (void)TreeView_GetItem(g_pChildWnd->hTreeWnd, &item);

                /* Set the Expand/Collapse menu item appropriately */
                LoadStringW(hInst, (item.state & TVIS_EXPANDED) ? IDS_COLLAPSE : IDS_EXPAND, buffer, COUNT_OF(buffer));
                memset(&mii, 0, sizeof(mii));
                mii.cbSize = sizeof(mii);
                mii.fMask = MIIM_STRING | MIIM_STATE | MIIM_ID;
                mii.fState = (item.cChildren > 0) ? MFS_DEFAULT : MFS_GRAYED;
                mii.wID = (item.state & TVIS_EXPANDED) ? ID_TREE_COLLAPSEBRANCH : ID_TREE_EXPANDBRANCH;
                mii.dwTypeData = (LPWSTR) buffer;
                SetMenuItemInfo(hContextMenu, 0, TRUE, &mii);

                /* Remove any existing suggestions */
                memset(&mii, 0, sizeof(mii));
                mii.cbSize = sizeof(mii);
                mii.fMask = MIIM_ID;
                GetMenuItemInfo(hContextMenu, GetMenuItemCount(hContextMenu) - 1, TRUE, &mii);
                if ((mii.wID >= ID_TREE_SUGGESTION_MIN) && (mii.wID <= ID_TREE_SUGGESTION_MAX))
                {
                    do
                    {
                        iLastPos = GetMenuItemCount(hContextMenu) - 1;
                        GetMenuItemInfo(hContextMenu, iLastPos, TRUE, &mii);
                        RemoveMenu(hContextMenu, iLastPos, MF_BYPOSITION);
                    }
                    while((mii.wID >= ID_TREE_SUGGESTION_MIN) && (mii.wID <= ID_TREE_SUGGESTION_MAX));
                }

                /* Come up with suggestions */
                keyPath = GetItemPath(g_pChildWnd->hTreeWnd, NULL, &hRootKey);
                SuggestKeys(hRootKey, keyPath, Suggestions, COUNT_OF(Suggestions));
                if (Suggestions[0])
                {
                    AppendMenu(hContextMenu, MF_SEPARATOR, 0, NULL);

                    LoadStringW(hInst, IDS_GOTO_SUGGESTED_KEY, resource, COUNT_OF(resource));

                    s = Suggestions;
                    wID = ID_TREE_SUGGESTION_MIN;
                    while(*s && (wID <= ID_TREE_SUGGESTION_MAX))
                    {
                        _snwprintf(buffer, COUNT_OF(buffer), resource, s);

                        memset(&mii, 0, sizeof(mii));
                        mii.cbSize = sizeof(mii);
                        mii.fMask = MIIM_STRING | MIIM_ID;
                        mii.wID = wID++;
                        mii.dwTypeData = buffer;
                        InsertMenuItem(hContextMenu, GetMenuItemCount(hContextMenu), TRUE, &mii);

                        s += wcslen(s) + 1;
                    }
                }
                TrackPopupMenu(hContextMenu, TPM_RIGHTBUTTON, pt.x, pt.y, 0, g_pChildWnd->hWnd, NULL);
            }
        }
        break;
    }

    case WM_SIZE:
        if (wParam != SIZE_MINIMIZED && g_pChildWnd != NULL)
        {
            ResizeWnd(LOWORD(lParam), HIWORD(lParam));
        }
        /* fall through */
    default:
def:
        return DefWindowProcW(hWnd, message, wParam, lParam);
    }
    return 0;
}
Ejemplo n.º 20
0
HMENU AFXAPI AfxMergeMenus(HMENU hMenuShared, HMENU hMenuSource,
	LONG* lpMenuWidths, int iWidthIndex, BOOL bMergeHelpMenus /* = FALSE */)
{
	ASSERT(hMenuShared != NULL && IsMenu(hMenuShared));
	ASSERT(hMenuSource != NULL && IsMenu(hMenuSource));

	BOOL bHelpMergedAsSubMenu = FALSE;
	HMENU hHelpSubMenu = NULL;

	// copy the popups from the pMenuSource
	int cMenuItems = GetMenuItemCount(hMenuSource);
	int cGroupWidth = 0;
	int nPosition = 0;

	// insert at appropriate spot depending on iWidthIndex
	ASSERT(iWidthIndex == 0 || iWidthIndex == 1);
	if (iWidthIndex == 1)
		nPosition = (int)lpMenuWidths[0];

	for (int i = 0; i < cMenuItems; i++)
	{
		// get the HMENU of the popup
		HMENU hMenuPopup = ::GetSubMenu(hMenuSource, i);

		// separators move us to next group
		UINT state = GetMenuState(hMenuSource, i, MF_BYPOSITION);
		if (hMenuPopup == NULL && (state & MF_SEPARATOR) != 0)
		{
			ASSERT(iWidthIndex <= 5);   // servers should not touch past 5
			lpMenuWidths[iWidthIndex] = cGroupWidth;
			cGroupWidth = 0;
			if (iWidthIndex < 5)
				nPosition += (int)lpMenuWidths[iWidthIndex+1];
			iWidthIndex += 2;
		}
		else
		{
			HMENU hHelpMenu = NULL;

			// are we processing the help menu group?

			if (bMergeHelpMenus && iWidthIndex == 5)
			{
				// if so, see if the container has Help any menu items
				if (lpMenuWidths[iWidthIndex] == 1)
				{
					// get the help menu from the container
					hHelpMenu = GetSubMenu(hMenuShared, nPosition);
				}
			}

			// get the menu item text
			TCHAR szItemText[256];
			int nLen = GetMenuString(hMenuSource, i, szItemText,
				sizeof szItemText, MF_BYPOSITION);

			// popups are handled differently than normal menu items
			if (hMenuPopup != NULL)
			{
				if (hHelpMenu != NULL)
				{
					CString strTearOff = AfxGetAppName();
					if (!strTearOff.IsEmpty())
						strTearOff += ' ';
					strTearOff += szItemText;

					// container has help items -- add ours to its submenu
					AppendMenu(hHelpMenu, MF_STRING | MF_POPUP,
						(UINT)hMenuPopup, strTearOff);

					// clear the count of Help group items and add
					// the help menu to the window group

					lpMenuWidths[iWidthIndex] = 0;
					lpMenuWidths[iWidthIndex-1]++;

					bHelpMergedAsSubMenu = TRUE;
					hHelpSubMenu = hMenuPopup;
				}
				else if (::GetMenuItemCount(hMenuPopup) != 0)
				{
					// strip the HIBYTE because it contains a count of items
					state = LOBYTE(state) | MF_POPUP;   // must be popup

					// non-empty popup -- add it to the shared menu bar
					InsertMenu(hMenuShared, nPosition, state | MF_BYPOSITION,
						(UINT)hMenuPopup, szItemText);
					++nPosition;
					++cGroupWidth;
				}
			}
			else if (nLen > 0)
			{
				// only non-empty items are added
				ASSERT(szItemText[0] != 0);

				// here the state does not contain a count in the HIBYTE
				InsertMenu(hMenuShared, nPosition, state | MF_BYPOSITION,
					GetMenuItemID(hMenuSource, i), szItemText);
				++nPosition;
				++cGroupWidth;
			}
		}
	}

	// set the last group width

	if (!bHelpMergedAsSubMenu)
	{
		ASSERT(iWidthIndex <= 5);   // servers should not touch past 5
		lpMenuWidths[iWidthIndex] = cGroupWidth;
	}

	return hHelpSubMenu;
}
Ejemplo n.º 21
0
Archivo: audio.c Proyecto: bilboed/wine
INT_PTR CALLBACK
AudioDlgProc (HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  switch (uMsg) {
      case WM_COMMAND:
	switch (LOWORD(wParam)) {
          case IDC_AUDIO_CONFIGURE:
	     configureAudioDriver(hDlg);
	     break;
          case IDC_AUDIO_TEST:
	     if(!PlaySound(MAKEINTRESOURCE(IDW_TESTSOUND), NULL, SND_RESOURCE | SND_SYNC))
                MessageBox(NULL, "Audio test failed!", "Error", MB_OK | MB_ICONERROR);
             break;
          case IDC_AUDIO_CONTROL_PANEL:
	     MessageBox(NULL, "Launching audio control panel not implemented yet!", "Fixme", MB_OK | MB_ICONERROR);
             break;
          case IDC_DSOUND_HW_ACCEL:
	    if (HIWORD(wParam) == CBN_SELCHANGE) {
	      int selected_dsound_accel;
              int i, j = 0;

	      SendMessage(GetParent(hDlg), PSM_CHANGED, 0, 0);
	      selected_dsound_accel = SendDlgItemMessage(hDlg, IDC_DSOUND_HW_ACCEL, CB_GETCURSEL, 0, 0);
              for (i = 0; DSound_HW_Accels[i].settingStr; ++i)
              {
                if (DSound_HW_Accels[i].visible)
                {
                  if (j == selected_dsound_accel)
                  {
                    set_reg_key(config_key, keypath("DirectSound"), "HardwareAcceleration",
                      DSound_HW_Accels[i].settingStr);
                    break;
                  }
                  j++;
                }
              }
	    }
	    break;
          case IDC_DSOUND_RATES:
	    if (HIWORD(wParam) == CBN_SELCHANGE) {
	      int selected_dsound_rate;
	      SendMessage(GetParent(hDlg), PSM_CHANGED, 0, 0);
	      selected_dsound_rate = SendDlgItemMessage(hDlg, IDC_DSOUND_RATES, CB_GETCURSEL, 0, 0);
	      set_reg_key(config_key, keypath("DirectSound"), "DefaultSampleRate", DSound_Rates[selected_dsound_rate]);
	    }
	    break;
          case IDC_DSOUND_BITS:
	    if (HIWORD(wParam) == CBN_SELCHANGE) {
	      int selected_dsound_bits;
	      SendMessage(GetParent(hDlg), PSM_CHANGED, 0, 0);
	      selected_dsound_bits = SendDlgItemMessage(hDlg, IDC_DSOUND_BITS, CB_GETCURSEL, 0, 0);
	      set_reg_key(config_key, keypath("DirectSound"), "DefaultBitsPerSample", DSound_Bits[selected_dsound_bits]);
	    }
	    break;
	}
	break;

      case WM_SHOWWINDOW:
        set_window_title(hDlg);
        break;

      case WM_NOTIFY:
	switch(((LPNMHDR)lParam)->code) {
	    case PSN_KILLACTIVE:
	      SetWindowLongPtr(hDlg, DWLP_MSGRESULT, FALSE);
	      break;
	    case PSN_APPLY:
	      set_reg_key(config_key, "Drivers", "Audio", curAudioDriver);
              apply();
	      SetWindowLongPtr(hDlg, DWLP_MSGRESULT, PSNRET_NOERROR);
	      break;
	    case PSN_SETACTIVE:
	      break;
            case NM_CLICK:
              if (((LPNMHDR)lParam)->idFrom == IDC_AUDIO_TREE)
              {
                  TVHITTESTINFO ht;
                  DWORD dwPos = GetMessagePos();
                  HWND tree = ((LPNMHDR)lParam)->hwndFrom;
                  ZeroMemory(&ht, sizeof(ht));
                  ht.pt.x = (short)LOWORD(dwPos);
                  ht.pt.y = (short)HIWORD(dwPos);
                  MapWindowPoints(HWND_DESKTOP, tree, &ht.pt, 1);
                  SendMessageW( tree, TVM_HITTEST, 0, (LPARAM)&ht );
                  if (TVHT_ONITEMSTATEICON & ht.flags)
                  {
                      TVITEM tvItem;
                      int index;
                      ZeroMemory(&tvItem, sizeof(tvItem));
                      tvItem.hItem = ht.hItem;
                      SendMessageW( tree, TVM_GETITEMW, 0, (LPARAM) &tvItem );

                      index = TreeView_GetItemState(tree, ht.hItem, TVIS_STATEIMAGEMASK);
                      if (index == INDEXTOSTATEIMAGEMASK(1))
                      {
                          TreeView_SetItemState(tree, ht.hItem, INDEXTOSTATEIMAGEMASK(2), TVIS_STATEIMAGEMASK);
                          addDriver(loadedAudioDrv[tvItem.lParam & 0xff].szDriver);
                          SendMessage(GetParent(hDlg), PSM_CHANGED, (WPARAM) hDlg, 0); /* enable apply button */
                      }
                      else if (index == INDEXTOSTATEIMAGEMASK(2))
                      {
                          TreeView_SetItemState(tree, ht.hItem, INDEXTOSTATEIMAGEMASK(1), TVIS_STATEIMAGEMASK);
                          removeDriver(loadedAudioDrv[tvItem.lParam & 0xff].szDriver);
                          SendMessage(GetParent(hDlg), PSM_CHANGED, (WPARAM) hDlg, 0); /* enable apply button */
                      }
                  }
              }
              break;
            case NM_RCLICK:
              if (((LPNMHDR)lParam)->idFrom == IDC_AUDIO_TREE)
              {
                  TVHITTESTINFO ht;
                  DWORD dwPos = GetMessagePos();
                  HWND tree = ((LPNMHDR)lParam)->hwndFrom;
                  POINT pt;
                  ZeroMemory(&ht, sizeof(ht));
                  pt.x = (short)LOWORD(dwPos);
                  pt.y = (short)HIWORD(dwPos);
                  ht.pt = pt;
                  MapWindowPoints(HWND_DESKTOP, tree, &ht.pt, 1);
                  SendMessageW( tree, TVM_HITTEST, 0, (LPARAM)&ht );
                  if (TVHT_ONITEMLABEL & ht.flags)
                  {
                      TVITEM tvItem;
                      ZeroMemory(&tvItem, sizeof(tvItem));
                      tvItem.hItem = ht.hItem;
                      tvItem.mask = TVIF_PARAM;
                      tvItem.lParam = -1;
                      if (TreeView_GetItem(tree, &tvItem))
                      {
                          if (tvItem.lParam & DRIVER_MASK)
                          {
                              if (hPopupMenus)
                              {
                                  TrackPopupMenu(GetSubMenu(hPopupMenus, 0), TPM_RIGHTBUTTON, pt.x, pt.y, 0, tree, NULL);
                                  toConfigure = tvItem.lParam & ~DRIVER_MASK;
                              }
                          }
                          else if (tvItem.lParam & DEVICE_MASK)
                          {
                              /* FIXME TBD */
                          }

                      }
                  }
              }
	}
	break;

  case WM_INITDIALOG:
    initAudioDlg(hDlg);
    break;
  }

  return FALSE;
}
void CManageBookmarksDialog::ShowViewMenu()
{
	DWORD dwButtonState = static_cast<DWORD>(SendMessage(m_hToolbar,TB_GETSTATE,TOOLBAR_ID_VIEWS,MAKEWORD(TBSTATE_PRESSED,0)));
	SendMessage(m_hToolbar,TB_SETSTATE,TOOLBAR_ID_VIEWS,MAKEWORD(dwButtonState|TBSTATE_PRESSED,0));

	HMENU hMenu = LoadMenu(GetInstance(),MAKEINTRESOURCE(IDR_MANAGEBOOKMARKS_VIEW_MENU));

	UINT uCheck;

	if(m_pmbdps->m_bSortAscending)
	{
		uCheck = IDM_MB_VIEW_SORTASCENDING;
	}
	else
	{
		uCheck = IDM_MB_VIEW_SORTDESCENDING;
	}

	CheckMenuRadioItem(hMenu,IDM_MB_VIEW_SORTASCENDING,IDM_MB_VIEW_SORTDESCENDING,uCheck,MF_BYCOMMAND);

	switch(m_pmbdps->m_SortMode)
	{
	case NBookmarkHelper::SM_NAME:
		uCheck = IDM_MB_VIEW_SORTBYNAME;
		break;

	case NBookmarkHelper::SM_LOCATION:
		uCheck = IDM_MB_VIEW_SORTBYLOCATION;
		break;

	case NBookmarkHelper::SM_VISIT_DATE:
		uCheck = IDM_MB_VIEW_SORTBYVISITDATE;
		break;

	case NBookmarkHelper::SM_VISIT_COUNT:
		uCheck = IDM_MB_VIEW_SORTBYVISITCOUNT;
		break;

	case NBookmarkHelper::SM_ADDED:
		uCheck = IDM_MB_VIEW_SORTBYADDED;
		break;

	case NBookmarkHelper::SM_LAST_MODIFIED:
		uCheck = IDM_MB_VIEW_SORTBYLASTMODIFIED;
		break;
	}

	CheckMenuRadioItem(hMenu,IDM_MB_VIEW_SORTBYNAME,IDM_MB_VIEW_SORTBYLASTMODIFIED,uCheck,MF_BYCOMMAND);

	RECT rcButton;
	SendMessage(m_hToolbar,TB_GETRECT,TOOLBAR_ID_VIEWS,reinterpret_cast<LPARAM>(&rcButton));

	POINT pt;
	pt.x = rcButton.left;
	pt.y = rcButton.bottom;
	ClientToScreen(m_hToolbar,&pt);

	TrackPopupMenu(GetSubMenu(hMenu,0),TPM_LEFTALIGN,pt.x,pt.y,0,m_hDlg,NULL);
	DestroyMenu(hMenu);

	SendMessage(m_hToolbar,TB_SETSTATE,TOOLBAR_ID_VIEWS,MAKEWORD(dwButtonState,0));
}
Ejemplo n.º 23
0
// Process window messages
LRESULT CALLBACK Daemon::WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) {
	// This is a static method, so we don't know which instantiation we're 
	// dealing with. We have stored a pseudo-this in the window user data, 
	// though.
    Daemon *_this = helper::SafeGetWindowUserData<Daemon>(hwnd);

	switch (iMsg) {

	case WM_CREATE:
		{
			return 0;
		}

	case WM_SOCKEVENT:
		{
			assert(HIWORD(lParam) == 0);
			// A new socket created by accept might send messages to
			// this procedure. We can ignore them.
			if(wParam != _this->m_deamon_sock) {
				return 0;
			}

			switch(lParam) {
			case FD_ACCEPT:
				{
					struct sockaddr_in incoming;
					int size_incoming=sizeof(incoming);
					memset(&incoming, 0, sizeof(incoming));


					SOCKET hNewSock;
					hNewSock = accept(_this->m_deamon_sock, (struct sockaddr *)&incoming,&size_incoming);
					WSAAsyncSelect(hNewSock, hwnd, 0, 0);
					unsigned long nbarg = 0;
					ioctlsocket(hNewSock, FIONBIO, &nbarg);
					// Phil Money @ Advantig, LLC 7-9-2005
					if (ListenMode){ 

						pApp->NewConnection(true,hNewSock);

					}else{ 
						closesocket(hNewSock); 
						hNewSock = INVALID_SOCKET;
					} 
					
					break;
				}
			case FD_READ:
				{
					unsigned long numbytes=0;
					ioctlsocket(_this->m_deamon_sock, FIONREAD, &numbytes);
					recv(_this->m_deamon_sock, _this->netbuf, numbytes, 0);
					break;
				}
			case FD_CLOSE:
				vnclog.Print(5, _T("Daemon connection closed\n"));
				DestroyWindow(hwnd);
				break;
			}
			
			return 0;
		}
	case WM_COMMAND:
		switch (LOWORD(wParam)) {
		case ID_NEWCONN:
			pApp->NewConnection(false);
			break;
		case IDC_OPTIONBUTTON:
			pApp->m_options.DoDialog();
			break;
		// Phil Money @ Advantig, LLC 7-9-2005
		case ID_LISTEN_MODE:
			if (GetListenMode()){ 
				SetListenMode(false); 
			}else{ 
				SetListenMode(true); 
			} 
			_this->CheckTrayIcon(); 
			break;
		case ID_CLOSEAPP:
			PostQuitMessage(0);
			//DestroyWindow(hwnd);
			break;
		case ID_CLOSEDAEMON:
			//if (_this->m_sock!=NULL) shutdown(_this->m_sock, SD_BOTH);
			//if (_this->m_sock!=NULL) closesocket(_this->m_sock);
			//_this->m_sock=NULL;
			break;
		case IDD_APP_ABOUT:
			ShowAboutBox();
			break;
		}
		return 0;
	case WM_TRAYNOTIFY:
		{
			HMENU hSubMenu = GetSubMenu(_this->m_hmenu, 0);
			if (lParam==WM_LBUTTONDBLCLK) {
				// double click: execute first menu item
				::SendMessage(_this->m_nid.hWnd, WM_COMMAND, 
					GetMenuItemID(hSubMenu, 0), 0);
			} else if (lParam==WM_RBUTTONUP) {
				if (hSubMenu == NULL) { 
					vnclog.Print(2, _T("No systray submenu\n"));
					return 0;
				}
				// Make first menu item the default (bold font)
				::SetMenuDefaultItem(hSubMenu, 0, TRUE);
				/*if (_this->m_sock==NULL){
					MENUITEMINFO pItem;
					ZeroMemory( &pItem, sizeof(pItem) );
					pItem.cbSize		= sizeof(pItem);
					pItem.fMask			= MIIM_TYPE;
					pItem.fType			= MFT_STRING;
					pItem.dwTypeData	= (LPTSTR)"Deamon closed !!!";

					SetMenuItemInfo( hSubMenu, 5, TRUE, &pItem );
					::SetMenuDefaultItem(hSubMenu, 5, TRUE);
				}*/
				
				// Display the menu at the current mouse location. There's a "bug"
				// (Microsoft calls it a feature) in Windows 95 that requires calling
				// SetForegroundWindow. To find out more, search for Q135788 in MSDN.
				//
				POINT mouse;
				GetCursorPos(&mouse);
				::SetForegroundWindow(_this->m_nid.hWnd);
				::TrackPopupMenu(hSubMenu, 0, mouse.x, mouse.y, 0,
					_this->m_nid.hWnd, NULL);
				
			} 
			return 0;
		}
	case WM_TIMER:
		_this->CheckTrayIcon();
		return 0;
	case WM_DESTROY:
		PostQuitMessage(0);
		return 0;
	}
	
	return DefWindowProc(hwnd, iMsg, wParam, lParam);
}
Ejemplo n.º 24
0
void moduleListRightClick(HWND hwnd, WPARAM wParam, LPARAM lParam) // hwnd here is to the main window, NOT the treview
{
	TVHITTESTINFO hti;
	hti.pt.x = (short)LOWORD(GetMessagePos());
	hti.pt.y = (short)HIWORD(GetMessagePos());
	ScreenToClient(((LPNMHDR)lParam)->hwndFrom, &hti.pt);

	if (TreeView_HitTest(((LPNMHDR)lParam)->hwndFrom, &hti)) {
		if (hti.flags & TVHT_ONITEM) {
			TVITEM tvi = {0};
			HMENU hMenu, hSubMenu;
			int menuNumber;
			char module[256];
			tvi.mask = TVIF_HANDLE | TVIF_PARAM | TVIF_TEXT;
			tvi.hItem = hti.hItem;
			tvi.pszText = module;
			tvi.cchTextMax = 255;
			TreeView_GetItem(((LPNMHDR)lParam)->hwndFrom, &tvi);
			if (tvi.lParam) {
				ModuleTreeInfoStruct *mtis = (ModuleTreeInfoStruct *)tvi.lParam;
				MCONTACT hContact = mtis->hContact;
				GetCursorPos(&hti.pt);
				hMenu = LoadMenu(hInst, MAKEINTRESOURCE(IDR_CONTEXTMENU));
				TranslateMenu(hMenu);
				if (mtis->type == CONTACT && hContact)
					menuNumber = 2;
				else if ((mtis->type == MODULE) && !hContact)
					menuNumber = 1;
				else if (mtis->type == CONTACT && !hContact)
					menuNumber = 3;
				else if (mtis->type == CONTACT_ROOT_ITEM && !hContact)
					menuNumber = 4;
				else if ((mtis->type == MODULE) && hContact)
					menuNumber = 5;
				else return;
				hSubMenu = GetSubMenu(hMenu, menuNumber);

				TranslateMenu(hSubMenu);
				switch (menuNumber) {
				case 1: // null module
				case 5: // contact module
					{
						// check if we r already watching the module
						int i, watching = 0;
						// check if the setting is being watched and if it is then check the menu item
						if (WatchListArray.item)
							for (i = 0; i < WatchListArray.count; i++)
								if (WatchListArray.item[i].module && (hContact == WatchListArray.item[i].hContact)) {
									if (!mir_strcmp(module, WatchListArray.item[i].module) && !WatchListArray.item[i].setting) {
										// yes so uncheck it
										CheckMenuItem(hSubMenu, MENU_WATCH_ITEM, MF_CHECKED | MF_BYCOMMAND);
										watching = 1;
										break;
									}
								}

						switch (TrackPopupMenu(hSubMenu, TPM_RETURNCMD, hti.pt.x, hti.pt.y, 0, hwnd, NULL)) {
						case MENU_RENAME_MOD:
							TreeView_EditLabel(GetDlgItem(hwnd, IDC_MODULES), tvi.hItem);
							break;

						case MENU_DELETE_MOD:
							if (deleteModule(module, hContact, 0)) {
								TreeView_DeleteItem(((LPNMHDR)lParam)->hwndFrom, hti.hItem);
								mir_free(mtis);
							}
							break;

						case MENU_COPY_MOD:
							copyModuleMenuItem(module, hContact);
							break;

							////////////////////////////////////////////////////////////////////// divider
						case MENU_WATCH_ITEM:
							if (!watching)
								addSettingToWatchList(hContact, module, 0);
							else
								freeWatchListItem(i);
							if (hwnd2watchedVarsWindow)
								PopulateWatchedWindow(GetDlgItem(hwnd2watchedVarsWindow, IDC_VARS));
							break;

						case MENU_EXPORTMODULE:
							exportDB(hContact, module);
							break;

						case MENU_EXPORTDB:
							exportDB(INVALID_CONTACT_ID, module);
							break;
						}
					}
					break;

				case 2: // contact
					switch (TrackPopupMenu(hSubMenu, TPM_RETURNCMD, hti.pt.x, hti.pt.y, 0, hwnd, NULL)) {
					case MENU_CLONE_CONTACT:
						if (CloneContact(hContact))
							refreshTree(1);
						break;

					case MENU_DELETE_CONTACT:
						if (db_get_b(NULL, "CList", "ConfirmDelete", 1)) {
							char msg[1024];
							mir_snprintf(msg, SIZEOF(msg), Translate("Are you sure you want to delete contact \"%s\"?"), module);
							if (MessageBox(0, msg, Translate("Confirm contact delete"), MB_YESNO | MB_ICONEXCLAMATION) == IDYES) {
								CallService(MS_DB_CONTACT_DELETE, hContact, 0);
								freeTree(((LPNMHDR)lParam)->hwndFrom, hContact);
								TreeView_DeleteItem(((LPNMHDR)lParam)->hwndFrom, tvi.hItem);
							}
						}
						else {
							CallService(MS_DB_CONTACT_DELETE, hContact, 0);
							freeTree(((LPNMHDR)lParam)->hwndFrom, hContact);
							TreeView_DeleteItem(((LPNMHDR)lParam)->hwndFrom, tvi.hItem);
						}
						break;

					////////////////////////////////////////////////////////////////////// divider
					case MENU_EXPORTCONTACT:
						exportDB(hContact, 0);
						break;
					case MENU_IMPORTFROMTEXT:
						ImportSettingsMenuItem(hContact);
						break;
					case MENU_IMPORTFROMFILE:
						ImportSettingsFromFileMenuItem(hContact, "");
						break;

					////////////////////////////////////////////////////////////////////// divider
					case MENU_ADD_MODULE:
						{
							HWND AddModhwnd = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_ADD_MODULE), hwnd, AddModDlgProc, hContact);
							char msg[1024];
							mir_snprintf(msg, SIZEOF(msg), Translate("Add module to contact \"%s\""), module);
							SetWindowText(AddModhwnd, module);
						}
						break;
					}
					break;

				case 3: // NULL contact
					switch (TrackPopupMenu(hSubMenu, TPM_RETURNCMD, hti.pt.x, hti.pt.y, 0, hwnd, NULL)) {
					case MENU_ADD_MODULE:
						{
							HWND AddModhwnd = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_ADD_MODULE), hwnd, AddModDlgProc, hContact);
							char msg[1024];
							mir_snprintf(msg, SIZEOF(msg), Translate("Add module to contact \"%s\""), module);
							SetWindowText(AddModhwnd, module);
						}
						break;
					case MENU_EXPORTCONTACT:
						exportDB(NULL, 0);
						break;
					case MENU_IMPORTFROMTEXT:
						ImportSettingsMenuItem(NULL);
						break;
					case MENU_IMPORTFROMFILE:
						ImportSettingsFromFileMenuItem(NULL, "");
						break;
					}
					break;

				case 4: // Contacts root
					switch (TrackPopupMenu(hSubMenu, TPM_RETURNCMD, hti.pt.x, hti.pt.y, 0, hwnd, NULL)) {
					case MENU_EXPORTCONTACT:
						exportDB(INVALID_CONTACT_ID, "");
						break;
					case MENU_IMPORTFROMTEXT:
						ImportSettingsMenuItem(NULL);
						break;
					case MENU_IMPORTFROMFILE:
						ImportSettingsFromFileMenuItem(NULL, "");
						break;
					}
					break;
				}
				DestroyMenu(hMenu);
			}
		}
	}
}
Ejemplo n.º 25
0
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	HDC hdc, hmem;
	static HDC offscreen;
	PAINTSTRUCT ps;
	RECT rect, rect2;
	BITMAP bm;
	POINT point;
	static POINT start;
	static int dragging = 0;
	HDC desktop;
	HBITMAP hbitmap;
	HANDLE hdrop;
	HFONT dfltFont;
	int dfltBGMode;
	double percomp;

	switch (message)
	{
		case WM_CREATE:
			menu = LoadMenu(hinst, MAKEINTRESOURCE(IDR_MENU1));
			menu = GetSubMenu(menu, 0);

			offscreen = CreateCompatibleDC(NULL);
			desktop = GetDC(GetDesktopWindow());
			hbitmap = CreateCompatibleBitmap(desktop, 200, 200);
			ReleaseDC(GetDesktopWindow(), desktop);
			SelectObject(offscreen, hbitmap);

			// Start the engines
			decthread_init();

			// We accept drag&drop
			DragAcceptFiles(hwnd, TRUE);
			return 0;

		case WM_PAINT:
			hdc = BeginPaint(hwnd, &ps);
			GetClientRect(hwnd, &rect);
			width = rect.right + 1;
			height = rect.bottom + 1;

			FillRect(offscreen, &rect, (HBRUSH)GetStockObject(WHITE_BRUSH));
			DrawText(offscreen, "Drop Files Here", -1, &rect, DT_SINGLELINE | DT_CENTER);
			SetRect(&rect2, 0, height - 110, width, height - 25);
			DrawText(offscreen, "For Decoding", -1, &rect2, DT_SINGLELINE | DT_CENTER);

			hmem = CreateCompatibleDC(offscreen);
			SelectObject(hmem, hbm[frame]);
			GetObject(hbm[frame], sizeof(BITMAP), &bm);
			BitBlt(offscreen, width / 2 - 33, height / 2 - 31, bm.bmWidth, bm.bmHeight, hmem, 0, 0, SRCCOPY);
			DeleteDC(hmem);

			percomp = ((double)(totalfiles - numfiles) + 1 - (1 - file_complete)) / (double)totalfiles;

			SetRect(&vbrBR, 0, height - 35, width, height - 19);

			dfltBGMode = SetBkMode(offscreen, TRANSPARENT);
			dfltFont = SelectObject(offscreen, font2);

			SetRect(&bar1, 0, height - 23, (int)(file_complete * width), height - 13);
			SetRect(&bar2, 0, height - 12, (int)(percomp * width), height - 2);

			FillRect(offscreen, &bar1, (HBRUSH)GetStockObject(LTGRAY_BRUSH));
			FillRect(offscreen, &bar2, (HBRUSH)GetStockObject(DKGRAY_BRUSH));

			if (fileName)
			{
				char* sep;
				char  fileCaption[80];

				if ((sep = strrchr(fileName, '\\')) != 0)
					fileName = sep+1;

				(void) strcpy(fileCaption, "   ");
				(void) strcat(fileCaption, fileName);

				DrawText(offscreen, fileCaption, -1, &bar1, DT_SINGLELINE | DT_LEFT);
			}

			SelectObject(offscreen, dfltFont);
			SetBkMode(offscreen, dfltBGMode);

			BitBlt(hdc, 0, 0, width, height, offscreen, 0, 0, SRCCOPY);

			EndPaint(hwnd, &ps);

			return DefWindowProc(hwnd, message, wParam, lParam);
			//return 0;

		case WM_TIMER:
			if (animate || frame)
			{
				frame++;
				if (frame > 7) 
					frame -= 8;
			}
			else
			{
				frame = 0;
			}
			GetClientRect(hwnd, &rect);
			InvalidateRect(hwnd, &rect, FALSE);
			return 0;

		case WM_LBUTTONDOWN:
			start.x = LOWORD(lParam);
			start.y = HIWORD(lParam);
			ClientToScreen(hwnd, &start);
			GetWindowRect(hwnd, &rect);
			start.x -= rect.left;
			start.y -= rect.top;
			dragging = 1;
			SetCapture(hwnd);
			return 0;

		case WM_LBUTTONUP:
			if (dragging)
			{
				dragging = 0;
				ReleaseCapture();
			}
			return 0;

		case WM_MOUSEMOVE:
			if (dragging)
			{
				point.x = LOSHORT(lParam);
				point.y = HISHORT(lParam);

				/* lParam can contain negative coordinates !
				 * point.x = LOWORD(lParam);
				 * point.y = HIWORD(lParam);
				 */

				ClientToScreen(hwnd, &point);
				SetWindowPos(hwnd, 0, point.x - start.x, point.y - start.y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW);
				iniSettings.window_x = point.x - start.x;
				iniSettings.window_y = point.y - start.y;
			}
			return 0;

		case WM_CAPTURECHANGED:
			if (dragging)
			{
				dragging = 0;
				ReleaseCapture();
			}
			return 0;

		case WM_RBUTTONUP:
			point.x = LOWORD(lParam);
			point.y = HIWORD(lParam);
			ClientToScreen(hwnd, &point);
			TrackPopupMenu(menu, TPM_RIGHTBUTTON, point.x, point.y, 0, hwnd, NULL);
			return 0;

		case WM_COMMAND:
			switch (LOWORD(wParam)) 
			{
				case IDM_QUIT:
					WriteIniFile(INI_FILE);
					decoding_done = 1;
					PostQuitMessage(0);
					break;
				case IDM_ONTOP:
					set_always_on_top(hwnd, ~GetMenuState(menu, LOWORD(wParam), MF_BYCOMMAND) & MF_CHECKED);
					break;	
				case IDM_LOGERR:
					set_logerr(hwnd, ~GetMenuState(menu, LOWORD(wParam), MF_BYCOMMAND) & MF_CHECKED);
					break;
				case IDM_STOP_DEC:
				{
					int v = ~GetMenuState(menu, LOWORD(wParam), MF_BYCOMMAND) & MF_CHECKED;
					if(v == 8)
						stop_decoding = 1;
					break;
				}
				case IDM_VOLUME:
				{
					int value = 
					DialogBox(
					hinst,  
					MAKEINTRESOURCE(IDD_VOLUME),   
					hwnd, QCProc);

					if (value == -2)
						break;
					break;
				}
				case IDM_ABOUT:
				{
					int value = DialogBox(hinst, MAKEINTRESOURCE(IDD_ABOUT), hwnd, QCProc);
					if (value == -7)
						break;
					break;
				}

			} // LOWORD(wParam)
			return 0;

		case WM_DROPFILES:
			hdrop = (HANDLE)wParam;
			HandleDrag(hwnd, hdrop);
			return 0;
	
		case WM_DESTROY:
			decoding_done = 1;
			PostQuitMessage(0);
			return 0;
	}

	return DefWindowProc(hwnd, message, wParam, lParam);
}
Ejemplo n.º 26
0
// Process window messages
LRESULT CALLBACK vncMenu::WndProc(HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam)
{
	// This is a static method, so we don't know which instantiation we're 
	// dealing with. We use Allen Hadden's ([email protected]) suggestion 
	// from a newsgroup to get the pseudo-this.
     vncMenu *_this = helper::SafeGetWindowUserData<vncMenu>(hwnd);
	//	Beep(100,10);
	//	vnclog.Print(LL_INTINFO, VNCLOG("iMsg 0x%x \n"),iMsg);

	 if (iMsg==WM_TASKBARCREATED)
	 {
		 if (_this->m_server->RunningFromExternalService())
			{
				Sleep(1000);
				vnclog.Print(LL_INTINFO,
				VNCLOG("WM_TASKBARCREATED \n"));
				// User has changed!
				strcpy(_this->m_username, newuser);
				vnclog.Print(LL_INTINFO,
				VNCLOG("############## Kill vncMenu thread\n"));
				// Order impersonation thread killing
				KillTimer(hwnd,1);
				PostQuitMessage(0);
			}
	 }

	switch (iMsg)
	{

	// Every five seconds, a timer message causes the icon to update
	case WM_TIMER:
		// sf@2007 - Can't get the WTS_CONSOLE_CONNECT message work properly for now..
		// So use a hack instead
        // jdp reread some ini settings
        _this->m_properties.ReloadDynamicSettings();

		// G_1111==true --> reconnect
		if (G_1111==true)
		{
			if (_this->IsIconSet==true)
			{
				vnclog.Print(LL_INTERR, VNCLOG("Add client reconnect from timer\n"));
				G_1111=false;
				PostMessage(hwnd,MENU_ADD_CLIENT_MSG,1111,1111);
			}
		}


		vnclog.Print(LL_INTERR, VNCLOG("########### vncMenu::TIMER TrayIcon 5s hack\n"));

		if (_this->m_server->RunningFromExternalService())
			{
				strcpy(newuser,"");
				if (vncService::CurrentUser((char *) &newuser, sizeof(newuser)))
				{
					// Check whether the user name has changed!
					if (_stricmp(newuser, _this->m_username) != 0 || _this->IconFaultCounter>2)
					{
						Sleep(1000);
						vnclog.Print(LL_INTINFO,
						VNCLOG("user name has changed\n"));
						// User has changed!
						strcpy(_this->m_username, newuser);
						vnclog.Print(LL_INTINFO,
						VNCLOG("############## Kill vncMenu thread\n"));
						// Order impersonation thread killing
						PostQuitMessage(0);
						break;
					}
				}
			}

		// *** HACK for running servicified
		if (vncService::RunningAsService())
			{
				vnclog.Print(LL_INTERR, VNCLOG("########### vncMenu::TIMER TrayIcon 5s hack call - Runningasservice\n"));
				// Attempt to add the icon if it's not already there
				_this->AddTrayIcon();
				// Trigger a check of the current user
				PostMessage(hwnd, WM_USERCHANGED, 0, 0);
			}
		// Update the icon
		_this->FlashTrayIcon(_this->m_server->AuthClientCount() != 0);
		break;

		// DEAL WITH NOTIFICATIONS FROM THE SERVER:
	case WM_SRV_CLIENT_AUTHENTICATED:
	case WM_SRV_CLIENT_DISCONNECT:
		// Adjust the icon accordingly
		_this->FlashTrayIcon(_this->m_server->AuthClientCount() != 0);

		if (_this->m_server->AuthClientCount() != 0) {
			if (_this->m_server->RemoveWallpaperEnabled())
				KillWallpaper();
			if (_this->m_server->RemoveAeroEnabled()) // Moved, redundant if //PGM @ Advantig
				DisableAero(); // Moved, redundant if //PGM @ Advantig
		} else {
			if (_this->m_server->RemoveAeroEnabled()) // Moved, redundant if //PGM @ Advantig
				ResetAero(); // Moved, redundant if //PGM @ Advantig
			if (_this->m_server->RemoveWallpaperEnabled()) { // Added { //PGM @ Advantig
				Sleep(2000); // Added 2 second delay to help wallpaper restore //PGM @ Advantig
				RestoreWallpaper();
			} //PGM @ Advantig
		}
//PGM @ Advantig		if (_this->m_server->AuthClientCount() != 0) {
//PGM @ Advantig			if (_this->m_server->RemoveAeroEnabled())
//PGM @ Advantig				DisableAero();
//PGM @ Advantig		} else {
//PGM @ Advantig			if (_this->m_server->RemoveAeroEnabled())
//PGM @ Advantig				ResetAero();
//PGM @ Advantig		}
		return 0;

		// STANDARD MESSAGE HANDLING
	case WM_CREATE:
		WM_TASKBARCREATED = RegisterWindowMessage("TaskbarCreated");
		return 0;

	case WM_COMMAND:
		// User has clicked an item on the tray menu
		switch (LOWORD(wParam))
		{
		case ID_DEFAULT_PROPERTIES:
			// Show the default properties dialog, unless it is already displayed
			vnclog.Print(LL_INTINFO, VNCLOG("show default properties requested\n"));
			_this->m_properties.ShowAdmin(TRUE, FALSE);
			_this->FlashTrayIcon(_this->m_server->AuthClientCount() != 0);
			break;
		
		case ID_PROPERTIES:
			// Show the properties dialog, unless it is already displayed
			vnclog.Print(LL_INTINFO, VNCLOG("show user properties requested\n"));
			_this->m_propertiesPoll.Show(TRUE, TRUE);
			_this->FlashTrayIcon(_this->m_server->AuthClientCount() != 0);
			break;

        case ID_ADMIN_PROPERTIES:
			// Show the properties dialog, unless it is already displayed
			vnclog.Print(LL_INTINFO, VNCLOG("show user properties requested\n"));
			_this->m_properties.ShowAdmin(TRUE, TRUE);
			_this->FlashTrayIcon(_this->m_server->AuthClientCount() != 0);
			break;
		
		case ID_OUTGOING_CONN:
			// Connect out to a listening VNC viewer
			{
				vncConnDialog *newconn = new vncConnDialog(_this->m_server);
				if (newconn)
				{
					newconn->DoDialog();
					// delete newconn; // NO ! Already done in vncConnDialog.
				}
			}
			break;

		case ID_KILLCLIENTS:
			// Disconnect all currently connected clients
			vnclog.Print(LL_INTINFO, VNCLOG("KillAuthClients() ID_KILLCLIENTS \n"));
			_this->m_server->KillAuthClients();
			break;

		// sf@2002
		case ID_LISTCLIENTS:
			_this->m_ListDlg.Display();
			break;

		case ID_ABOUT:
			// Show the About box
			_this->m_about.Show(TRUE);
			break;

		case ID_VISITUSONLINE_HOMEPAGE:
			{
						HANDLE hProcess,hPToken;
						DWORD id=GetExplorerLogonPid();
						if (id!=0) 
						{
							hProcess = OpenProcess(MAXIMUM_ALLOWED,FALSE,id);
							if(!OpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY
													|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|TOKEN_ADJUST_SESSIONID
													|TOKEN_READ|TOKEN_WRITE,&hPToken)) break;

							char dir[MAX_PATH];
							char exe_file_name[MAX_PATH];
							GetModuleFileName(0, exe_file_name, MAX_PATH);
							strcpy(dir, exe_file_name);
							strcat(dir, " -openhomepage");
				
							{
								STARTUPINFO          StartUPInfo;
								PROCESS_INFORMATION  ProcessInfo;
								ZeroMemory(&StartUPInfo,sizeof(STARTUPINFO));
								ZeroMemory(&ProcessInfo,sizeof(PROCESS_INFORMATION));
								StartUPInfo.wShowWindow = SW_SHOW;
								StartUPInfo.lpDesktop = "Winsta0\\Default";
								StartUPInfo.cb = sizeof(STARTUPINFO);
						
								CreateProcessAsUser(hPToken,NULL,dir,NULL,NULL,FALSE,DETACHED_PROCESS,NULL,NULL,&StartUPInfo,&ProcessInfo);
								DWORD error=GetLastError();
                                if (ProcessInfo.hThread) CloseHandle(ProcessInfo.hThread);
                                if (ProcessInfo.hProcess) CloseHandle(ProcessInfo.hProcess);
								//if (error==1314)
								//	{
								//		Open_homepage();
								//	}

							}
						}
			}
			break;

		case ID_VISITUSONLINE_FORUM:
			{
						HANDLE hProcess,hPToken;
						DWORD id=GetExplorerLogonPid();
						if (id!=0) 
						{
							hProcess = OpenProcess(MAXIMUM_ALLOWED,FALSE,id);
							if(!OpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY
													|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|TOKEN_ADJUST_SESSIONID
													|TOKEN_READ|TOKEN_WRITE,&hPToken)) break;

							char dir[MAX_PATH];
							char exe_file_name[MAX_PATH];
							GetModuleFileName(0, exe_file_name, MAX_PATH);
							strcpy(dir, exe_file_name);
							strcat(dir, " -openforum");
				
							{
								STARTUPINFO          StartUPInfo;
								PROCESS_INFORMATION  ProcessInfo;
								ZeroMemory(&StartUPInfo,sizeof(STARTUPINFO));
								ZeroMemory(&ProcessInfo,sizeof(PROCESS_INFORMATION));
								StartUPInfo.wShowWindow = SW_SHOW;
								StartUPInfo.lpDesktop = "Winsta0\\Default";
								StartUPInfo.cb = sizeof(STARTUPINFO);
						
								CreateProcessAsUser(hPToken,NULL,dir,NULL,NULL,FALSE,DETACHED_PROCESS,NULL,NULL,&StartUPInfo,&ProcessInfo);
								DWORD error=GetLastError();
                                if (ProcessInfo.hThread) CloseHandle(ProcessInfo.hThread);
                                if (ProcessInfo.hProcess) CloseHandle(ProcessInfo.hProcess);
								//if (error==1314)
								//	{
								//		Open_forum();
								//	}

							}
						}
			}
			break;

		case ID_CLOSE:
			// User selected Close from the tray menu
			fShutdownOrdered=TRUE;
			Sleep(1000);
			vnclog.Print(LL_INTINFO, VNCLOG("KillAuthClients() ID_CLOSE \n"));
			_this->m_server->KillAuthClients();
			PostMessage(hwnd, WM_CLOSE, 0, 0);
			break;
		case ID_UNINSTALL_SERVICE:
			{
			HANDLE hProcess,hPToken;
			DWORD id=GetExplorerLogonPid();
				if (id!=0) 
				{
					hProcess = OpenProcess(MAXIMUM_ALLOWED,FALSE,id);
					if(!OpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY
											|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|TOKEN_ADJUST_SESSIONID
											|TOKEN_READ|TOKEN_WRITE,&hPToken)) break;

					char dir[MAX_PATH];
					char exe_file_name[MAX_PATH];
					GetModuleFileName(0, exe_file_name, MAX_PATH);
					strcpy(dir, exe_file_name);
					strcat(dir, " -uninstallhelper");
		
					{
					STARTUPINFO          StartUPInfo;
					PROCESS_INFORMATION  ProcessInfo;
					HANDLE Token=NULL;
					HANDLE process=NULL;
					ZeroMemory(&StartUPInfo,sizeof(STARTUPINFO));
					ZeroMemory(&ProcessInfo,sizeof(PROCESS_INFORMATION));
					StartUPInfo.wShowWindow = SW_SHOW;
					StartUPInfo.lpDesktop = "Winsta0\\Default";
					StartUPInfo.cb = sizeof(STARTUPINFO);
			
					CreateProcessAsUser(hPToken,NULL,dir,NULL,NULL,FALSE,DETACHED_PROCESS,NULL,NULL,&StartUPInfo,&ProcessInfo);
					DWORD errorcode=GetLastError();
					if (process) CloseHandle(process);
					if (Token) CloseHandle(Token);
					if (errorcode==1314)
					{
						Set_uninstall_service_as_admin();
					}

					}
					fShutdownOrdered=TRUE;
					vnclog.Print(LL_INTINFO, VNCLOG("KillAuthClients() ID_CLOSE \n"));
					_this->m_server->KillAuthClients();					
					PostMessage(hwnd, WM_CLOSE, 0, 0);
				}
			}
			break;
		case ID_RUNASSERVICE:
			{
			HANDLE hProcess,hPToken;
			DWORD id=GetExplorerLogonPid();
				if (id!=0) 
				{
					hProcess = OpenProcess(MAXIMUM_ALLOWED,FALSE,id);
					if(!OpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY
											|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|TOKEN_ADJUST_SESSIONID
											|TOKEN_READ|TOKEN_WRITE,&hPToken)) break;

					char dir[MAX_PATH];
					char exe_file_name[MAX_PATH];
					GetModuleFileName(0, exe_file_name, MAX_PATH);
					strcpy(dir, exe_file_name);
					strcat(dir, " -installhelper");
		

					STARTUPINFO          StartUPInfo;
					PROCESS_INFORMATION  ProcessInfo;
					HANDLE Token=NULL;
					HANDLE process=NULL;
					ZeroMemory(&StartUPInfo,sizeof(STARTUPINFO));
					ZeroMemory(&ProcessInfo,sizeof(PROCESS_INFORMATION));
					StartUPInfo.wShowWindow = SW_SHOW;
					StartUPInfo.lpDesktop = "Winsta0\\Default";
					StartUPInfo.cb = sizeof(STARTUPINFO);
			
					CreateProcessAsUser(hPToken,NULL,dir,NULL,NULL,FALSE,DETACHED_PROCESS,NULL,NULL,&StartUPInfo,&ProcessInfo);
					DWORD error=GetLastError();
					if (process) CloseHandle(process);
					if (Token) CloseHandle(Token);
					if (error==1314)
					{
						Set_install_service_as_admin();
					}
				}
			fShutdownOrdered=TRUE;
			Sleep(1000);
			vnclog.Print(LL_INTINFO, VNCLOG("KillAuthClients() ID_CLOSE \n"));
			_this->m_server->KillAuthClients();
			PostMessage(hwnd, WM_CLOSE, 0, 0);
			}
			break;
		case ID_CLOSE_SERVICE:
			{
			HANDLE hProcess,hPToken;
			DWORD id=GetExplorerLogonPid();
				if (id!=0) 
				{
					hProcess = OpenProcess(MAXIMUM_ALLOWED,FALSE,id);
					if(!OpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY
											|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|TOKEN_ADJUST_SESSIONID
											|TOKEN_READ|TOKEN_WRITE,&hPToken))
					{
						CloseHandle(hProcess);
						break;
					}

					char dir[MAX_PATH];
					char exe_file_name[MAX_PATH];
					GetModuleFileName(0, exe_file_name, MAX_PATH);
					strcpy(dir, exe_file_name);
					strcat(dir, " -stopservicehelper");
		

					STARTUPINFO          StartUPInfo;
					PROCESS_INFORMATION  ProcessInfo;
					HANDLE Token=NULL;
					HANDLE process=NULL;
					ZeroMemory(&StartUPInfo,sizeof(STARTUPINFO));
					ZeroMemory(&ProcessInfo,sizeof(PROCESS_INFORMATION));
					StartUPInfo.wShowWindow = SW_SHOW;
					StartUPInfo.lpDesktop = "Winsta0\\Default";
					StartUPInfo.cb = sizeof(STARTUPINFO);
			
					CreateProcessAsUser(hPToken,NULL,dir,NULL,NULL,FALSE,DETACHED_PROCESS,NULL,NULL,&StartUPInfo,&ProcessInfo);
					DWORD error=GetLastError();
					if (process) CloseHandle(process);
					if (Token) CloseHandle(Token);
					if (hProcess) CloseHandle(hProcess);
					if (error==1314)
					{
						Set_stop_service_as_admin();
					}
				}
			}
			break;
		case ID_START_SERVICE:
			{
			HANDLE hProcess,hPToken;
			DWORD id=GetExplorerLogonPid();
				if (id!=0) 
				{
					hProcess = OpenProcess(MAXIMUM_ALLOWED,FALSE,id);
					if(!OpenProcessToken(hProcess,TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY
											|TOKEN_DUPLICATE|TOKEN_ASSIGN_PRIMARY|TOKEN_ADJUST_SESSIONID
											|TOKEN_READ|TOKEN_WRITE,&hPToken))
					{
						CloseHandle(hProcess);
						break;
					}

					char dir[MAX_PATH];
					char exe_file_name[MAX_PATH];
					GetModuleFileName(0, exe_file_name, MAX_PATH);
					strcpy(dir, exe_file_name);
					strcat(dir, " -startservicehelper");
		

					STARTUPINFO          StartUPInfo;
					PROCESS_INFORMATION  ProcessInfo;
					HANDLE Token=NULL;
					HANDLE process=NULL;
					ZeroMemory(&StartUPInfo,sizeof(STARTUPINFO));
					ZeroMemory(&ProcessInfo,sizeof(PROCESS_INFORMATION));
					StartUPInfo.wShowWindow = SW_SHOW;
					StartUPInfo.lpDesktop = "Winsta0\\Default";
					StartUPInfo.cb = sizeof(STARTUPINFO);
			
					CreateProcessAsUser(hPToken,NULL,dir,NULL,NULL,FALSE,DETACHED_PROCESS,NULL,NULL,&StartUPInfo,&ProcessInfo);
					DWORD error=GetLastError();
					if (hPToken) CloseHandle(hPToken);
					if (process) CloseHandle(process);
					if (Token) CloseHandle(Token);
					if (hProcess) CloseHandle(hProcess);
					if (error==1314)
					{
						Set_start_service_as_admin();
					}
					fShutdownOrdered=TRUE;
					Sleep(1000);
					vnclog.Print(LL_INTINFO, VNCLOG("KillAuthClients() ID_CLOSE \n"));
					_this->m_server->KillAuthClients();
					PostMessage(hwnd, WM_CLOSE, 0, 0);
				}
			}
			break;

		}
		return 0;

	case WM_TRAYNOTIFY:
		// User has clicked on the tray icon or the menu
		{
			// Get the submenu to use as a pop-up menu
			HMENU submenu = GetSubMenu(_this->m_hmenu, 0);

			// What event are we responding to, RMB click?
			if (lParam==WM_RBUTTONUP)
			{
				if (submenu == NULL)
				{ 
					vnclog.Print(LL_INTERR, VNCLOG("no submenu available\n"));
					return 0;
				}

				// Make the first menu item the default (bold font)
				SetMenuDefaultItem(submenu, 0, TRUE);
				
				// Get the current cursor position, to display the menu at
				POINT mouse;
				GetCursorPos(&mouse);

				// There's a "bug"
				// (Microsoft calls it a feature) in Windows 95 that requires calling
				// SetForegroundWindow. To find out more, search for Q135788 in MSDN.
				//
				SetForegroundWindow(_this->m_nid.hWnd);

				// Display the menu at the desired position
				TrackPopupMenu(submenu,
						0, mouse.x, mouse.y, 0,
						_this->m_nid.hWnd, NULL);

                PostMessage(hwnd, WM_NULL, 0, 0);

				return 0;
			}
			
			// Or was there a LMB double click?
			if (lParam==WM_LBUTTONDBLCLK)
			{
				// double click: execute first menu item
				SendMessage(_this->m_nid.hWnd,
							WM_COMMAND, 
							GetMenuItemID(submenu, 0),
							0);
			}

			return 0;
		}
		
	case WM_CLOSE:
		
		// Only accept WM_CLOSE if the logged on user has AllowShutdown set
		if (!_this->m_properties.AllowShutdown())
		{
			return 0;
		}
		// tnatsni Wallpaper fix
		if (_this->m_server->RemoveWallpaperEnabled())
			RestoreWallpaper();
		if (_this->m_server->RemoveAeroEnabled())
			ResetAero();

		vnclog.Print(LL_INTERR, VNCLOG("vncMenu WM_CLOSE call - All cleanup done\n"));
		Sleep(2000);
		DestroyWindow(hwnd);
		break;
		
	case WM_DESTROY:
		// The user wants WinVNC to quit cleanly...
		vnclog.Print(LL_INTINFO, VNCLOG("quitting from WM_DESTROY\n"));
		PostQuitMessage(0);
		return 0;
		
	case WM_QUERYENDSESSION:
		{
			//shutdown or reboot
			if((lParam & ENDSESSION_LOGOFF) != ENDSESSION_LOGOFF)
			{
				fShutdownOrdered=TRUE;
				Sleep(1000);
				vnclog.Print(LL_INTERR, VNCLOG("SHUTDOWN OS detected\n"));
				vnclog.Print(LL_INTINFO, VNCLOG("KillAuthClients() ID_CLOSE \n"));
				_this->m_server->KillAuthClients();				
				PostMessage(hwnd, WM_CLOSE, 0, 0);
				break;
			}


			DWORD SessionID;
			SessionID=GetCurrentSessionID();
			vnclog.Print(LL_INTERR, VNCLOG("Session ID %i\n"),SessionID);
			if (SessionID!=0)
			{
				fShutdownOrdered=TRUE;
				Sleep(1000);
				vnclog.Print(LL_INTERR, VNCLOG("WM_QUERYENDSESSION session!=0\n"));
				vnclog.Print(LL_INTINFO, VNCLOG("KillAuthClients() ID_CLOSE \n"));
				_this->m_server->KillAuthClients();				
				PostMessage(hwnd, WM_CLOSE, 0, 0);
			}
		}	
		break;
		
	case WM_ENDSESSION:
		vnclog.Print(LL_INTERR, VNCLOG("WM_ENDSESSION\n"));
		break;

	case WM_USERCHANGED:
		// The current user may have changed.
		{
			strcpy(newuser,"");

			if (vncService::CurrentUser((char *) &newuser, sizeof(newuser)))
			{
				vnclog.Print(LL_INTINFO,
					VNCLOG("############### Usernames change: old=\"%s\", new=\"%s\"\n"),
					_this->m_username, newuser);

				// Check whether the user name has changed!
				if (_stricmp(newuser, _this->m_username) != 0)
				{
					vnclog.Print(LL_INTINFO,
						VNCLOG("user name has changed\n"));

					// User has changed!
					strcpy(_this->m_username, newuser);

					// Redraw the tray icon and set it's state
					_this->DelTrayIcon();
					_this->AddTrayIcon();
					_this->FlashTrayIcon(_this->m_server->AuthClientCount() != 0);
					// We should load in the prefs for the new user
					if (_this->m_properties.m_fUseRegistry)
					{
						_this->m_properties.Load(TRUE);
						_this->m_propertiesPoll.Load(TRUE);
					}
					else
					{
						_this->m_properties.LoadFromIniFile();
						_this->m_propertiesPoll.LoadFromIniFile();
					}
				}
			}
		}
		return 0;

	// [v1.0.2-jp1 fix] Don't show IME toolbar on right click menu.
	case WM_INITMENU:
	case WM_INITMENUPOPUP:
		SendMessage(ImmGetDefaultIMEWnd(hwnd), WM_IME_CONTROL, IMC_CLOSESTATUSWINDOW, 0);
		return 0;

	default:
		// Deal with any of our custom message types		
		// wa@2005 -- added support for the AutoReconnectId
		// removed the previous code that used 999,999
		if ( iMsg == MENU_AUTO_RECONNECT_MSG )
		{
			char szId[MAX_PATH] = {0};
			UINT ret = 0;
			if ( lParam != NULL )
			{
				ret = GlobalGetAtomName( (ATOM)lParam, szId, sizeof( szId ) );
				GlobalDeleteAtom( (ATOM)lParam );
			}
			
			_this->m_server->AutoReconnect(true);
			
			if ( ret > 0 )
				_this->m_server->AutoReconnectId(szId);
			
			return 0;
		}
		if ( iMsg == MENU_REPEATER_ID_MSG )
 		{
			char szId[MAX_PATH] = {0};
			UINT ret = 0;
			if ( lParam != NULL )
			{
				ret = GlobalGetAtomName( (ATOM)lParam, szId, sizeof( szId ) );
				GlobalDeleteAtom( (ATOM)lParam );
			}
			_this->m_server->IdReconnect(true);
			
			if ( ret > 0 )
				_this->m_server->AutoReconnectId(szId);
			
			return 0;
		}


		if (iMsg == MENU_ADD_CLIENT_MSG)
		{
			/*
			// sf@2005 - FTNoUserImpersonation
			// Dirty trick to avoid to add a new MSG... no time
			if (lParam == 998)
			{
				_this->m_server->FTUserImpersonation(false);
				return 0;
			}
			*/

			// Add Client message.  This message includes an IP address
			// of a listening client, to which we should connect.

			//adzm 2009-06-20 - Check for special add repeater client message
			if (wParam == 0xFFFFFFFF && lParam == 0xFFFFFFFF) {
				vncConnDialog *newconn = new vncConnDialog(_this->m_server);
				if (newconn)
				{
					if (IDOK != newconn->DoDialog()) {
						if (SPECIAL_SC_PROMPT && _this->m_server->AuthClientCount() == 0 && _this->m_server->UnauthClientCount() == 0) {
							PostMessage(hwnd, WM_COMMAND, ID_CLOSE, 0);
						}
					}
				}
				return 0;
			}

			// If there is no IP address then show the connection dialog
			if (!lParam) {
				vncConnDialog *newconn = new vncConnDialog(_this->m_server);
				if (newconn)
				{
					newconn->DoDialog();
					// winvnc -connect fixed
					//CHECH memeory leak
					//			delete newconn;
				}
				return 0;
			}

			unsigned short nport = 0;
			char *nameDup = 0;
			char szAdrName[64];
			char szId[MAX_PATH] = {0};
			// sf@2003 - Values are already converted
			if ((_this->m_server->AutoReconnect()|| _this->m_server->IdReconnect() )&& strlen(_this->m_server->AutoReconnectAdr()) > 0)
			{
				nport = _this->m_server->AutoReconnectPort();
				strcpy(szAdrName, _this->m_server->AutoReconnectAdr());
			}
			else
			{
				// Get the IP address stringified
				struct in_addr address;
				address.S_un.S_addr = lParam;
				char *name = inet_ntoa(address);
				if (name == 0)
					return 0;
				nameDup = _strdup(name);
				if (nameDup == 0)
					return 0;
				strcpy(szAdrName, nameDup);
				// Free the duplicate name
				if (nameDup != 0) free(nameDup);

				// Get the port number
				nport = (unsigned short)wParam;
				if (nport == 0)
					nport = INCOMING_PORT_OFFSET;
				
			}

			// wa@2005 -- added support for the AutoReconnectId
			// (but it's not required)
			bool bId = ( strlen(_this->m_server->AutoReconnectId() ) > 0);
			if ( bId )
				strcpy( szId, _this->m_server->AutoReconnectId() );
			
			// sf@2003
			// Stores the client adr/ports the first time we try to connect
			// This way we can call this message again later to reconnect with the same values
			if ((_this->m_server->AutoReconnect() || _this->m_server->IdReconnect())&& strlen(_this->m_server->AutoReconnectAdr()) == 0)
			{
				_this->m_server->AutoReconnectAdr(szAdrName);
				_this->m_server->AutoReconnectPort(nport);
			}

			// Attempt to create a new socket
			VSocket *tmpsock;
			tmpsock = new VSocket;
			if (tmpsock) {

				// Connect out to the specified host on the VNCviewer listen port
				tmpsock->Create();
				if (tmpsock->Connect(szAdrName, nport)) {
					if ( bId )
					{
						// wa@2005 -- added support for the AutoReconnectId
						// Set the ID for this client -- code taken from vncconndialog.cpp (ln:142)
						tmpsock->Send(szId,250);
						tmpsock->SetTimeout(0);
						
						// adzm 2009-07-05 - repeater IDs
						// Add the new client to this server
						// adzm 2009-08-02
						_this->m_server->AddClient(tmpsock, TRUE, TRUE, 0, NULL, szId, szAdrName, nport);
					} else {
						// Add the new client to this server
						// adzm 2009-08-02
						_this->m_server->AddClient(tmpsock, TRUE, TRUE, 0, NULL, NULL, szAdrName, nport);
					}
				} else {
					delete tmpsock;
					_this->m_server->AutoConnectRetry();
				}
			}
		
			return 0;
		}

		// Process FileTransfer asynchronous Send Packet Message
		if (iMsg == FileTransferSendPacketMessage) 
		{
		  vncClient* pClient = (vncClient*) wParam;
		  if (_this->m_server->IsClient(pClient)) pClient->SendFileChunk();
		}

		// adzm 2009-07-05 - Tray icon balloon tips
		if (iMsg == MENU_TRAYICON_BALLOON_MSG) {
			omni_mutex_lock sync(_this->m_mutexTrayIcon);

			// adzm 2009-07-05 - Tray icon balloon tips
			if (_this->m_BalloonInfo) {		
				free(_this->m_BalloonInfo);
				_this->m_BalloonInfo = NULL;
			}
			if (_this->m_BalloonTitle) {
				free(_this->m_BalloonTitle);
				_this->m_BalloonTitle = NULL;
			}

			char* szInfo = (char*)wParam;
			char* szTitle = (char*)lParam;
			
			if (szInfo && (strlen(szInfo) > 0) ) {
				_this->m_BalloonInfo = _strdup(szInfo);
			}
			if (szTitle && (strlen(szTitle) > 0) ) {
				_this->m_BalloonTitle = _strdup(szTitle);
			}

			if (szInfo) {
				free(szInfo);
			}
			if (szTitle) {
				free(szTitle);
			}

			if (_this->IsIconSet) {
				_this->SendTrayMsg(NIM_MODIFY, _this->m_nid.hIcon == _this->m_winvnc_icon ? FALSE : TRUE);
			}
		}
	}

	// Message not recognised
	return DefWindowProc(hwnd, iMsg, wParam, lParam);
}
Ejemplo n.º 27
0
//////////////////////////////////////////////////////////////////////////
//进程管理窗口过程
//////////////////////////////////////////////////////////////////////////
LRESULT CALLBACK ProcDlgProc(HWND hDlg,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
	HWND hList = NULL;
	LPNMHDR lPnmhdr = NULL;
	switch (uMsg)
	{
	case WM_COMMAND:
		{
			switch(LOWORD(wParam))
			{
			case ID_POPUP_40007:
				{
					hList = GetDlgItem(hDlg,IDC_LIST1);
					int index = ListView_GetSelectionMark(hList);
					char temp[10] = {0};
					ListView_GetItemText(hList,index,0,temp,sizeof(temp));
					int pid = atoi(temp);
					ProcDelete(sockfd,pid);

				}
				break;
			case ID_POPUP_40009:
				{
					//PID==0为刷新
					int pid = 0;
					ProcDelete(sockfd,pid);
				}
				break;
			}
		}
		break;
	case WM_NOTIFY:
		{
			lPnmhdr = (LPNMHDR)lParam;
			hList = GetDlgItem(hDlg,IDC_LIST1);
			if (lPnmhdr->hwndFrom==hList)
			{
				switch (lPnmhdr->code)
				{
				case NM_RCLICK:
					{
						HMENU hMenu = LoadMenu(hInst,MAKEINTRESOURCE(IDR_MENU2));
						hMenu = GetSubMenu(hMenu,0);
						POINT stPos;
						GetCursorPos(&stPos);
						TrackPopupMenu(hMenu,TPM_LEFTALIGN,stPos.x,stPos.y,NULL,hDlg,NULL);
					}
					break;
				}
			}
		}
	case WM_INITMENUPOPUP:
		{
			BOOL flag = TRUE;
			hList = GetDlgItem(hDlg,IDC_LIST1);
			int index = ListView_GetSelectionMark(hList);
			int count = ListView_GetItemCount(hList);
			if (index >= count)
			{
				flag = FALSE;
			}
			switch(LOWORD(lParam))
			{
			case 0:
				{
					if (flag)
					{
						EnableMenuItem((HMENU)wParam,ID_POPUP_40007,MF_ENABLED);
					}
					else
					{
						EnableMenuItem((HMENU)wParam,ID_POPUP_40007,MF_GRAYED);
					}

				}
				break;
			}
		}
		break;
	case WM_SOCKET:
		{
			switch(LOWORD(lParam))
			{
			case FD_WRITE:
				{
					//继续发送
					SendCmd(sockfd,NULL,NULL);
				}
				break;
			case FD_READ:
				{
					RecvCmd(sockfd);
				}
				break;
			case FD_CLOSE:
				{
					//SOCKET出错处理,MainFunc.H里 清理缓冲区
					SocketError(sockfd);
				}
				break;
			}
		}
		break;
	case WM_INITDIALOG:
		{
			sockfd = (SOCKET)lParam;
			hList = GetDlgItem(hDlg,IDC_LIST1);
			hSysList = hList;
			//非拥塞模式
			WSAAsyncSelect(sockfd,hDlg,WM_SOCKET,FD_WRITE|FD_READ|FD_CLOSE);
			//发送命令请求
			RatProto ratPro;
			ratPro.RatId = PROC_VIEW;
			ratPro.RatLen = sizeof(RatProto);
			SendCmd(sockfd,(char*)&ratPro,ratPro.RatLen);
			//初始化列表
			InitProcList(hList);
		}
		break;
	case WM_CLOSE:
		{
			EndDialog(hDlg,NULL);
		}
		break;
	default:
		break;
	}

	return FALSE;
}
Ejemplo n.º 28
0
LRESULT CALLBACK CTitleBar::WndProc(HWND hwnd, UINT iMsg, 
					   WPARAM wParam, LPARAM lParam)
{
	// Added Jef Fix
    CTitleBar *TitleBarThis=NULL;
    TitleBarThis = helper::SafeGetWindowUserData<CTitleBar>(hwnd);

	switch (iMsg)
	{

	case WM_CREATE:
		return 0;

	case WM_PAINT:
			TitleBarThis->Draw();
			return 0;

	case WM_CLOSE:
		{
			HWND Window=TitleBarThis->GetSafeHwnd();
			TitleBarThis->FreePictures();
			DestroyWindow(Window);
//			vnclog.Print(0,_T(" Q6 \n"));
//			PostQuitMessage(0);
			return 0;
		}

	case WM_DESTROY:
			TitleBarThis->FreePictures();
//			vnclog.Print(0,_T(" Q7 \n"));
//			PostQuitMessage(0);
			return 0;

	case WM_DRAWITEM:
		{
			HDC hdcMem; 
			LPDRAWITEMSTRUCT lpdis; 

            lpdis = (LPDRAWITEMSTRUCT) lParam; 
            hdcMem = CreateCompatibleDC(lpdis->hDC); 
			HGDIOBJ hbrOld=NULL;
 
			if(lpdis->CtlID==tbIDC_CLOSE)
					hbrOld=SelectObject(hdcMem, TitleBarThis->hClose); 
			if(lpdis->CtlID==tbIDC_MAXIMIZE)
					hbrOld=SelectObject(hdcMem, TitleBarThis->hMaximize); 
			if(lpdis->CtlID==tbIDC_MINIMIZE)
					hbrOld=SelectObject(hdcMem, TitleBarThis->hMinimize); 
			
			if(lpdis->CtlID==tbIDC_PIN)
			{
				if(TitleBarThis->AutoHide==TRUE)
					hbrOld=SelectObject(hdcMem, TitleBarThis->hPinUp); 
				else
					hbrOld=SelectObject(hdcMem, TitleBarThis->hPinDown); 
			}

			BitBlt(lpdis->hDC,
					lpdis->rcItem.left,
					lpdis->rcItem.top,
	                lpdis->rcItem.right - lpdis->rcItem.left, 
					lpdis->rcItem.bottom - lpdis->rcItem.top, 
	                hdcMem,
					0,
					0,
					SRCCOPY);
			if (hbrOld) SelectObject(hdcMem,hbrOld);
            DeleteDC(hdcMem); 
            return TRUE; 
		}

	case WM_COMMAND: 
		if (HIWORD(wParam) == BN_CLICKED)
		{
			//Handle the Pin for holding the window
			if(LOWORD(wParam) == tbIDC_PIN)
			{
				if(TitleBarThis->AutoHide==TRUE)
				{
					TitleBarThis->AutoHide=FALSE;
					TitleBarThis->DisplayWindow(TRUE);
				}
				else
				{
					TitleBarThis->AutoHide=TRUE;
					TitleBarThis->DisplayWindow(FALSE);
				}

				//Redraw window to show the new gfx...
				::RedrawWindow(TitleBarThis->Pin, NULL, NULL, TRUE);
			}

			//If default = true we'll send usally showwindow and close messages
			if(tbDefault==TRUE)
			{
				if(LOWORD(wParam) == tbIDC_CLOSE)
					::SendMessage(TitleBarThis->Parent, WM_CLOSE, NULL, 0);
				if(LOWORD(wParam) == tbIDC_MAXIMIZE)
				{
					//if(::IsZoomed(TitleBarThis->Parent)==TRUE)
						ShowWindow(TitleBarThis->Parent, SW_RESTORE);
					/*else
						ShowWindow(TitleBarThis->Parent, SW_MAXIMIZE);*/
				}
				if(LOWORD(wParam) == tbIDC_MINIMIZE)
					ShowWindow(TitleBarThis->Parent, SW_MINIMIZE);
			}
			else //default = false - send custom message on buttons
			{
				if(LOWORD(wParam) == tbIDC_CLOSE)
					::SendMessage(TitleBarThis->Parent, tbWM_CLOSE, NULL, NULL);
				if(LOWORD(wParam) == tbIDC_MAXIMIZE)
					::SendMessage(TitleBarThis->Parent, tbWM_MAXIMIZE, NULL, NULL);
				if(LOWORD(wParam) == tbIDC_MINIMIZE)
					::SendMessage(TitleBarThis->Parent, tbWM_MINIMIZE, NULL, NULL);
			}
        }

		//Menu part starts here
		{
			UINT IDNum=LOWORD(wParam);
		
			if(IDNum>=tbWMCOMMANDIDStart&&IDNum<tbWMCOMMANDIDEnd) //The ID is in range for a menuclick
			{
				UINT Num=IDNum-tbWMCOMMANDIDStart;

				//When the close,minimize, maximize is not present just send! :)
				if(tbLastIsStandard==FALSE)
					::SendMessage(TitleBarThis->Parent, WM_USER+tbWMUSERID+Num, NULL,NULL);
				else //Handle close, minimize and maximize
				{
					HMENU Menu=LoadMenu(TitleBarThis->hInstance,MAKEINTRESOURCE (tbMENUID));
					HMENU SubMenu=GetSubMenu(Menu,0);;

					UINT Total=0;

					//Get the real number of entries (exluding seperators)
					for(int i=0;i<GetMenuItemCount(SubMenu);i++)
					{
						int res=::GetMenuString(SubMenu, i, NULL, 0, MF_BYPOSITION);
						if(res!=0)
							Total++;
					}

					if(Num==Total-1) //Close button
						::SendMessage(TitleBarThis->m_hWnd,WM_COMMAND,MAKEWPARAM(tbIDC_CLOSE,BN_CLICKED),NULL);
					else if(Num==Total-2) //Minimize button
						::SendMessage(TitleBarThis->m_hWnd,WM_COMMAND,MAKEWPARAM(tbIDC_MINIMIZE,BN_CLICKED),NULL);
					else if(Num==Total-3) //Maximize button
						::SendMessage(TitleBarThis->m_hWnd,WM_COMMAND,MAKEWPARAM(tbIDC_MAXIMIZE,BN_CLICKED),NULL);
					else
						::SendMessage(TitleBarThis->Parent, WM_USER+tbWMUSERID+Num, NULL,NULL);

					DestroyMenu (SubMenu);
					DestroyMenu (Menu);
				}
			}
		}

        break;
	
	case WM_MOUSEMOVE:
			if(TitleBarThis->HideAfterSlide==FALSE)
			{
				TitleBarThis->SlideDown=TRUE;
				::SetTimer(TitleBarThis->m_hWnd, tbScrollTimerID, 20, NULL);
			}
		break;

	case WM_LBUTTONDBLCLK:
			//If the default entries on the context menu is activated then doubleclick is restore :)
			if(tbLastIsStandard==TRUE)
				::SendMessage(TitleBarThis->m_hWnd,WM_COMMAND,MAKEWPARAM(tbIDC_MAXIMIZE,BN_CLICKED),NULL);
		break;

	case WM_RBUTTONDOWN:
		{
			HMENU Menu=LoadMenu(TitleBarThis->hInstance,MAKEINTRESOURCE (tbMENUID));
			HMENU SubMenu=GetSubMenu(Menu,0);;

			POINT  lpPoint;
			::GetCursorPos(&lpPoint);

			int Pos=0;

			//Set ID values to each item
			for(int i=0;i<GetMenuItemCount(SubMenu);i++)
			{
				TCHAR Text[MAX_PATH];
				ZeroMemory(Text,sizeof(Text));
				int res=::GetMenuString(SubMenu, i, Text, MAX_PATH, MF_BYPOSITION);
				
				if(res!=0)
				{
					::ModifyMenu(SubMenu,i,MF_BYPOSITION, tbWMCOMMANDIDStart+Pos,Text);
					Pos++;
				}
			}

			//Loop through each item from pos to set the default value on restore
			if(tbLastIsStandard==TRUE)
			{
				int RealPos=0;
				for(int i=0;i<GetMenuItemCount(SubMenu);i++)
				{
					TCHAR Text[MAX_PATH];
					ZeroMemory(Text,sizeof(Text));
					int res=::GetMenuString(SubMenu, i, Text, MAX_PATH, MF_BYPOSITION);
					
					if(res!=0)
					{
						RealPos++;

						if(RealPos==Pos-2)
						::SetMenuDefaultItem(SubMenu, i, TRUE);
					}
				}
			}

			TrackPopupMenu(SubMenu,TPM_LEFTALIGN, lpPoint.x, lpPoint.y, 0, TitleBarThis->m_hWnd, NULL);

			SetForegroundWindow (TitleBarThis->m_hWnd);
			DestroyMenu (SubMenu);
			DestroyMenu (Menu);

			break;
		}

	case WM_TIMER:
		{
			UINT TimerID=(UINT)wParam;
			
			if(TimerID==tbScrollTimerID)
			{
				RECT lpRect;
				::GetWindowRect(TitleBarThis->m_hWnd, &lpRect);

				if( ((lpRect.top==0)&&(TitleBarThis->SlideDown==TRUE))
					||
					((lpRect.top==-tbHeigth+1)&&(TitleBarThis->SlideDown==FALSE)))
				{
					KillTimer(TitleBarThis->m_hWnd, tbScrollTimerID);

					if(TitleBarThis->HideAfterSlide==TRUE)
					{
						TitleBarThis->HideAfterSlide=FALSE;
						ShowWindow(TitleBarThis->GetSafeHwnd(), SW_HIDE);
					}
					return 0;
				}

				if(TitleBarThis->SlideDown==TRUE)
				{
					lpRect.top++; lpRect.bottom++;
				}
				else
				{
					lpRect.top--; lpRect.bottom--;
				}

				::MoveWindow(TitleBarThis->m_hWnd, lpRect.left, lpRect.top, lpRect.right-lpRect.left, lpRect.bottom-lpRect.top, TRUE);
			}

			//Check mouse cordinates and hide if the mouse haven't been in the window for a few seconds
			if(TimerID==tbAutoScrollTimer)
			{
				RECT lpRect;
				POINT pt;
				::GetWindowRect(TitleBarThis->m_hWnd, &lpRect);
				::GetCursorPos(&pt);

				if(PtInRect(&lpRect, pt)==FALSE) 
				{
					TitleBarThis->IntAutoHideCounter++;

					if(TitleBarThis->IntAutoHideCounter==tbAutoScrollTime)
					{
						TitleBarThis->SlideDown=FALSE;
						::SetTimer(TitleBarThis->m_hWnd, tbScrollTimerID, tbScrollDelay, NULL);
					}
				}
				else
				{
					TitleBarThis->IntAutoHideCounter=0;
				}
			}

			break;
		}
	}//Case - end
	
	return DefWindowProc(hwnd, iMsg, wParam, lParam);
}
Ejemplo n.º 29
0
Boolean handle_menu (short item, HMENU menu)
{
	short i;
	Boolean to_return = FALSE;
	short item_hit;
	Boolean need_redraw = FALSE;
	item_hit = item;

	switch (item) {
   	case -1: break;
		case 1: // open
			load_scenario();
			if (overall_mode == 60) {
				update_item_menu();
				set_up_main_screen();
				}
			break;
		case 2: // save
			modify_lists();
			save_scenario();
			break;
		case 3: // new scen
			build_scenario();
			if (overall_mode == 60)
				set_up_main_screen();
			break;

		case 5: // quit
			if (save_check(869) == FALSE)
				break;
			discard_graphics();
			PostQuitMessage(0);
			break;

			// Scenario Menu

		case 101:
			if (change_made == TRUE) {
				give_error("You need to save the changes made to your scenario before you can add a new town.",
					"",0);
				return to_return;
				}
			if (scenario.num_towns >= 200) {
				give_error("You have reached the limit of 200 towns you can have in one scenario.",
					"",0);
				return to_return;
				}
			if (new_town(scenario.num_towns) == TRUE)
				set_up_main_screen();
			break;
		case 103:
			edit_scen_details();
			break;
		case 104:
			edit_scen_intro();
			break;
		case 105:
			set_starting_loc();
			break;
		case 106: overall_mode = 47;
			set_string("Select party starting location.","");
			break;
		case 109:
            lpsi.fMask = SIF_POS;
            lpsi.nPos = 0;
            SetScrollInfo(right_sbar,SB_CTL,&lpsi,TRUE);
            //SetScrollPos(right_sbar,SB_CTL,0,TRUE);
            start_special_editing(0,0); break;
		case 110:
            lpsi.fMask = SIF_POS;
            lpsi.nPos = 0;
            SetScrollInfo(right_sbar,SB_CTL,&lpsi,TRUE);
			 //SetScrollPos(right_sbar,SB_CTL,0,TRUE);
             start_string_editing(0,0);
			break;
		case 111:
			if (change_made == TRUE) {
				give_error("You need to save the changes made to your scenario before you can add a new town.",
					"",0);
				return to_return;
				}
			i = pick_import_town(841,0);
			if (i >= 0) {
				import_town(i);
				change_made = TRUE;
				redraw_screen();
				}
			break;
		case 112:
			edit_save_rects();
			break;
		case 113:
			edit_horses();
			break;
		case 114:
			edit_boats();
			break;
		case 115:
			edit_add_town();
			break;
		case 116:
			edit_scenario_events();
			break;
		case 117:
			edit_item_placement();
			break;
		case 118:
			if (change_made == TRUE) {
				give_error("You need to save the changes made to your scenario before you can delete a town.",
					"",0);
				return to_return;
				}
			if (scenario.num_towns == 1) {
				give_error("You can't delete the last town in a scenario. All scenarios must have at least 1 town.",
					"",0);
				return to_return;
				}
			if (scenario.num_towns - 1 == cur_town) {
				give_error("You can't delete the last town in a scenario while you're working on it. Load a different town, and try this again.",
					"",0);
				return to_return;
				}
			if (scenario.num_towns - 1 == scenario.which_town_start) {
				give_error("You can't delete the last town in a scenario while it's the town the party starts the scenario in. Change the parties starting point and try this again.",
					"",0);
				return to_return;
				}
			if (fancy_choice_dialog(865,0) == 1)
				delete_last_town();
			break;
		case 119:
			if (fancy_choice_dialog(866,0) == 1) {
        last_file_printed = 0;
				start_data_dump();
				}
			break;
		case 120:
			if (change_made == TRUE) {
				give_error("You need to save the changes made to your scenario before you can print the file Scenario Text.",
					"",0);
				return to_return;
				}
			if (fancy_choice_dialog(871,0) == 1) {
        last_file_printed = 1;
				scen_text_dump();
			redraw_screen();
			}
			break;

		case 121:
			if (fancy_choice_dialog(867,0) == 1) {
        last_file_printed = 2;
				start_shopping_data_dump();
				}
		break;
		case 122:
			if (fancy_choice_dialog(868,0) == 1) {
        last_file_printed = 3;
				start_monst_data_dump();
				}
		break;
    case 123:
			if (fancy_choice_dialog(890,0) == 1) {
         last_file_printed = 4;
         start_spec_data_dump();
				}
    break;
		case 124:
			if (fancy_choice_dialog(878,0) == 1) {
      	 last_file_printed = 7;
				 object_scenario_data_dump();
			}
			break;


			// Town Menu
		case 201: edit_town_details(); break;
		case 202: edit_town_wand(); break;
		case 203: 							overall_mode = 9;
			mode_count = 2;
			set_cursor(5);
			set_string("Set town boundary","Select upper left corner");
			break;
		case 204: frill_up_terrain(); break;
		case 205: unfrill_terrain(); break;
		case 206: edit_town_strs(); break;
		case 208: if (fancy_choice_dialog(863,0) == 2) // add random
					break;
				place_items_in_town();
				 break;
		case 209: for (i = 0; i < 64; i++) // set not prop
					town.preset_items[i].property = 0;
				fancy_choice_dialog(861,0);
				draw_terrain();
				break;
		case 210: if (fancy_choice_dialog(862,0) == 2) // clear all items
					break;
				for (i = 0; i < 64; i++)
					town.preset_items[i].item_code = -1;
				draw_terrain();
				break;
		case 213:
            lpsi.fMask = SIF_POS;
            lpsi.nPos = 0;
            SetScrollInfo(right_sbar,SB_CTL,&lpsi,TRUE);
            //SetScrollPos(right_sbar,SB_CTL,0,TRUE);
             start_special_editing(2,0); break;
		case 214:
            lpsi.fMask = SIF_POS;
            lpsi.nPos = 0;
            SetScrollInfo(right_sbar,SB_CTL,&lpsi,TRUE);
            //SetScrollPos(right_sbar,SB_CTL,0,TRUE);
        start_string_editing(2,0); break;
		case 215: edit_advanced_town(); break;
		case 216: edit_town_events(); break;
		case 217: if (fancy_choice_dialog(872,0) == 2) // clear all monsters
					break;
				for (i = 0; i < 60; i++) {
						t_d.creatures[i].number = 0;
						t_d.creatures[i].start_loc.x = 0;
						t_d.creatures[i].start_loc.y = 0;
						t_d.creatures[i].spec_enc_code = 0;
						t_d.creatures[i].time_flag = 0;
                        t_d.creatures[i].spec1 = -1;
                        t_d.creatures[i].spec2 = -1;
						}
		break;
		case 218: if (fancy_choice_dialog(873,0) == 2) // clear all special encounters
					break;
					for (i = 0; i < 50; i++) {
							town.special_locs[i].x = 100;
							town.special_locs[i].y = 0;
							town.spec_id[i] = 255;
							}
		break;
		case 219: if (fancy_choice_dialog(874,0) == 2) // clear all fields
					break;
				for (i = 0; i < 50; i++)
						if ((town.preset_fields[i].field_type >= 0) && (town.preset_fields[i].field_type < 9)) {
						town.preset_fields[i].field_type = 0;
						town.preset_fields[i].field_loc.x = 0;
						town.preset_fields[i].field_loc.y = 0;
						}
		break;

		case 220: if (fancy_choice_dialog(876,0) == 2) // clear all stains
					break;
				for (i = 0; i < 50; i++)
						if ((town.preset_fields[i].field_type > 13) && (town.preset_fields[i].field_type < 22)) {
						town.preset_fields[i].field_type = 0;
						town.preset_fields[i].field_loc.x = 0;
						town.preset_fields[i].field_loc.y = 0;
						}
		break;

		case 221:    if (fancy_choice_dialog(877,0) == 1) { // make concise town report
		              last_file_printed = 5;
									start_town_data_dump();
									}
			break;

		case 222:
					start_dialogue_editing(0);
		break;


			// Outdoor Menu
		case 301: outdoor_details(); break;
		case 302: edit_out_wand(0); break;
		case 303: edit_out_wand(1); break;
		case 304: frill_up_terrain(); break;
		case 305: unfrill_terrain(); break;
		case 306: edit_out_strs(); break;
		case 307: if (fancy_choice_dialog(875,0) == 2) // clear all special encounters
					break;
					for (i = 0; i < 18; i++) {
							current_terrain.special_locs[i].x = 100;
							current_terrain.special_locs[i].y = 0;
							current_terrain.special_id[i] = 255;
							}

		case 311:
            lpsi.fMask = SIF_POS;
            lpsi.nPos = 0;
            SetScrollInfo(right_sbar,SB_CTL,&lpsi,TRUE);
            //SetScrollPos(right_sbar,SB_CTL,0,TRUE);
            start_special_editing(1,0); break;
		case 312:
            lpsi.fMask = SIF_POS;
            lpsi.nPos = 0;
            SetScrollInfo(right_sbar,SB_CTL,&lpsi,TRUE);
            //SetScrollPos(right_sbar,SB_CTL,0,TRUE);
            start_string_editing(1,0); break;
		break;

		case 313:
			if (fancy_choice_dialog(879,0) == 1) {
				 last_file_printed = 6;
				 start_outdoor_data_dump();
				 }
			break;

		case 401:
				 start_town_edit();
		break;
		case 402:
				 start_out_edit();
		break;
		case 403:
			short x, y;
			location spot_hit;

			if (editing_town == false) {

							if (change_made == TRUE) {
								if (save_check(859) == FALSE)
									break;
								}
							x = pick_out(cur_out);
							if (x >= 0) {
								spot_hit.x = x / 100;
								spot_hit.y = x % 100;
								load_outdoors(spot_hit,0);
								augment_terrain(spot_hit);
								start_out_edit();
								}

							}
			else {
							if (change_made == TRUE) {
								if (save_check(859) == FALSE)
									break;
								}
							x = pick_town_num(855,cur_town);
							if (x >= 0) {
								load_town(x);
								start_town_edit();
								}
							}
			break;
		case 404:
                    set_up_main_screen();
					start_terrain_editing();
		break;
		case 405:
                    set_up_main_screen();
					start_monster_editing(0);
		break;
		case 406:
					start_item_editing(0);
		break;
		case 407:
					set_up_main_screen();
		break;

		case 408: // switch view
				cur_viewing_mode = 1 - cur_viewing_mode;
				need_redraw = TRUE;
				draw_main_screen();
				draw_terrain();
		break;

		case 409: // load previous town/outdoor zone
					if (editing_town == true) {
								if (cur_town == 0)
								load_town(scenario.num_towns - 1);
								else load_town(cur_town - 1);
								start_town_edit();
						 }
			 else {
							if (cur_out.x > 0) {
							 x = cur_out.x - 1;
				 			 y = cur_out.y;
				 			 }
							if ((cur_out.x == 0) && (cur_out.y > 0)) {
				 			x = scenario.out_width - 1;
				 			y = cur_out.y - 1;
				 			}
							if ((cur_out.x == 0) && (cur_out.y == 0)) {
				 			x = scenario.out_width - 1;
				 			y = scenario.out_height - 1;
				 			}
								spot_hit.x = x;
								spot_hit.y = y;
								load_outdoors(spot_hit,0);
								augment_terrain(spot_hit);
								start_out_edit();
						}
		break;

		case 410: // load next town/outdoor zone
					if (editing_town == true) {
								if (cur_town + 1 == scenario.num_towns)
								load_town(0);
								else load_town(cur_town + 1);
								start_town_edit();
						 }
				 else {
				 			if ((cur_out.x < (scenario.out_width - 1)) && (cur_out.y <= (scenario.out_height - 1))) {
				 			x = cur_out.x + 1;
				 			y = cur_out.y;
				 			}
							if ((cur_out.x == (scenario.out_width - 1)) && (cur_out.y < (scenario.out_height - 1))) {
							x = 0;
				 			y = cur_out.y + 1;
							}
							if ((cur_out.x == (scenario.out_width - 1)) && (cur_out.y == (scenario.out_height - 1))) {
							x = 0;
							y = 0;
							}
								spot_hit.x = x;
								spot_hit.y = y;
								load_outdoors(spot_hit,0);
								augment_terrain(spot_hit);
								start_out_edit();
						 }
			break;

			case 411: //   MENUITEM "Terrain Animations Play", 411

            HMENU menu,big_menu;
            big_menu = GetMenu(mainPtr);
            menu = GetSubMenu(big_menu,4);

            if(play_anim == FALSE){
                play_anim = TRUE;
                CheckMenuItem(menu,411,MF_BYCOMMAND | MF_CHECKED);
                }
            else{
                play_anim = FALSE;
                CheckMenuItem(menu,411,MF_BYCOMMAND | MF_UNCHECKED);
                }
            break;

		case 412: // load outdoor zone above
							if (editing_town)
							break;
							if (cur_out.y > 0) {
							 x = cur_out.x;
				 			 y = cur_out.y - 1;
				 			 }
							else {
							 x = cur_out.x;
				 			y = scenario.out_height - 1;
				 			}
								spot_hit.x = x;
								spot_hit.y = y;
								load_outdoors(spot_hit,0);
								augment_terrain(spot_hit);
								start_out_edit();
		break;

		case 413: // load outdoor zone below
							if (editing_town)
							break;
							if (cur_out.y == scenario.out_height - 1) {
							 x = cur_out.x;
				 			 y = 0;
				 			 }
							else {
							 x = cur_out.x;
				 			 y = cur_out.y + 1;
				 			}
								spot_hit.x = x;
								spot_hit.y = y;
								load_outdoors(spot_hit,0);
								augment_terrain(spot_hit);
								start_out_edit();
		break;

		case 414: //   Repeat print of last file printed
         switch (last_file_printed){
            case 0:
				start_data_dump();
		    break;

            case 1:
				scen_text_dump();
            break;

            case 2:
				start_shopping_data_dump();
			break;

            case 3:
				start_monst_data_dump();
            break;

            case 4:
             start_spec_data_dump();
            break;

            case 5:
				start_town_data_dump();
            break;

            case 6:
				 start_outdoor_data_dump();
            break;

            case 7:
				 object_scenario_data_dump();
            break;
            }
		break;

				// Extra Help
		case 801: // help file
			WinHelp(mainPtr,"Scenario Editor.hlp",HELP_CONTENTS,0L);
			break;
		case 802: fancy_choice_dialog(986,0); break; // started
		case 803: fancy_choice_dialog(1000,0); break; // testing
		case 804: fancy_choice_dialog(1001,0); break; // distributing
		case 805:
		fancy_choice_dialog(1062,0);
		break;

		default:
			if ((overall_mode >= 60) || (editing_town == FALSE)) {
				give_error("You can only place items and individual monsters in town sections, not outdoors.","",0);
				break;
				}
			if ((item_hit >= 600) && (item_hit < 1000)) {
				item_hit -= 600;
				if (scen_item_list.scen_items[item_hit].variety == 0) {
					give_error("This item has its Variety set to No Item. You can only place items with a Variety set to an actual item type.","",0);
					return to_return;
					}
				overall_mode = 4;
				set_string("Place the item.","Select item location");
				mode_count = item_hit;
				}
//       skip the type 0 monster, it is non-existent
			if ((item_hit >= 1001) && (item_hit <= 1255)) { // 1,255?
				overall_mode = 28;
            item_hit -= 1000;
				set_string("Place the monster.","Select monster location");
				mode_count = item_hit;
				}
/*
			if ((item_hit >= 1256) && (item_hit <= 1455)) {
            item_hit -= 1256;
								mode_count = item_hit;
								load_town(item_hit);
								start_town_edit();
//				set_string("Loading the indicated town."," ");

				}
*/
			break;

		}
	if ((item >= 100) && (item < 200) && (item != 118) && (item != 119))
		change_made = TRUE;

	return to_return;
}
Ejemplo n.º 30
0
void Filesets_OnEndTask_Menu (HWND hDlg, LPTASKPACKET ptp)
{
   LPIDENT lpiFileset = (LPIDENT)(TASKDATA(ptp)->mt.lpi);

   HMENU hm;
   if (lpiFileset != NULL)
      hm = TaLocale_LoadMenu (MENU_SET);
   else
      hm = TaLocale_LoadMenu (MENU_SET_NONE);

   if (hm != NULL)
      {
      if (lpiFileset == NULL)
         {
         HMENU hmView = GetSubMenu (hm, 0);
         DWORD dwStyle = GetWindowLong (TASKDATA(ptp)->mt.hParent, GWL_STYLE);

         CheckMenuRadioItem (hmView,
                             M_SET_VIEW_REPORT, M_SET_VIEW_TREE,
                             ((dwStyle & FLS_VIEW_MASK) == FLS_VIEW_TREELIST) ? M_SET_VIEW_TREELIST :
                             ((dwStyle & FLS_VIEW_MASK) == FLS_VIEW_TREE)     ? M_SET_VIEW_TREE : M_SET_VIEW_REPORT,
                             MF_BYCOMMAND);

         CheckMenuRadioItem (hmView,
                             M_VIEW_ONEICON, M_VIEW_STATUS,
                             (gr.ivSet == ivTWOICONS) ? M_VIEW_TWOICONS :
                             (gr.ivSet == ivONEICON)  ? M_VIEW_ONEICON : M_VIEW_STATUS,
                             MF_BYCOMMAND);
         }
      else
         {
         if (!ptp->rc)
            {
            EnableMenu (hm, M_SET_REPLICATION, FALSE);
            EnableMenu (hm, M_SET_SETQUOTA,    FALSE);
            EnableMenu (hm, M_SET_RELEASE,     FALSE);
            EnableMenu (hm, M_SET_CLONE,       FALSE);
            EnableMenu (hm, M_SET_MOVETO,      FALSE);
            EnableMenu (hm, M_SET_DUMP,        FALSE);
            EnableMenu (hm, M_SET_RESTORE,     FALSE);
            }
         else
            {
            if (TASKDATA(ptp)->fs.Type == ftCLONE)
               {
               EnableMenu (hm, M_SET_REPLICATION, FALSE);
               EnableMenu (hm, M_SET_RELEASE,     FALSE);
               EnableMenu (hm, M_SET_CLONE,       FALSE);
               EnableMenu (hm, M_SET_MOVETO,      FALSE);
               }

            if (TASKDATA(ptp)->fs.Type != ftREADWRITE)
               {
               EnableMenu (hm, M_SET_CLONE, FALSE);
               EnableMenu (hm, M_SET_RELEASE, FALSE);
               EnableMenu (hm, M_SET_SETQUOTA, FALSE);
               EnableMenu (hm, M_SET_RESTORE, FALSE);
               }
            }
         }

      DisplayContextMenu (hm, TASKDATA(ptp)->mt.ptScreen, TASKDATA(ptp)->mt.hParent);
      }
}