Esempio n. 1
0
static INT_PTR CALLBACK SettingsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg) {
	case WM_INITDIALOG:
		TranslateDialogDefault(hwndDlg);
		{
			hwndSettingsDlg = hwndDlg;
			LCID locale = Langpack_GetDefaultLocale();
			SendDlgItemMessage(hwndDlg, IDC_ICON_HEADER, STM_SETIMAGE, IMAGE_ICON, (LPARAM)IcoLib_GetIcon("AutoShutdown_Header"));
			{
				HFONT hBoldFont;
				LOGFONT lf;
				if (GetObject((HFONT)SendDlgItemMessage(hwndDlg, IDC_TEXT_HEADER, WM_GETFONT, 0, 0), sizeof(lf), &lf)) {
					lf.lfWeight = FW_BOLD;
					hBoldFont = CreateFontIndirect(&lf);
				}
				else hBoldFont = NULL;
				SendDlgItemMessage(hwndDlg, IDC_TEXT_HEADER, WM_SETFONT, (WPARAM)hBoldFont, FALSE);
			}
			/* read-in watcher flags */
			{
				WORD watcherType = db_get_w(NULL, "AutoShutdown", "WatcherFlags", SETTING_WATCHERFLAGS_DEFAULT);
				CheckRadioButton(hwndDlg, IDC_RADIO_STTIME, IDC_RADIO_STCOUNTDOWN, (watcherType&SDWTF_ST_TIME) ? IDC_RADIO_STTIME : IDC_RADIO_STCOUNTDOWN);
				CheckDlgButton(hwndDlg, IDC_CHECK_SPECIFICTIME, (watcherType&SDWTF_SPECIFICTIME) != 0 ? BST_CHECKED : BST_UNCHECKED);
				CheckDlgButton(hwndDlg, IDC_CHECK_MESSAGE, (watcherType&SDWTF_MESSAGE) != 0 ? BST_CHECKED : BST_UNCHECKED);
				CheckDlgButton(hwndDlg, IDC_CHECK_FILETRANSFER, (watcherType&SDWTF_FILETRANSFER) != 0 ? BST_CHECKED : BST_UNCHECKED);
				CheckDlgButton(hwndDlg, IDC_CHECK_IDLE, (watcherType&SDWTF_IDLE) != 0 ? BST_CHECKED : BST_UNCHECKED);
				CheckDlgButton(hwndDlg, IDC_CHECK_STATUS, (watcherType&SDWTF_STATUS) != 0 ? BST_CHECKED : BST_UNCHECKED);
				CheckDlgButton(hwndDlg, IDC_CHECK_CPUUSAGE, (watcherType&SDWTF_CPUUSAGE) != 0 ? BST_CHECKED : BST_UNCHECKED);
			}
			/* read-in countdown val */
			{
				SYSTEMTIME st;
				if (!TimeStampToSystemTime((time_t)db_get_dw(NULL, "AutoShutdown", "TimeStamp", SETTING_TIMESTAMP_DEFAULT), &st))
					GetLocalTime(&st);
				DateTime_SetSystemtime(GetDlgItem(hwndDlg, IDC_TIME_TIMESTAMP), GDT_VALID, &st);
				DateTime_SetSystemtime(GetDlgItem(hwndDlg, IDC_DATE_TIMESTAMP), GDT_VALID, &st);
				SendMessage(hwndDlg, M_CHECK_DATETIME, 0, 0);
			}
			{
				DWORD setting = db_get_dw(NULL, "AutoShutdown", "Countdown", SETTING_COUNTDOWN_DEFAULT);
				if (setting < 1) setting = SETTING_COUNTDOWN_DEFAULT;
				SendDlgItemMessage(hwndDlg, IDC_SPIN_COUNTDOWN, UDM_SETRANGE, 0, MAKELPARAM(UD_MAXVAL, 1));
				SendDlgItemMessage(hwndDlg, IDC_EDIT_COUNTDOWN, EM_SETLIMITTEXT, (WPARAM)10, 0);
				SendDlgItemMessage(hwndDlg, IDC_SPIN_COUNTDOWN, UDM_SETPOS, 0, MAKELPARAM(setting, 0));
				SetDlgItemInt(hwndDlg, IDC_EDIT_COUNTDOWN, setting, FALSE);
			}
			{
				HWND hwndCombo = GetDlgItem(hwndDlg, IDC_COMBO_COUNTDOWNUNIT);
				DWORD lastUnit = db_get_dw(NULL, "AutoShutdown", "CountdownUnit", SETTING_COUNTDOWNUNIT_DEFAULT);
				SendMessage(hwndCombo, CB_SETLOCALE, (WPARAM)locale, 0); /* sort order */
				SendMessage(hwndCombo, CB_INITSTORAGE, _countof(unitNames), _countof(unitNames) * 16); /* approx. */
				for (int i = 0; i < _countof(unitNames); ++i) {
					int index = SendMessage(hwndCombo, CB_ADDSTRING, 0, (LPARAM)TranslateTS(unitNames[i]));
					if (index != LB_ERR) {
						SendMessage(hwndCombo, CB_SETITEMDATA, index, (LPARAM)unitValues[i]);
						if (i == 0 || unitValues[i] == lastUnit) SendMessage(hwndCombo, CB_SETCURSEL, index, 0);
					}
				}
			}
			{
				DBVARIANT dbv;
				if (!db_get_ts(NULL, "AutoShutdown", "Message", &dbv)) {
					SetDlgItemText(hwndDlg, IDC_EDIT_MESSAGE, dbv.ptszVal);
					mir_free(dbv.ptszVal);
				}
			}
			/* cpuusage threshold */
			{
				BYTE setting = DBGetContactSettingRangedByte(NULL, "AutoShutdown", "CpuUsageThreshold", SETTING_CPUUSAGETHRESHOLD_DEFAULT, 1, 100);
				SendDlgItemMessage(hwndDlg, IDC_SPIN_CPUUSAGE, UDM_SETRANGE, 0, MAKELPARAM(100, 1));
				SendDlgItemMessage(hwndDlg, IDC_EDIT_CPUUSAGE, EM_SETLIMITTEXT, (WPARAM)3, 0);
				SendDlgItemMessage(hwndDlg, IDC_SPIN_CPUUSAGE, UDM_SETPOS, 0, MAKELPARAM(setting, 0));
				SetDlgItemInt(hwndDlg, IDC_EDIT_CPUUSAGE, setting, FALSE);
			}
			/* shutdown types */
			{
				HWND hwndCombo = GetDlgItem(hwndDlg, IDC_COMBO_SHUTDOWNTYPE);
				BYTE lastShutdownType = db_get_b(NULL, "AutoShutdown", "ShutdownType", SETTING_SHUTDOWNTYPE_DEFAULT);
				SendMessage(hwndCombo, CB_SETLOCALE, (WPARAM)locale, 0); /* sort order */
				SendMessage(hwndCombo, CB_SETEXTENDEDUI, TRUE, 0);
				SendMessage(hwndCombo, CB_INITSTORAGE, SDSDT_MAX, SDSDT_MAX * 32);
				for (BYTE shutdownType = 1; shutdownType <= SDSDT_MAX; ++shutdownType)
					if (ServiceIsTypeEnabled(shutdownType, 0)) {
						TCHAR *pszText = (TCHAR*)ServiceGetTypeDescription(shutdownType, GSTDF_TCHAR); /* never fails */
						int index = SendMessage(hwndCombo, CB_ADDSTRING, 0, (LPARAM)pszText);
						if (index != LB_ERR) {
							SendMessage(hwndCombo, CB_SETITEMDATA, index, (LPARAM)shutdownType);
							if (shutdownType == 1 || shutdownType == lastShutdownType) SendMessage(hwndCombo, CB_SETCURSEL, (WPARAM)index, 0);
						}
					}
				SendMessage(hwndDlg, M_UPDATE_SHUTDOWNDESC, 0, (LPARAM)hwndCombo);
			}
			/* check if proto is installed that supports instant messages and check if a message dialog plugin is installed */
			if (!AnyProtoHasCaps(PF1_IMRECV) || !ServiceExists(MS_MSG_SENDMESSAGE)) { /* no srmessage present? */
				CheckDlgButton(hwndDlg, IDC_CHECK_MESSAGE, BST_UNCHECKED);
				EnableWindow(GetDlgItem(hwndDlg, IDC_CHECK_MESSAGE), FALSE);
				EnableWindow(GetDlgItem(hwndDlg, IDC_EDIT_MESSAGE), FALSE);
			}
			/* check if proto is installed that supports file transfers and check if a file transfer dialog is available */
			if (!AnyProtoHasCaps(PF1_FILESEND) && !AnyProtoHasCaps(PF1_FILERECV)) {  /* no srfile present? */
				CheckDlgButton(hwndDlg, IDC_CHECK_FILETRANSFER, BST_UNCHECKED);
				EnableWindow(GetDlgItem(hwndDlg, IDC_CHECK_FILETRANSFER), FALSE);
			}
			/* check if cpu usage can be detected */
			if (!PollCpuUsage(DisplayCpuUsageProc, (LPARAM)GetDlgItem(hwndDlg, IDC_TEXT_CURRENTCPU), 1800)) {
				CheckDlgButton(hwndDlg, IDC_CHECK_CPUUSAGE, BST_UNCHECKED);
				EnableWindow(GetDlgItem(hwndDlg, IDC_CHECK_CPUUSAGE), FALSE);
			}
		}
		SendMessage(hwndDlg, M_ENABLE_SUBCTLS, 0, 0);
		Utils_RestoreWindowPositionNoSize(hwndDlg, NULL, "AutoShutdown", "SettingsDlg_");
		return TRUE; /* default focus */

	case WM_DESTROY:
		Utils_SaveWindowPosition(hwndDlg, NULL, "AutoShutdown", "SettingsDlg_");
		{
			HFONT hFont = (HFONT)SendDlgItemMessage(hwndDlg, IDC_TEXT_HEADER, WM_GETFONT, 0, 0);
			SendDlgItemMessage(hwndDlg, IDC_TEXT_HEADER, WM_SETFONT, 0, FALSE); /* no return value */
			if (hFont != NULL)
				DeleteObject(hFont);
			hwndSettingsDlg = NULL;
		}
		return TRUE;

	case WM_CTLCOLORSTATIC:
		switch (GetDlgCtrlID((HWND)lParam)) {
		case IDC_ICON_HEADER:
			SetBkMode((HDC)wParam, TRANSPARENT);

		case IDC_RECT_HEADER:
			/* need to set COLOR_WINDOW manually for Win9x */
			SetBkColor((HDC)wParam, GetSysColor(COLOR_WINDOW));
			return (INT_PTR)GetSysColorBrush(COLOR_WINDOW);

		case IDC_TEXT_HEADER:
		case IDC_TEXT_HEADERDESC:
			SetBkMode((HDC)wParam, TRANSPARENT);
			return (INT_PTR)GetStockObject(NULL_BRUSH);
		}
		break;

	case M_ENABLE_SUBCTLS:
		{
			BOOL checked = IsDlgButtonChecked(hwndDlg, IDC_CHECK_MESSAGE) != 0;
			EnableDlgItem(hwndDlg, IDC_EDIT_MESSAGE, checked);
			checked = IsDlgButtonChecked(hwndDlg, IDC_CHECK_SPECIFICTIME) != 0;
			EnableDlgItem(hwndDlg, IDC_RADIO_STTIME, checked);
			EnableDlgItem(hwndDlg, IDC_RADIO_STCOUNTDOWN, checked);
			checked = (IsDlgButtonChecked(hwndDlg, IDC_CHECK_SPECIFICTIME) && IsDlgButtonChecked(hwndDlg, IDC_RADIO_STTIME));
			EnableDlgItem(hwndDlg, IDC_TIME_TIMESTAMP, checked);
			EnableDlgItem(hwndDlg, IDC_DATE_TIMESTAMP, checked);
			checked = (IsDlgButtonChecked(hwndDlg, IDC_CHECK_SPECIFICTIME) && IsDlgButtonChecked(hwndDlg, IDC_RADIO_STCOUNTDOWN));
			EnableDlgItem(hwndDlg, IDC_EDIT_COUNTDOWN, checked);
			EnableDlgItem(hwndDlg, IDC_SPIN_COUNTDOWN, checked);
			EnableDlgItem(hwndDlg, IDC_COMBO_COUNTDOWNUNIT, checked);
			checked = IsDlgButtonChecked(hwndDlg, IDC_CHECK_IDLE) != 0;
			EnableDlgItem(hwndDlg, IDC_URL_IDLE, checked);
			checked = IsDlgButtonChecked(hwndDlg, IDC_CHECK_CPUUSAGE) != 0;
			EnableDlgItem(hwndDlg, IDC_EDIT_CPUUSAGE, checked);
			EnableDlgItem(hwndDlg, IDC_SPIN_CPUUSAGE, checked);
			EnableDlgItem(hwndDlg, IDC_TEXT_PERCENT, checked);
			EnableDlgItem(hwndDlg, IDC_TEXT_CURRENTCPU, checked);
			checked = (IsDlgButtonChecked(hwndDlg, IDC_CHECK_SPECIFICTIME) || IsDlgButtonChecked(hwndDlg, IDC_CHECK_MESSAGE) ||
				IsDlgButtonChecked(hwndDlg, IDC_CHECK_IDLE) || IsDlgButtonChecked(hwndDlg, IDC_CHECK_STATUS) ||
				IsDlgButtonChecked(hwndDlg, IDC_CHECK_FILETRANSFER) || IsDlgButtonChecked(hwndDlg, IDC_CHECK_CPUUSAGE));
			EnableDlgItem(hwndDlg, IDOK, checked);
		}
		return TRUE;

	case M_UPDATE_SHUTDOWNDESC: /* lParam=(LPARAM)(HWND)hwndCombo */
		{
			BYTE shutdownType = (BYTE)SendMessage((HWND)lParam, CB_GETITEMDATA, SendMessage((HWND)lParam, CB_GETCURSEL, 0, 0), 0);
			SetDlgItemText(hwndDlg, IDC_TEXT_SHUTDOWNTYPE, (TCHAR*)ServiceGetTypeDescription(shutdownType, GSTDF_LONGDESC | GSTDF_TCHAR));
		}
		return TRUE;

	case WM_TIMECHANGE: /* system time changed */
		SendMessage(hwndDlg, M_CHECK_DATETIME, 0, 0);
		return TRUE;

	case M_CHECK_DATETIME:
		{
			SYSTEMTIME st, stBuf;
			time_t timestamp;
			DateTime_GetSystemtime(GetDlgItem(hwndDlg, IDC_DATE_TIMESTAMP), &stBuf);
			DateTime_GetSystemtime(GetDlgItem(hwndDlg, IDC_TIME_TIMESTAMP), &st);
			st.wDay = stBuf.wDay;
			st.wDayOfWeek = stBuf.wDayOfWeek;
			st.wMonth = stBuf.wMonth;
			st.wYear = stBuf.wYear;
			GetLocalTime(&stBuf);
			if (SystemTimeToTimeStamp(&st, &timestamp)) {
				/* set to current date if earlier */
				if (timestamp < time(NULL)) {
					st.wDay = stBuf.wDay;
					st.wDayOfWeek = stBuf.wDayOfWeek;
					st.wMonth = stBuf.wMonth;
					st.wYear = stBuf.wYear;
					if (SystemTimeToTimeStamp(&st, &timestamp)) {
						/* step one day up if still earlier */
						if (timestamp < time(NULL)) {
							timestamp += 24 * 60 * 60;
							TimeStampToSystemTime(timestamp, &st);
						}
					}
				}
			}
			DateTime_SetRange(GetDlgItem(hwndDlg, IDC_DATE_TIMESTAMP), GDTR_MIN, &stBuf);
			DateTime_SetRange(GetDlgItem(hwndDlg, IDC_TIME_TIMESTAMP), GDTR_MIN, &stBuf);
			DateTime_SetSystemtime(GetDlgItem(hwndDlg, IDC_DATE_TIMESTAMP), GDT_VALID, &st);
			DateTime_SetSystemtime(GetDlgItem(hwndDlg, IDC_TIME_TIMESTAMP), GDT_VALID, &st);
		}
		return TRUE;

	case WM_NOTIFY:
		switch (((NMHDR*)lParam)->idFrom) {
		case IDC_TIME_TIMESTAMP:
		case IDC_DATE_TIMESTAMP:
			switch (((NMHDR*)lParam)->code) {
			case DTN_CLOSEUP:
			case NM_KILLFOCUS:
				PostMessage(hwndDlg, M_CHECK_DATETIME, 0, 0);
				return TRUE;
			}
		}
		break;

	case WM_COMMAND:
		switch (LOWORD(wParam)) {
		case IDC_CHECK_MESSAGE:
		case IDC_CHECK_FILETRANSFER:
		case IDC_CHECK_IDLE:
		case IDC_CHECK_CPUUSAGE:
		case IDC_CHECK_STATUS:
		case IDC_CHECK_SPECIFICTIME:
		case IDC_RADIO_STTIME:
		case IDC_RADIO_STCOUNTDOWN:
			SendMessage(hwndDlg, M_ENABLE_SUBCTLS, 0, 0);
			return TRUE;

		case IDC_EDIT_COUNTDOWN:
			if (HIWORD(wParam) == EN_KILLFOCUS) {
				if ((int)GetDlgItemInt(hwndDlg, IDC_EDIT_COUNTDOWN, NULL, TRUE) < 1) {
					SendDlgItemMessage(hwndDlg, IDC_SPIN_COUNTDOWN, UDM_SETPOS, 0, MAKELPARAM(1, 0));
					SetDlgItemInt(hwndDlg, IDC_EDIT_COUNTDOWN, 1, FALSE);
				}
				return TRUE;
			}
			break;

		case IDC_EDIT_CPUUSAGE:
			if (HIWORD(wParam) == EN_KILLFOCUS) {
				WORD val = (WORD)GetDlgItemInt(hwndDlg, IDC_EDIT_CPUUSAGE, NULL, FALSE);
				if (val < 1) val = 1;
				else if (val>100) val = 100;
				SendDlgItemMessage(hwndDlg, IDC_SPIN_CPUUSAGE, UDM_SETPOS, 0, MAKELPARAM(val, 0));
				SetDlgItemInt(hwndDlg, IDC_EDIT_CPUUSAGE, val, FALSE);
				return TRUE;
			}
			break;

		case IDC_URL_IDLE:
			{
				OPENOPTIONSDIALOG ood;
				ood.cbSize = sizeof(ood);
				ood.pszGroup = "Status"; /* autotranslated */
				ood.pszPage = "Idle"; /* autotranslated */
				ood.pszTab = NULL;
				Options_Open(&ood);
				return TRUE;
			}

		case IDC_COMBO_SHUTDOWNTYPE:
			if (HIWORD(wParam) == CBN_SELCHANGE)
				SendMessage(hwndDlg, M_UPDATE_SHUTDOWNDESC, 0, lParam);
			return TRUE;

		case IDOK: /* save settings and start watcher */
			ShowWindow(hwndDlg, SW_HIDE);
			/* message text */
			{
				HWND hwndEdit = GetDlgItem(hwndDlg, IDC_EDIT_MESSAGE);
				int len = GetWindowTextLength(hwndEdit) + 1;
				TCHAR *pszText = (TCHAR*)mir_alloc(len*sizeof(TCHAR));
				if (pszText != NULL && GetWindowText(hwndEdit, pszText, len + 1)) {
					TrimString(pszText);
					db_set_ts(NULL, "AutoShutdown", "Message", pszText);
				}
				mir_free(pszText); /* does NULL check */
			}
			/* timestamp */
			{
				SYSTEMTIME st;
				time_t timestamp;
				DateTime_GetSystemtime(GetDlgItem(hwndDlg, IDC_TIME_TIMESTAMP), &st); /* time gets synchronized */
				if (!SystemTimeToTimeStamp(&st, &timestamp))
					timestamp = time(NULL);
				db_set_dw(NULL, "AutoShutdown", "TimeStamp", (DWORD)timestamp);
			}
			/* shutdown type */
			{
				int index = SendDlgItemMessage(hwndDlg, IDC_COMBO_SHUTDOWNTYPE, CB_GETCURSEL, 0, 0);
				if (index != LB_ERR)
					db_set_b(NULL, "AutoShutdown", "ShutdownType", (BYTE)SendDlgItemMessage(hwndDlg, IDC_COMBO_SHUTDOWNTYPE, CB_GETITEMDATA, (WPARAM)index, 0));
				index = SendDlgItemMessage(hwndDlg, IDC_COMBO_COUNTDOWNUNIT, CB_GETCURSEL, 0, 0);
				if (index != LB_ERR)
					db_set_dw(NULL, "AutoShutdown", "CountdownUnit", (DWORD)SendDlgItemMessage(hwndDlg, IDC_COMBO_COUNTDOWNUNIT, CB_GETITEMDATA, (WPARAM)index, 0));
				db_set_dw(NULL, "AutoShutdown", "Countdown", (DWORD)GetDlgItemInt(hwndDlg, IDC_EDIT_COUNTDOWN, NULL, FALSE));
				db_set_b(NULL, "AutoShutdown", "CpuUsageThreshold", (BYTE)GetDlgItemInt(hwndDlg, IDC_EDIT_CPUUSAGE, NULL, FALSE));
			}
			/* watcher type */
			{
				WORD watcherType = (WORD)(IsDlgButtonChecked(hwndDlg, IDC_RADIO_STTIME) ? SDWTF_ST_TIME : SDWTF_ST_COUNTDOWN);
				if (IsDlgButtonChecked(hwndDlg, IDC_CHECK_SPECIFICTIME)) watcherType |= SDWTF_SPECIFICTIME;
				if (IsDlgButtonChecked(hwndDlg, IDC_CHECK_MESSAGE)) watcherType |= SDWTF_MESSAGE;
				if (IsDlgButtonChecked(hwndDlg, IDC_CHECK_FILETRANSFER)) watcherType |= SDWTF_FILETRANSFER;
				if (IsDlgButtonChecked(hwndDlg, IDC_CHECK_IDLE)) watcherType |= SDWTF_IDLE;
				if (IsDlgButtonChecked(hwndDlg, IDC_CHECK_STATUS)) watcherType |= SDWTF_STATUS;
				if (IsDlgButtonChecked(hwndDlg, IDC_CHECK_CPUUSAGE)) watcherType |= SDWTF_CPUUSAGE;
				db_set_w(NULL, "AutoShutdown", "WatcherFlags", watcherType);
				ServiceStartWatcher(0, watcherType);
			}
			DestroyWindow(hwndDlg);
			return TRUE;
			// fall through 

		case IDCANCEL: /* WM_CLOSE */
			DestroyWindow(hwndDlg);
			SetShutdownToolbarButton(false);
			SetShutdownMenuItem(false);
			return TRUE;
		}
		break;
	}
	return FALSE;
}
Esempio n. 2
0
// Windows-only at present. Also, you must use the wxNB_FIXEDWIDTH
// style.
void wxNotebook::SetTabSize(const wxSize& sz)
{
    ::SendMessage(GetHwnd(), TCM_SETITEMSIZE, 0, MAKELPARAM(sz.x, sz.y));
}
Esempio n. 3
0
void wxNotebook::OnSize(wxSizeEvent& event)
{
    if ( GetPageCount() == 0 )
    {
        // Prevents droppings on resize, but does cause some flicker
        // when there are no pages.
        Refresh();
        event.Skip();
        return;
    }
#ifndef __WXWINCE__
    else
    {
        // Without this, we can sometimes get droppings at the edges
        // of a notebook, for example a notebook in a splitter window.
        // This needs to be reconciled with the RefreshRect calls
        // at the end of this function, which weren't enough to prevent
        // the droppings.

        wxSize sz = GetClientSize();

        // Refresh right side
        wxRect rect(sz.x-4, 0, 4, sz.y);
        RefreshRect(rect);

        // Refresh bottom side
        rect = wxRect(0, sz.y-4, sz.x, 4);
        RefreshRect(rect);

        // Refresh left side
        rect = wxRect(0, 0, 4, sz.y);
        RefreshRect(rect);
    }
#endif // !__WXWINCE__

    // fit all the notebook pages to the tab control's display area

    RECT rc;
    rc.left = rc.top = 0;
    GetSize((int *)&rc.right, (int *)&rc.bottom);

    // save the total size, we'll use it below
    int widthNbook = rc.right - rc.left,
        heightNbook = rc.bottom - rc.top;

    // there seems to be a bug in the implementation of TabCtrl_AdjustRect(): it
    // returns completely false values for multiline tab controls after the tabs
    // are added but before getting the first WM_SIZE (off by ~50 pixels, see
    //
    // http://sf.net/tracker/index.php?func=detail&aid=645323&group_id=9863&atid=109863
    //
    // and the only work around I could find was this ugly hack... without it
    // simply toggling the "multiline" checkbox in the notebook sample resulted
    // in a noticeable page displacement
    if ( HasFlag(wxNB_MULTILINE) )
    {
        // avoid an infinite recursion: we get another notification too!
        static bool s_isInOnSize = false;

        if ( !s_isInOnSize )
        {
            s_isInOnSize = true;
            SendMessage(GetHwnd(), WM_SIZE, SIZE_RESTORED,
                        MAKELPARAM(rc.right, rc.bottom));
            s_isInOnSize = false;
        }

        // The best size depends on the number of rows of tabs, which can
        // change when the notepad is resized.
        InvalidateBestSize();
    }

#if wxUSE_UXTHEME
    // background bitmap size has changed, update the brush using it too
    UpdateBgBrush();
#endif // wxUSE_UXTHEME

    TabCtrl_AdjustRect(GetHwnd(), false, &rc);

    int width = rc.right - rc.left,
        height = rc.bottom - rc.top;
    size_t nCount = m_pages.Count();
    for ( size_t nPage = 0; nPage < nCount; nPage++ ) {
        wxNotebookPage *pPage = m_pages[nPage];
        pPage->SetSize(rc.left, rc.top, width, height);
    }


    // unless we had already repainted everything, we now need to refresh
    if ( !HasFlag(wxFULL_REPAINT_ON_RESIZE) )
    {
        // invalidate areas not covered by pages
        RefreshRect(wxRect(0, 0, widthNbook, rc.top), false);
        RefreshRect(wxRect(0, rc.top, rc.left, height), false);
        RefreshRect(wxRect(0, rc.bottom, widthNbook, heightNbook - rc.bottom),
                    false);
        RefreshRect(wxRect(rc.right, rc.top, widthNbook - rc.right, height),
                    false);
    }

#if USE_NOTEBOOK_ANTIFLICKER
    // subclass the spin control used by the notebook to scroll pages to
    // prevent it from flickering on resize
    if ( !m_hasSubclassedUpdown )
    {
        // iterate over all child windows to find spin button
        for ( HWND child = ::GetWindow(GetHwnd(), GW_CHILD);
                child;
                child = ::GetWindow(child, GW_HWNDNEXT) )
        {
            wxWindow *childWindow = wxFindWinFromHandle((WXHWND)child);

            // see if it exists, if no wxWindow found then assume it's the spin
            // btn
            if ( !childWindow )
            {
                // subclass the spin button to override WM_ERASEBKGND
                if ( !gs_wndprocNotebookSpinBtn )
                    gs_wndprocNotebookSpinBtn = (WXFARPROC)wxGetWindowProc(child);

                wxSetWindowProc(child, wxNotebookSpinBtnWndProc);
                m_hasSubclassedUpdown = true;
                break;
            }
        }
    }

    // Probably because of the games we play above to avoid flicker sometimes
    // the text controls inside notebook pages are not shown correctly (they
    // don't have their borders) when the notebook is shown for the first time.
    // It's not really clear why does this happen and maybe the bug is in
    // wxTextCtrl itself and not here but updating the page when it's about to
    // be shown doesn't cost much and works around the problem so do it here
    // for now.
    if ( !m_doneUpdateHack && IsShownOnScreen() )
    {
        m_doneUpdateHack = true;
        wxWindow* const page = GetCurrentPage();
        if ( page )
            page->Update();
    }
#endif // USE_NOTEBOOK_ANTIFLICKER

    event.Skip();
}
Esempio n. 4
0
__declspec(dllexport) void download (HWND   parent,
              int    string_size,
              TCHAR   *variables,
              stack_t **stacktop)
{
  char buf[1024];
  char url[1024];
  TCHAR filenameT[1024];
  static char proxy[1024];
  BOOL bSuccess=FALSE;
  int timeout_ms=30000;
  int getieproxy=1;
  int manualproxy=0;
  int translation_version;

  const char *error=NULL;

  // translation version 2 & 1
  static char szDownloading[1024]; // "Downloading %s"
  static char szConnecting[1024];  // "Connecting ..."
  static char szSecond[1024];      // " (1 second remaining)" for v2
                                   // "second" for v1
  static char szMinute[1024];      // " (1 minute remaining)" for v2
                                   // "minute" for v1
  static char szHour[1024];        // " (1 hour remaining)" for v2
                                   // "hour" for v1
  static char szProgress[1024];    // "%skB (%d%%) of %skB at %u.%01ukB/s" for v2
                                   // "%dkB (%d%%) of %dkB at %d.%01dkB/s" for v1

  // translation version 2 only
  static char szSeconds[1024];     // " (%u seconds remaining)"
  static char szMinutes[1024];     // " (%u minutes remaining)"
  static char szHours[1024];       // " (%u hours remaining)"

  // translation version 1 only
  static char szPlural[1024];      // "s";
  static char szRemaining[1024];   // " (%d %s%s remaining)";

  EXDLL_INIT();

  PopStringA(url);
  if (!lstrcmpiA(url, "/TRANSLATE2")) {
    PopStringA(szDownloading);
    PopStringA(szConnecting);
    PopStringA(szSecond);
    PopStringA(szMinute);
    PopStringA(szHour);
    PopStringA(szSeconds);
    PopStringA(szMinutes);
    PopStringA(szHours);
    PopStringA(szProgress);
    PopStringA(url);
    translation_version=2;
  } else if (!lstrcmpiA(url, "/TRANSLATE")) {
    PopStringA(szDownloading);
    PopStringA(szConnecting);
    PopStringA(szSecond);
    PopStringA(szMinute);
    PopStringA(szHour);
    PopStringA(szPlural);
    PopStringA(szProgress);
    PopStringA(szRemaining);
    PopStringA(url);
    translation_version=1;
  } else {
    lstrcpyA(szDownloading, "Downloading %s");
    lstrcpyA(szConnecting, "Connecting ...");
    lstrcpyA(szSecond, " (1 second remaining)");
    lstrcpyA(szMinute, " (1 minute remaining)");
    lstrcpyA(szHour, " (1 hour remaining)");
    lstrcpyA(szSeconds, " (%u seconds remaining)");
    lstrcpyA(szMinutes, " (%u minutes remaining)");
    lstrcpyA(szHours, " (%u hours remaining)");
    lstrcpyA(szProgress, "%skB (%d%%) of %skB at %u.%01ukB/s");
    translation_version=2;
  }
  lstrcpynA(buf, url, 10);
  if (!lstrcmpiA(buf, "/TIMEOUT=")) {
    timeout_ms=my_atoi(url+9);
    PopStringA(url);
  }
  if (!lstrcmpiA(url, "/PROXY")) {
    getieproxy=0;
    manualproxy=1;
    PopStringA(proxy);
    PopStringA(url);
  }
  if (!lstrcmpiA(url, "/NOIEPROXY")) {
    getieproxy=0;
    PopStringA(url);
  }
  popstring(filenameT);

  static char main_buf[8192];
  char *filenameA;
#ifdef _UNICODE
  filenameA = main_buf;
  wsprintfA(filenameA, "%S", filenameT);
#else
  filenameA = filenameT;
#endif

  HANDLE hFile = CreateFile(filenameT,GENERIC_WRITE,FILE_SHARE_READ,NULL,CREATE_ALWAYS,0,NULL);

  if (hFile == INVALID_HANDLE_VALUE)
  {
    wsprintfA(buf, "Unable to open %s", filenameA);
    error = buf;
  }
  else
  {
    if (parent)
    {
      uMsgCreate = RegisterWindowMessage(_T("nsisdl create"));

      lpWndProcOld = (WNDPROC)SetWindowLongPtr(parent,GWLP_WNDPROC,(LONG_PTR)ParentWndProc);

      SendMessage(parent, uMsgCreate, TRUE, (LPARAM) parent);

      // set initial text
      char *p = filenameA;
      while (*p) p++;
      while (*p !='\\' && p != filenameA) p = CharPrevA(filenameA, p);
      wsprintfA(buf, szDownloading, p != filenameA ? p + 1 : p);
      SetDlgItemTextA(childwnd, 1006, buf);
      SetWindowTextA(g_hwndStatic, szConnecting);
    }
    {
      WSADATA wsaData;
      WSAStartup(MAKEWORD(1, 1), &wsaData);

      JNL_HTTPGet *get = 0;

      char *buf = main_buf, *p = NULL;

      HKEY hKey;
      if (getieproxy && RegOpenKeyExA(HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",0,KEY_READ,&hKey) == ERROR_SUCCESS)
      {
        DWORD l = 4;
        DWORD t;
        DWORD v;
        if (RegQueryValueExA(hKey,"ProxyEnable",NULL,&t,(unsigned char*)&v,&l) == ERROR_SUCCESS && t == REG_DWORD && v)
        {
          l=8192;
          if (RegQueryValueExA(hKey,"ProxyServer",NULL,&t,(unsigned char *)buf,&l ) == ERROR_SUCCESS && t == REG_SZ)
          {
            p=strstr(buf,"http=");
            if (!p) p=buf;
            else {
              p+=5;
            }
            char *tp=strstr(p,";");
            if (tp) *tp=0;
            char *p2=strstr(p,"=");
            if (p2) p=0; // we found the wrong proxy
          }
        }
        buf[8192-1]=0;
        RegCloseKey(hKey);
      }
      if (manualproxy == 1) {
        p = proxy;
      }

      DWORD start_time=GetTickCount();
      get=new JNL_HTTPGet(JNL_CONNECTION_AUTODNS,16384,(p&&p[0])?p:NULL);
      int         st;
      int         has_printed_headers = 0;
      __int64     cl = 0;
      int         len;
      __int64     sofar = 0;
      DWORD last_recv_time=start_time;

      get->addheader ("User-Agent: NSISDL/1.2 (Mozilla)");
      get->addheader ("Accept: */*");

      get->connect (url);

      while (1) {
        if (g_cancelled)
            error = "cancel";

        if (error)
        {
          if (parent)
          {
            SendMessage(parent, uMsgCreate, FALSE, (LPARAM) parent);
            SetWindowLongPtr(parent, GWLP_WNDPROC, (LONG_PTR)lpWndProcOld);
          }
          break;
        }

        st = get->run ();

        if (st == -1) {
          lstrcpynA(url, get->geterrorstr(), sizeof(url));
          error = url;
        } else if (st == 1) {
          if (sofar < cl || get->get_status () != 2)
            error="download incomplete";
          else
          {
            bSuccess=TRUE;
            error = "success";
          }
        } else {

          if (get->get_status () == 0) {
            // progressFunc ("Connecting ...", 0);
            if (last_recv_time+timeout_ms < GetTickCount())
              error = "Timed out on connecting.";
            else
              Sleep(10); // don't busy-loop while connecting

          } else if (get->get_status () == 1) {

            progress_callback("Reading headers", 0);
            if (last_recv_time+timeout_ms < GetTickCount())
              error = "Timed out on getting headers.";
            else
              Sleep(10); // don't busy-loop while reading headers

          } else if (get->get_status () == 2) {

            if (! has_printed_headers) {
              has_printed_headers = 1;
              last_recv_time=GetTickCount();

              cl = get->content_length ();
              if (cl == 0)
                error = "Server did not specify content length.";
              else if (g_hwndProgressBar) {
                SendMessage(g_hwndProgressBar, PBM_SETRANGE, 0, MAKELPARAM(0, 30000));
                g_file_size = cl;
              }
            }

            int data_downloaded = 0;
            while ((len = get->bytes_available ()) > 0) {
              data_downloaded++;
              if (len > 8192)
                len = 8192;
              len = get->get_bytes (buf, len);
              if (len > 0) {
                last_recv_time=GetTickCount();
                DWORD dw;
                WriteFile(hFile,buf,len,&dw,NULL);
                sofar += len;
                int time_sofar=(GetTickCount()-start_time)/1000;
                int bps = (int)(sofar/(time_sofar?time_sofar:1));
                int remain = MulDiv64(time_sofar, cl, sofar) - time_sofar;

                if (translation_version == 2) {
                  char *rtext=remain==1?szSecond:szSeconds;;
                  if (remain >= 60)
                  {
                    remain/=60;
                    rtext=remain==1?szMinute:szMinutes;
                    if (remain >= 60)
                    {
                      remain/=60;
                      rtext=remain==1?szHour:szHours;
                    }
                  }

                  char sofar_str[128];
                  char cl_str[128];
                  myitoa64(sofar/1024, sofar_str);
                  myitoa64(cl/1024, cl_str);

                  wsprintfA (buf,
                        szProgress, //%skB (%d%%) of %skB @ %u.%01ukB/s
                        sofar_str,
                        MulDiv64(100, sofar, cl),
                        cl_str,
                        bps/1024,((bps*10)/1024)%10
                        );
                  if (remain) wsprintfA(buf+lstrlenA(buf),rtext,
                        remain
                        );
                } else if (translation_version == 1) {
                  char *rtext=szSecond;
                  if (remain >= 60)
                  {
                    remain/=60;
                    rtext=szMinute;
                    if (remain >= 60)
                    {
                      remain/=60;
                      rtext=szHour;
                    }
                  }

                  wsprintfA (buf,
                        szProgress, //%dkB (%d%%) of %dkB @ %d.%01dkB/s
                        int(sofar/1024),
                        MulDiv64(100, sofar, cl),
                        int(cl/1024),
                        bps/1024,((bps*10)/1024)%10
                        );
                  if (remain) wsprintfA(buf+lstrlenA(buf),szRemaining,
                        remain,
                        rtext,
                        remain==1?"":szPlural
                        );
                }
                progress_callback(buf, sofar);
              } else {
                if (sofar < cl)
                  error = "Server aborted.";
              }
            }
            if (GetTickCount() > last_recv_time+timeout_ms)
            {
              if (sofar != cl)
              {
                error = "Downloading timed out.";
              }
              else
              {
                // workaround for bug #1713562
                //   buggy servers that wait for the client to close the connection.
                //   another solution would be manually stopping when cl == sofar,
                //   but then buggy servers that return wrong content-length will fail.
                bSuccess = TRUE;
                error = "success";
              }
            }
            else if (!data_downloaded)
              Sleep(10);

          } else {
            error = "Bad response status.";
          }
        }

      }

      // Clean up the connection then release winsock
      if (get) delete get;
      WSACleanup();
    }

    CloseHandle(hFile);
  }

  if (g_cancelled || !bSuccess) {
    DeleteFile(filenameT);
  }

  PushStringA(error);
}
Esempio n. 5
0
void logThread(void *dummy)
{
	SetProcessPriorityBoost	(GetCurrentProcess(),TRUE);

	logWindow = CreateDialog(
		HINSTANCE(GetModuleHandle(0)),
	 	MAKEINTRESOURCE(IDD_LOG),
		0, logDlgProc );
	if (!logWindow) {
		R_CHK			(GetLastError());
	};
	SetWindowPos(logWindow,HWND_NOTOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_SHOWWINDOW);
	hwLog		= GetDlgItem(logWindow, IDC_LOG);
	hwProgress	= GetDlgItem(logWindow, IDC_PROGRESS);
	hwInfo		= GetDlgItem(logWindow, IDC_INFO);
	hwStage		= GetDlgItem(logWindow, IDC_STAGE);
	hwTime		= GetDlgItem(logWindow, IDC_TIMING);
	hwPText		= GetDlgItem(logWindow, IDC_P_TEXT);
	hwPhaseTime	= GetDlgItem(logWindow, IDC_PHASE_TIME);

	SendMessage(hwProgress, PBM_SETRANGE,	0, MAKELPARAM(0, 1000)); 
	SendMessage(hwProgress, PBM_SETPOS,		0, 0); 

	Msg("\"LevelBuilder v4.1\" beta build\nCompilation date: %s\n",__DATE__);
	{
		char tmpbuf[128];
		Msg("Startup time: %s",_strtime(tmpbuf));
	}

	BOOL		bHighPriority	= FALSE;
	string256	u_name;
	unsigned long		u_size	= sizeof(u_name)-1;
	GetUserName	(u_name,&u_size);
	_strlwr		(u_name);
	if ((0==xr_strcmp(u_name,"oles"))||(0==xr_strcmp(u_name,"alexmx")))	bHighPriority	= TRUE;

	// Main cycle
	u32		LogSize = 0;
	float	PrSave	= 0;
	while (TRUE)
	{
		SetPriorityClass	(GetCurrentProcess(),IDLE_PRIORITY_CLASS);	// bHighPriority?NORMAL_PRIORITY_CLASS:IDLE_PRIORITY_CLASS

		// transfer data
		while (!csLog.TryEnter())	{
			_process_messages	( );
			Sleep				(1);
		}
		if (progress>1.f)		progress = 1.f;
		else if (progress<0)	progress = 0;

		BOOL bWasChanges = FALSE;
		char tbuf		[256];
		csLog.Enter		();
		if (LogSize!=LogFile->size())
		{
			bWasChanges		= TRUE;
			for (; LogSize<LogFile->size(); LogSize++)
			{
				const char *S = *(*LogFile)[LogSize];
				if (0==S)	S = "";
				SendMessage	( hwLog, LB_ADDSTRING, 0, (LPARAM) S);
			}
			SendMessage		( hwLog, LB_SETTOPINDEX, LogSize-1, 0);
			FlushLog		( );
		}
		csLog.Leave		();
		if (_abs(PrSave-progress)>EPS_L) {
			bWasChanges = TRUE;
			PrSave = progress;
			SendMessage		( hwProgress, PBM_SETPOS, u32(progress*1000.f), 0);

			// timing
			if (progress>0.005f) {
				u32 dwCurrentTime = timeGetTime();
				u32 dwTimeDiff	= dwCurrentTime-phase_start_time;
				u32 secElapsed	= dwTimeDiff/1000;
				u32 secRemain		= u32(float(secElapsed)/progress)-secElapsed;
				sprintf(tbuf,
					"Elapsed: %s\n"
					"Remain:  %s",
					make_time(secElapsed).c_str(),
					make_time(secRemain).c_str()
					);
				SetWindowText	( hwTime, tbuf );
			} else {
				SetWindowText	( hwTime, "" );
			}

			// percentage text
			sprintf(tbuf,"%3.2f%%",progress*100.f);
			SetWindowText	( hwPText, tbuf );
		}

		if (bStatusChange) {
			bWasChanges		= TRUE;
			bStatusChange	= FALSE;
			SetWindowText	( hwInfo,	status);
		}
		if (bWasChanges) {
			UpdateWindow	( logWindow);
			bWasChanges		= FALSE;
		}
		csLog.Leave			();

		_process_messages	();
		if (bClose)			break;
		Sleep				(200);
	}

	// Cleanup
	DestroyWindow(logWindow);
}
Esempio n. 6
0
/*!
	Set the dialog's default pushbutton
	\param pDialog Dialog to set the default pushbutton
	\param nID Button ID to make default
	\note It fixes the drawing problem that sometimes occurs when using plain CDialog::SetDefID,
	see also MS kb Q67655 (<A HREF="http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q67655&">
	HOWTO: Change or Set the Default Push Button in a Dialog Box</A>)
*/
void COddButton::SetDefID(CDialog* pDialog, const UINT nID)
{
	if( !pDialog || !::IsWindow(pDialog->m_hWnd) )
	{
		ASSERT(FALSE); // Bad pointer or dialog is not a window
		return;
	}

	// get the current default button
	const DWORD dwPrevDefID = pDialog->GetDefID();
	const UINT nPrevID = (HIWORD(dwPrevDefID) == DC_HASDEFID) ? LOWORD(dwPrevDefID) : 0;
		
	/*
	 *	Set the new default ID in the dialog
	 */
	pDialog->SetDefID(nID);

	/*
	 *	Make sure the previous default button doesn't have the default state anymore
	 */

	// check previous ID is a default-compatible button
	// and it has the default state
	LRESULT lRes = (nPrevID == 0) ? 0 : pDialog->SendDlgItemMessage(nPrevID, WM_GETDLGCODE);
	if( (lRes & DLGC_BUTTON) && 
		(lRes & DLGC_DEFPUSHBUTTON) )
	{
		pDialog->SendDlgItemMessage(nPrevID, BM_SETSTYLE,
			BS_PUSHBUTTON, MAKELPARAM(TRUE, 0));
	}
	
	/*
	 *	Make sure the new default button receives the default state
	 */

	// check new ID is a button
	lRes = (nID == 0) ? 0 : pDialog->SendDlgItemMessage(nID, WM_GETDLGCODE);
	if( lRes & DLGC_BUTTON )
	{
		// exception: current focused button should keep its default state (IMHO)
		CWnd* pFocusWnd = GetFocus();
		LRESULT lResFocus = (pFocusWnd == NULL) ? 0 : pFocusWnd->SendMessage(WM_GETDLGCODE);

		// check focused control is a default-compatible button
		if( (lResFocus & DLGC_BUTTON) && 
			(lResFocus & (DLGC_DEFPUSHBUTTON | DLGC_UNDEFPUSHBUTTON)) )
		{
			// remove default state (if needed)
			if( (lRes & DLGC_DEFPUSHBUTTON) && 
				(nID != (UINT)pFocusWnd->GetDlgCtrlID()) )
			{
				pDialog->SendDlgItemMessage(nID, BM_SETSTYLE,
					BS_PUSHBUTTON, MAKELPARAM(TRUE, 0));
			}

			// set default state (if needed)
			if( lResFocus & DLGC_UNDEFPUSHBUTTON )
			{
				pFocusWnd->SendMessage(BM_SETSTYLE,
					BS_DEFPUSHBUTTON, MAKELPARAM(TRUE, 0));
			}
		}
		else if( lRes & DLGC_UNDEFPUSHBUTTON )
		{
			// not default-compatible button has the focus
			// set default state
			pDialog->SendDlgItemMessage(nID, BM_SETSTYLE,
				BS_DEFPUSHBUTTON, MAKELPARAM(TRUE, 0));
		}
	}
}
Esempio n. 7
0
/**
 * Program start point, build the windows GUI, initialise the emulator.
 * Enter the program main loop, and tidy up when finished.
 */
int WINAPI WinMain (HINSTANCE hThisInstance,
                    HINSTANCE hPrevInstance,
                    LPSTR lpszArgument,
                    int nFunsterStil)

{
        static const char szClassName[] = "WindowsApp";
        MSG messages = {0};     /**< Here messages to the application are saved */
        WNDCLASSEX wincl;       /**< Data structure for the windowclass */

        hinstance=hThisInstance;

        /* The Window structure */
        wincl.hInstance = hThisInstance;
        wincl.lpszClassName = szClassName;
        wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
        wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
        wincl.cbSize = sizeof (WNDCLASSEX);

        /* Use custom icon and default mouse-pointer */
        wincl.hIcon = LoadIcon(hThisInstance, "allegro_icon");
        wincl.hIconSm = LoadIcon(hThisInstance, "allegro_icon");
        wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
        wincl.lpszMenuName = NULL;                 /* No menu */
        wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
        wincl.cbWndExtra = 0;                      /* structure or the window instance */
        /* Use Windows's default color as the background of the window */
        wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;

        /* Register the window class, and if it fails quit the program */
        if (!RegisterClassEx (&wincl))
           return 0;

        /* Load Menu from resources file */
        menu=LoadMenu(hThisInstance,TEXT("MainMenu"));

        /* Add in CDROM links to the settings menu dynamically */
        initmenu();

        /* The class is registered, let's create the program*/
        ghwnd = CreateWindowEx (
           0,                   /* Extended possibilites for variation */
           szClassName,         /* Classname */
           "RPCEmu v" VERSION,      /* Title Text */
           WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX, /* overlapped window with no sizing frame */
           CW_USEDEFAULT,       /* Windows decides the position */
           CW_USEDEFAULT,       /* where the window ends up on the screen */
           640 + (GetSystemMetrics(SM_CXFIXEDFRAME) * 2), /* The window width */
           480 + (GetSystemMetrics(SM_CYFIXEDFRAME) * 2) + GetSystemMetrics(SM_CYMENU) + GetSystemMetrics(SM_CYCAPTION), /* and height in pixels */
           HWND_DESKTOP,        /* The window is a child-window to desktop */
           menu,                /* Menu handle */
           hThisInstance,       /* Program Instance handler */
           NULL                 /* No Window Creation data */
           );

        /* Make the window visible on the screen */
        ShowWindow (ghwnd, nFunsterStil);
        win_set_window(ghwnd);

        allegro_init();     /* allegro */

	/* Allegro does not appear to read the window position until it
	   receives a window move message. This results in the mousehack
	   pointer being offset incorrectly until the window is moved.

	   To workaround this issue, we generate a window move message to the
	   window's current position.
	 */
	{
		WINDOWINFO wi;

		GetWindowInfo(ghwnd, &wi);
		PostMessage(ghwnd, WM_MOVE, 0, MAKELPARAM(wi.rcClient.left, wi.rcClient.top));
	}

        /* Initialise the emulation and read the config file */
        if (startrpcemu())
           return -1;

        /* Initialise the podules */
        opendlls();

        /* Based on the contents of config file, dynamically update the Windows GUI items */
        if (config.cdromtype > 2) {
                WindowProcedure(ghwnd, WM_COMMAND, IDM_CDROM_DISABLED + config.cdromtype, 0);
        }
        CheckMenuItem(menu, IDM_CDROM_DISABLED + config.cdromtype, MF_CHECKED);

        CheckMenuItem(menu, IDM_MOUSE_TWOBUTTON,
                      config.mousetwobutton ? MF_CHECKED : MF_UNCHECKED);
        CheckMenuItem(menu, IDM_CPUIDLE,
                      config.cpu_idle ? MF_CHECKED : MF_UNCHECKED);
        
        if (config.mousehackon) {
                CheckMenuItem(menu, IDM_MOUSE_FOL, MF_CHECKED);
        } else {
                CheckMenuItem(menu, IDM_MOUSE_CAP, MF_CHECKED);
        }

        /* Return the mouse clipping to normal on program exit */
        atexit(releasemousecapture);

//        SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
        install_int_ex(vblupdate, BPS_TO_TIMER(config.refresh));
        drawscre=0;

        /* Program main loop */
        while (!quited)
        {
                /* Execute the emulation */
                execrpcemu();

                /* Update title with mips speed */
                if (updatemips)
                {
                        char title[128];

                        if (mousehack) {
                               sprintf(title, "RPCEmu v" VERSION " - MIPS: %.1f, AVG: %.1f",
                                       perf.mips, perf.mips_total / perf.mips_count);
                        } else {
                               sprintf(title, "RPCEmu v" VERSION " - MIPS: %.1f, AVG: %.1f - %s",
                                       perf.mips, perf.mips_total / perf.mips_count,
                                       (mousecapture) ?
                                           "Press CTRL-END to release mouse" :
                                           "Click to capture mouse");
                        }
                        SetWindowText(ghwnd, title);
                        updatemips=0;
                }

		if (handle_sigio) {
			handle_sigio = 0;
			sig_io(1);
		}

                /* Exit full screen? */
                if ((key[KEY_LCONTROL] || key[KEY_RCONTROL]) && key[KEY_END] && fullscreen)
                {
                        togglefullscreen(0);
                        mousecapture=0;
                }

                /* Release mouse from mouse capture mode? */
                if ((key[KEY_LCONTROL] || key[KEY_RCONTROL]) && key[KEY_END] && mousecapture && !config.mousehackon)
                {
                        ClipCursor(&oldclip);
                        mousecapture=0;
                        updatemips=1;
                }

                /* Handle Windows events */
                if (PeekMessage(&messages,NULL,0,0,PM_REMOVE))
                {
                        if (messages.message==WM_QUIT)
                        {
                                quited=1;
                        }
                        /* Translate virtual-key messages into character messages */
                        TranslateMessage(&messages);
                        /* Send message to WindowProcedure */
                        DispatchMessage(&messages);
                }
        }

        /* Program has exited. Tidy up */
        endrpcemu();
        
        /* The program return-value is 0 - The value that PostQuitMessage() gave */
        return messages.wParam;
}
Esempio n. 8
0
//---------------------------------------------------------------------
// メッセージボックスのプロシージャ
LRESULT CALLBACK MyMessageBoxProc(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp)
{
	
	static LPMSGBOXDATA lpMsgBoxData;
	static HICON hIcon;
	static BOOL bDrawIcon; // アイコンを貼るかどうか
	static RECT textRt;  // テキスト描画領域
	static SIZE sizeText; //  テキスト描画領域のサイズ
	static LONG width,height; // ウィンドウ幅、高さ
	static HWND hWndBt[3];
	static int nResult[3];
	static HFONT hFont; // ボタン用フォント
	static LONG nButtonNum; // ボタン数
	static BOOL bOwnerDraw; // ボタンをオーナードローするか
	static UINT uCurFocus; // 現在のフォーカスボタンID
	
	CHAR szBtStr[3][CHR_BUF];
	LONG x1,x2,x3,y;
	HINSTANCE hInst;
	HDC hDC;
	LONG nButtonSize;
	UINT uIconType,uMskType;
	DWORD dwStyle;
	COLORREF rgbStr;
	WORD i;
	
	switch (msg) {
		
	case WM_INITDIALOG:  // ダイアログ初期化
		
		lpMsgBoxData = (LPMSGBOXDATA)lp;
		hInst = (HINSTANCE)GetWindowLong(hWnd, GWL_HINSTANCE);
		
		// アイコンロード
		uIconType = lpMsgBoxData->uType & MB_ICONMASK;
		
		if(uIconType > 0) bDrawIcon = TRUE;
		else bDrawIcon = FALSE;
		
		switch(uIconType){
			
		case MB_ICONQUESTION:
			hIcon = LoadIcon(NULL,IDI_QUESTION);
			break;
			
		case MB_ICONINFORMATION:
			hIcon = LoadIcon(NULL,IDI_INFORMATION);
			break;
			
		case MB_ICONEXCLAMATION:
			hIcon = LoadIcon(NULL,IDI_EXCLAMATION);
			break;
			
		case MB_ICONERROR:
			hIcon = LoadIcon(NULL,IDI_ERROR);
		}
		
		
		// テキスト領域の幅と高さ取得
		GetTextSize(hWnd,lpMsgBoxData->lpText,&sizeText,MSGBOXTEXTSIZE);
		
		// テキスト描画領域セット
		textRt.top = MSGBOXMERGIN + (sizeText.cy > MSGBOXICONHEIGHT? 0 : (MSGBOXICONHEIGHT-sizeText.cy)/2);
		textRt.left = MSGBOXICONWIDTH*bDrawIcon+MSGBOXMERGIN;
		textRt.right = textRt.left + sizeText.cx;
		textRt.bottom = textRt.top + sizeText.cy;
		
		// タイトルセット
		SetWindowText(hWnd,lpMsgBoxData->lpCaption);
		
		// ボタン名設定
		for(i=0;i<3;i++) nResult[i] = 0;
		switch(lpMsgBoxData->uType & MB_TYPEMASK){
			
		default:
			nResult[0] = IDOK;
			wsprintf(szBtStr[0],"OK");
			
			nButtonNum = 1;
			break;
			
		case MB_OKCANCEL:
			nResult[0] = IDOK;
			wsprintf(szBtStr[0],"OK");
			
			nResult[1] = IDCANCEL;
			wsprintf(szBtStr[1],"キャンセル");
			
			nButtonNum = 2;
			break;
			
		case MB_YESNOCANCEL:
			
			nResult[0] = IDYES;
			wsprintf(szBtStr[0],"はい(&Y)");
			
			nResult[1] = IDNO;
			wsprintf(szBtStr[1],"いいえ(&N)");
			
			nResult[2] = IDCANCEL;
			wsprintf(szBtStr[2],"キャンセル");
			
			nButtonNum = 3;
			break;
			
		case MB_YESNO:
			
			nResult[0] = IDYES;
			wsprintf(szBtStr[0],"はい(&Y)");
			
			nResult[1] = IDNO;
			wsprintf(szBtStr[1],"いいえ(&N)");
			
			nButtonNum = 2;
		}
		
		// ウィンドウリサイズ
		nButtonSize =MSGBOXBTWIDTH*nButtonNum+MSGBOXMERGIN*(nButtonNum-1);
		
		width = max(nButtonSize+MSGBOXMERGIN*2,sizeText.cx+MSGBOXMERGIN*2+MSGBOXICONWIDTH*bDrawIcon);
		height = max(MSGBOXICONHEIGHT*bDrawIcon,sizeText.cy)+ MSGBOXMERGIN*3+MSGBOXBTHEIGHT;
		
		SetWindowPos(hWnd,NULL,0,0,
			width+GetSystemMetrics(SM_CXFIXEDFRAME)*2,
			height+GetSystemMetrics(SM_CYCAPTION)+GetSystemMetrics(SM_CYFIXEDFRAME)*2
			,SWP_NOMOVE|SWP_NOREPOSITION);
		
		
		// ボタン作成
		x1 = (width - nButtonSize)/2;
		x2 = x1 + MSGBOXBTWIDTH+MSGBOXMERGIN;
		x3 = x2 + MSGBOXBTWIDTH+MSGBOXMERGIN;
		y = height-MSGBOXBTHEIGHT - MSGBOXMERGIN;
		
		uMskType = lpMsgBoxData->uType & MB_DEFMASK;
		bOwnerDraw = lpMsgBoxData->bOwnerDraw; // オーナードローか
		
		// ボタン 1
		if((nButtonNum >=2 && uMskType == MB_DEFBUTTON2) ||
			(nButtonNum == 3 && uMskType == MB_DEFBUTTON3))
			dwStyle = WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON|WS_TABSTOP;
		else dwStyle = WS_CHILD|WS_VISIBLE|BS_DEFPUSHBUTTON|WS_TABSTOP;
		if(bOwnerDraw) dwStyle |= BS_OWNERDRAW;
		CreateWindow("BUTTON","bt1",dwStyle,x1,y,MSGBOXBTWIDTH,MSGBOXBTHEIGHT,hWnd,(HMENU)IDC_BT1,hInst,NULL);
		
		// ボタン 2
		if(nButtonNum >= 2){
			if(uMskType == MB_DEFBUTTON2)
				dwStyle = WS_CHILD|WS_VISIBLE|BS_DEFPUSHBUTTON|WS_TABSTOP;
			else dwStyle = WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON|WS_TABSTOP;
			if(bOwnerDraw) dwStyle |= BS_OWNERDRAW;
			CreateWindow("BUTTON","bt2",dwStyle,x2,y,MSGBOXBTWIDTH,MSGBOXBTHEIGHT,hWnd,(HMENU)IDC_BT2,hInst,NULL);
		}
		
		
		// ボタン 3
		if(nButtonNum == 3){
			if(uMskType == MB_DEFBUTTON3)
				dwStyle = WS_CHILD|WS_VISIBLE|BS_DEFPUSHBUTTON|WS_TABSTOP;
			else dwStyle = WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON|WS_TABSTOP;
			if(bOwnerDraw) dwStyle |= BS_OWNERDRAW;
			CreateWindow("BUTTON","bt3",dwStyle,x3,y,MSGBOXBTWIDTH,MSGBOXBTHEIGHT,hWnd,(HMENU)IDC_BT3,hInst,NULL);
		}
		
		
		// ボタン用フォント作成
		if(!bOwnerDraw) hFont=CreateFont(10,0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET
			,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH,"MS Pゴシック");
		
		// ボタンにフォントと文字セット
		hWndBt[0] = GetDlgItem(hWnd,IDC_BT1);
		hWndBt[1] = GetDlgItem(hWnd,IDC_BT2);
		hWndBt[2] = GetDlgItem(hWnd,IDC_BT3);
		
		for(i=0;i<3;i++)
		{
			// フォントセット
			if(!bOwnerDraw) SendMessage(hWndBt[i],WM_SETFONT,(WPARAM)hFont,(LPARAM)MAKELPARAM(TRUE,0));
			SetWindowText(hWndBt[i],szBtStr[i]);
		}
		
		// フォーカス移動
		switch(uMskType){
			
		case MB_DEFBUTTON2:
			uCurFocus = IDC_BT2;
			SetFocus(hWndBt[1]);
			break;
			
		case MB_DEFBUTTON3:
			uCurFocus = IDC_BT3;
			SetFocus(hWndBt[2]);
			break;
			
		default:
			uCurFocus = IDC_BT1;
			SetFocus(hWndBt[0]);
		}
		
		// 中心移動
		SetDlgCenter(hWnd);

		// forgrand
		if(lpMsgBoxData->uType & MB_SETFOREGROUND) SetForegroundWindow(hWnd);
		
		break;
		
		
		case WM_CTLCOLORDLG: // 背景色を変えたい場合
			
			if(bOwnerDraw){
				SetBkMode((HDC)wp,TRANSPARENT);			 
				SetTextColor((HDC)wp,RGB(255,255,255)) ;
				return ((BOOL)GetStockObject(GRAY_BRUSH)) ;    
			}
			
			break;
			
			
		case WM_DRAWITEM: // ボタンのオーナー描画をする場合
			
			if(bOwnerDraw){
				
				UINT uCtlID,uButtonStat;
				LPDRAWITEMSTRUCT lpDrawItem;
				
				uCtlID = (UINT)wp;
				lpDrawItem = (LPDRAWITEMSTRUCT)lp;
				uButtonStat = MYID_RELEASEBUTTON;
				
				if(lpDrawItem->CtlType == ODT_BUTTON){ // ボタンならば
					
					if(lpDrawItem->itemAction & ODA_SELECT){ // 選択
						if(lpDrawItem->itemState & ODS_FOCUS) uButtonStat = MYID_PUSHBUTTON;
					}
					else if(lpDrawItem->itemAction & ODA_FOCUS){ // フォーカス
						// 自前でフォーカスの管理をする
						if(lpDrawItem->itemState & ODS_FOCUS) uCurFocus = uCtlID;
					}
					
					// ボタン描画
					DrawMsgButton(hWnd,uCtlID,lpDrawItem->hDC,lpDrawItem->rcItem,uCurFocus,uButtonStat);
					
				}
			}
			
			break;
			
		case WM_PAINT: // 描画
			
			hDC = GetDC(hWnd);
			
			if(bOwnerDraw){
				// 枠描画
				DrawMyFrame(hDC,MSGBOXMERGIN-2,MSGBOXMERGIN-2,
					width - (MSGBOXMERGIN-2)*2,height-MSGBOXBTHEIGHT - MSGBOXMERGIN-(MSGBOXMERGIN-2)*2
					,RGB(0,0,0));
				rgbStr = RGB(255,255,255);
			}
			else rgbStr = RGB(0,0,0);
			
			// アイコン
			if(bDrawIcon)
				DrawIcon(hDC,MSGBOXMERGIN+1,MSGBOXMERGIN+1,hIcon);
			
			// テキスト
			DrawMyStringJP(hDC,lpMsgBoxData->lpText,
				textRt.left,textRt.top,textRt.right-textRt.left,
				textRt.bottom-textRt.top,MSGBOXTEXTSIZE,rgbStr);
			
			
			ReleaseDC(hWnd,hDC);
			
			break;
			
			
		case WM_SETTEXT: // ダイアログのタイトル変更
			
			// DefWindowProc に処理してもらう(なんか胡散臭いやり方 (^^; )
			return(DefWindowProc(hWnd, msg, wp, lp)); 
			
			break;
			
		case WM_COMMAND:
			
			// オーナードローの時はコントロール ID をもらえないので
			// 自前でフォーカス管理をする
			if(bOwnerDraw && HIWORD(wp)== BN_CLICKED) wp = uCurFocus;
			
			switch (LOWORD(wp)) {
				
			case IDC_BT1: 
				if(!bOwnerDraw) DeleteObject(hFont);
				EndDialog(hWnd, nResult[0]);
				return TRUE;
				
			case IDC_BT2: 
				if(!bOwnerDraw) DeleteObject(hFont);
				EndDialog(hWnd, nResult[1]);
				return TRUE;
				
			case IDC_BT3: 
				if(!bOwnerDraw) DeleteObject(hFont);
				EndDialog(hWnd, nResult[2]);
				return TRUE;
				
			case IDCANCEL: 
				if(!bOwnerDraw) DeleteObject(hFont);
				EndDialog(hWnd, IDCANCEL);
				return TRUE;
				
			}
			break;
			
			default:
				break;
	}
    return FALSE;
}
Esempio n. 9
0
NOEXPORT LRESULT CALLBACK window_proc(HWND main_window_handle,
        UINT message, WPARAM wParam, LPARAM lParam) {
    NOTIFYICONDATA nid;
    POINT pt;
    RECT rect;
    SERVICE_OPTIONS *section;
    unsigned int section_number;

#if 0
    if(message!=WM_CTLCOLORSTATIC && message!=WM_TIMER)
        s_log(LOG_DEBUG, "Window message: %d", message);
#endif
    switch(message) {
    case WM_CREATE:
#ifdef _WIN32_WCE
        /* create command bar */
        command_bar_handle=CommandBar_Create(ghInst, main_window_handle, 1);
        if(!command_bar_handle)
            error_box("CommandBar_Create");
        if(!CommandBar_InsertMenubar(command_bar_handle, ghInst, IDM_MAINMENU, 0))
            error_box("CommandBar_InsertMenubar");
        if(!CommandBar_AddAdornments(command_bar_handle, 0, 0))
            error_box("CommandBar_AddAdornments");
#endif

        /* create child edit window */
        edit_handle=CreateWindow(TEXT("EDIT"), NULL,
            WS_CHILD|WS_VISIBLE|WS_HSCROLL|WS_VSCROLL|ES_MULTILINE|ES_READONLY,
            0, 0, 0, 0, main_window_handle, (HMENU)IDE_EDIT, ghInst, NULL);
#ifndef _WIN32_WCE
        SendMessage(edit_handle, WM_SETFONT,
            (WPARAM)CreateFont(-12, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE,
                DEFAULT_CHARSET, OUT_RASTER_PRECIS, CLIP_DEFAULT_PRECIS,
                PROOF_QUALITY, DEFAULT_PITCH, TEXT("Courier")),
            MAKELPARAM(FALSE, 0)); /* no need to redraw right, now */
#endif
        /* NOTE: there's no return statement here -> proceeding with resize */

    case WM_SIZE:
        GetClientRect(main_window_handle, &rect);
#ifdef _WIN32_WCE
        MoveWindow(edit_handle, 0, CommandBar_Height(command_bar_handle),
            rect.right, rect.bottom-CommandBar_Height(command_bar_handle), TRUE);
#else
        MoveWindow(edit_handle, 0, 0, rect.right, rect.bottom, TRUE);
#endif
        UpdateWindow(edit_handle);
        /* CommandBar_Show(command_bar_handle, TRUE); */
        return TRUE;

    case WM_SETFOCUS:
        SetFocus(edit_handle);
        return TRUE;

    case WM_TIMER:
        if(visible)
            update_logs();
        return TRUE;

    case WM_CLOSE:
        ShowWindow(main_window_handle, SW_HIDE);
        return TRUE;

    case WM_SHOWWINDOW:
        visible=wParam; /* setup global variable */
        if(tray_menu_handle)
            CheckMenuItem(tray_menu_handle, IDM_SHOW_LOG,
                visible ? MF_CHECKED : MF_UNCHECKED);
        if(visible)
            update_logs();
        return TRUE;

    case WM_DESTROY:
#ifdef _WIN32_WCE
        CommandBar_Destroy(command_bar_handle);
#else
        if(main_menu_handle)
            DestroyMenu(main_menu_handle);
#endif
        if(tray_menu_handle)
            DestroyMenu(tray_menu_handle);
        ZeroMemory(&nid, sizeof nid);
        nid.cbSize=sizeof nid;
        nid.hWnd=main_window_handle;
        nid.uID=1;
        nid.uFlags=NIF_TIP; /* not really sure what to put here, but it works */
        Shell_NotifyIcon(NIM_DELETE, &nid); /* this removes the icon */
        PostQuitMessage(0);
        KillTimer(main_window_handle, 0x29a);
        return TRUE;

    case WM_COMMAND:
        if(wParam>=IDM_PEER_MENU && wParam<IDM_PEER_MENU+number_of_sections) {
            for(section=service_options.next, section_number=0;
                    section && wParam!=IDM_PEER_MENU+section_number;
                    section=section->next, ++section_number)
                ;
            if(!section)
                return TRUE;
            if(save_text_file(section->file, section->chain))
                return TRUE;
#ifndef _WIN32_WCE
            if(main_menu_handle)
                CheckMenuItem(main_menu_handle, wParam, MF_CHECKED);
#endif
            if(tray_menu_handle)
                CheckMenuItem(tray_menu_handle, wParam, MF_CHECKED);
            message_box(section->help, MB_ICONINFORMATION);
            return TRUE;
        }
        switch(wParam) {
        case IDM_ABOUT:
            DialogBox(ghInst, TEXT("AboutBox"), main_window_handle,
                (DLGPROC)about_proc);
            break;
        case IDM_SHOW_LOG:
            if(visible) {
                ShowWindow(main_window_handle, SW_HIDE); /* hide window */
            } else {
                ShowWindow(main_window_handle, SW_SHOWNORMAL); /* show window */
                SetForegroundWindow(main_window_handle); /* bring on top */
            }
            break;
        case IDM_CLOSE:
            ShowWindow(main_window_handle, SW_HIDE); /* hide window */
            break;
        case IDM_EXIT:
            if(!error_mode) /* signal_pipe is active */
                signal_post(SIGNAL_TERMINATE);
            DestroyWindow(main_window_handle);
            break;
        case IDM_SAVE_LOG:
            if(!cmdline.service) /* security */
                save_log();
            break;
        case IDM_EDIT_CONFIG:
#ifndef _WIN32_WCE
            if(!cmdline.service) /* security */
                edit_config(main_window_handle);
#endif
            break;
        case IDM_RELOAD_CONFIG:
            if(error_mode) /* unlock daemon_thread */
                SetEvent(config_ready);
            else /* signal_pipe is active */
                signal_post(SIGNAL_RELOAD_CONFIG);
            break;
        case IDM_REOPEN_LOG:
            signal_post(SIGNAL_REOPEN_LOG);
            break;
        case IDM_MANPAGE:
#ifndef _WIN32_WCE
            if(!cmdline.service) /* security */
                ShellExecute(main_window_handle, TEXT("open"),
                    TEXT("stunnel.html"), NULL, NULL, SW_SHOWNORMAL);
#endif
            break;
        case IDM_HOMEPAGE:
#ifndef _WIN32_WCE
            if(!cmdline.service) /* security */
                ShellExecute(main_window_handle, TEXT("open"),
                    TEXT("http://www.stunnel.org/"), NULL, NULL, SW_SHOWNORMAL);
#endif
            break;
        }
        return TRUE;

    case WM_SYSTRAY: /* a taskbar event */
        switch(lParam) {
#ifdef _WIN32_WCE
        case WM_LBUTTONDOWN: /* no right mouse button on Windows CE */
            GetWindowRect(GetDesktopWindow(), &rect); /* no cursor position */
            pt.x=rect.right;
            pt.y=rect.bottom-25;
#else
        case WM_RBUTTONDOWN:
            GetCursorPos(&pt);
#endif
            SetForegroundWindow(main_window_handle);
            TrackPopupMenuEx(GetSubMenu(tray_menu_handle, 0), TPM_BOTTOMALIGN,
                pt.x, pt.y, main_window_handle, NULL);
            PostMessage(main_window_handle, WM_NULL, 0, 0);
            break;
#ifndef _WIN32_WCE
        case WM_LBUTTONDBLCLK: /* switch log window visibility */
            if(visible) {
                ShowWindow(main_window_handle, SW_HIDE); /* hide window */
            } else {
                ShowWindow(main_window_handle, SW_SHOWNORMAL); /* show window */
                SetForegroundWindow(main_window_handle); /* bring on top */
            }
            break;
#endif
        }
        return TRUE;

    case WM_VALID_CONFIG:
        valid_config();
        return TRUE;

    case WM_INVALID_CONFIG:
        invalid_config();
        return TRUE;

    case WM_LOG:
        win_log((LPSTR)wParam);
        return TRUE;

    case WM_NEW_CHAIN:
#ifndef _WIN32_WCE
        if(main_menu_handle)
            EnableMenuItem(main_menu_handle, IDM_PEER_MENU+wParam, MF_ENABLED);
#endif
        if(tray_menu_handle)
            EnableMenuItem(tray_menu_handle, IDM_PEER_MENU+wParam, MF_ENABLED);
        return TRUE;

    case WM_CLIENTS:
        update_tray_icon((int)wParam);
        return TRUE;
    }

    return DefWindowProc(main_window_handle, message, wParam, lParam);
}
Esempio n. 10
0
/////////////////////////////////////////////////////////////////////////////
//
//Method......: OnLButtonDblClk
//Class.......: CHSShadeButton
//
//Author......: Milan Gardian
//Created.....: MAR-2001
//
//Return value: NONE
//Parameters..: Used only to be forwarded as WM_LBUTTONDOWN message parameters
//Exceptions..: NONE
//------------
//Description :
//
//  > We do not care about doublelicks - handle this event
//    like an ordinary left-button-down event
//
//---------------------------------------------------------
void CHSShadeButton::OnLButtonDblClk(UINT flags, CPoint point) 
{
    SendMessage(WM_LBUTTONDOWN, flags, MAKELPARAM(point.x, point.y));
}
Esempio n. 11
0
	LRESULT CComboWnd::HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
	{
		if( uMsg == WM_CREATE ) {
			m_pm.SetForceUseSharedRes(true);
			m_pm.Init(m_hWnd);
			// The trick is to add the items to the new container. Their owner gets
			// reassigned by this operation - which is why it is important to reassign
			// the items back to the righfull owner/manager when the window closes.
			m_pLayout = new CVerticalLayoutUI;
			m_pLayout->SetManager(&m_pm, NULL, true);
			LPCTSTR pDefaultAttributes = m_pOwner->GetManager()->GetDefaultAttributeList(_T("VerticalLayout"));
			if( pDefaultAttributes ) {
				m_pLayout->ApplyAttributeList(pDefaultAttributes);
			}
			m_pLayout->SetInset(CDuiRect(1, 1, 1, 1));
			m_pLayout->SetBkColor(0xFFFFFFFF);
			m_pLayout->SetBorderColor(0xFFC6C7D2);
			m_pLayout->SetBorderSize(1);
			m_pLayout->SetAutoDestroy(false);
			m_pLayout->EnableScrollBar();
			m_pLayout->ApplyAttributeList(m_pOwner->GetDropBoxAttributeList());
			for( int i = 0; i < m_pOwner->GetCount(); i++ ) {
				m_pLayout->Add(static_cast<CControlUI*>(m_pOwner->GetItemAt(i)));
			}
			m_pm.AttachDialog(m_pLayout);
			m_pm.AddNotifier(this);
			return 0;
		}
		else if( uMsg == WM_CLOSE ) {
			m_pOwner->SetManager(m_pOwner->GetManager(), m_pOwner->GetParent(), false);
			RECT rcNull = { 0 };
			for( int i = 0; i < m_pOwner->GetCount(); i++ ) static_cast<CControlUI*>(m_pOwner->GetItemAt(i))->SetPos(rcNull);
			m_pOwner->SetFocus();
		}
		else if( uMsg == WM_LBUTTONUP ) {
			POINT pt = { 0 };
			::GetCursorPos(&pt);
			::ScreenToClient(m_pm.GetPaintWindow(), &pt);
			CControlUI* pControl = m_pm.FindControl(pt);
			if( pControl && _tcsicmp(pControl->GetClass(), _T("ScrollBarUI")) != 0 ) PostMessage(WM_KILLFOCUS);
		}
		else if( uMsg == WM_KEYDOWN ) {
			switch( wParam ) {
			case VK_ESCAPE:
				m_pOwner->SelectItem(m_iOldSel, true);
				EnsureVisible(m_iOldSel);
			case VK_RETURN:
				PostMessage(WM_KILLFOCUS);
				break;
			default:
				TEventUI event;
				event.Type = UIEVENT_KEYDOWN;
				event.chKey = (TCHAR)wParam;
				m_pOwner->DoEvent(event);
				EnsureVisible(m_pOwner->GetCurSel());
				return 0;
			}
		}
		else if( uMsg == WM_MOUSEWHEEL ) {
			int zDelta = (int) (short) HIWORD(wParam);
			TEventUI event = { 0 };
			event.Type = UIEVENT_SCROLLWHEEL;
			event.wParam = MAKELPARAM(zDelta < 0 ? SB_LINEDOWN : SB_LINEUP, 0);
			event.lParam = lParam;
			event.dwTimestamp = ::GetTickCount();
			m_pOwner->DoEvent(event);
			EnsureVisible(m_pOwner->GetCurSel());
			return 0;
		}
		else if( uMsg == WM_KILLFOCUS ) {
			if( m_hWnd != (HWND) wParam ) PostMessage(WM_CLOSE);
		}

		LRESULT lRes = 0;
		if( m_pm.MessageHandler(uMsg, wParam, lParam, lRes) ) return lRes;
		return CWindowWnd::HandleMessage(uMsg, wParam, lParam);
	}
Esempio n. 12
0
// Used to update the tracking info to account for a change in the top-level menu
HRESULT CMenuFocusManager::UpdateFocus()
{
    HRESULT hr;
    StackEntry * old = m_current;

    TRACE("UpdateFocus\n");

    // Assign the new current item
    if (m_bandCount > 0)
        m_current = &(m_bandStack[m_bandCount - 1]);
    else
        m_current = NULL;

    // Remove the menu capture if necesary
    if (!m_current || m_current->type != MenuPopupEntry)
    {
        SetMenuCapture(NULL);
        if (old && old->type == MenuPopupEntry && m_PreviousForeground)
        {
            ::SetForegroundWindow(m_PreviousForeground);
            m_PreviousForeground = NULL;
        }
    }

    // Obtain the top-level window for the new active menu
    if (m_current && m_current->type != TrackedMenuEntry)
    {
        hr = m_current->mb->_GetTopLevelWindow(&(m_current->hwnd));
        if (FAILED_UNEXPECTEDLY(hr))
            return hr;
    }

    // Refresh the parent pointer
    if (m_bandCount >= 2)
    {
        m_parent = &(m_bandStack[m_bandCount - 2]);
        _ASSERT(m_parent->type != TrackedMenuEntry);
    }
    else
    {
        m_parent = NULL;
    }

    // Refresh the menubar pointer, if applicable
    if (m_bandCount >= 1 && m_bandStack[0].type == MenuBarEntry)
    {
        m_menuBar = &(m_bandStack[0]);
    }
    else
    {
        m_menuBar = NULL;
    }

    // Remove the old hooks if the menu type changed, or we don't have a menu anymore
    if (old && (!m_current || old->type != m_current->type))
    {
        if (m_current && m_current->type != TrackedMenuEntry)
        {
            DisableMouseTrack(m_current->hwnd, FALSE);
        }

        hr = RemoveHooks();
        if (FAILED_UNEXPECTEDLY(hr))
            return hr;
    }

    // And place new ones if necessary
    if (m_current && (!old || old->type != m_current->type))
    {
        hr = PlaceHooks();
        if (FAILED_UNEXPECTEDLY(hr))
            return hr;
    }

    // Give the user a chance to move the mouse to the new menu
    if (m_parent)
    {
        DisableMouseTrack(m_parent->hwnd, TRUE);
    }

    if (m_current && m_current->type == MenuPopupEntry)
    {
        if (m_captureHwnd == NULL)
        {
            // We need to restore the capture after a non-shell submenu or context menu is shown
            StackEntry * topMenu = m_bandStack;
            if (topMenu->type == MenuBarEntry)
                topMenu++;

            // Get the top-level window from the top popup
            CComPtr<IServiceProvider> bandSite;
            CComPtr<IOleWindow> deskBar;
            hr = topMenu->mb->GetSite(IID_PPV_ARG(IServiceProvider, &bandSite));
            if (FAILED(hr))
                goto NoCapture;
            hr = bandSite->QueryService(SID_SMenuPopup, IID_PPV_ARG(IOleWindow, &deskBar));
            if (FAILED(hr))
                goto NoCapture;

            CComPtr<IOleWindow> deskBarSite;
            hr = IUnknown_GetSite(deskBar, IID_PPV_ARG(IOleWindow, &deskBarSite));
            if (FAILED(hr))
                goto NoCapture;

            // FIXME: Find the correct place for this
            HWND hWndOwner;
            hr = deskBarSite->GetWindow(&hWndOwner);
            if (FAILED(hr))
                goto NoCapture;

            m_PreviousForeground = ::GetForegroundWindow();
            if (m_PreviousForeground != hWndOwner)
                ::SetForegroundWindow(hWndOwner);
            else
                m_PreviousForeground = NULL;

            // Get the HWND of the top-level window
            HWND hWndSite;
            hr = deskBar->GetWindow(&hWndSite);
            if (FAILED(hr))
                goto NoCapture;
            SetMenuCapture(hWndSite);
        }
NoCapture:

        if (!m_parent || m_parent->type == MenuBarEntry)
        {
            if (old && old->type == TrackedMenuEntry)
            {
                // FIXME: Debugging code, probably not right
                POINT pt2;
                RECT rc2;
                GetCursorPos(&pt2);
                ScreenToClient(m_current->hwnd, &pt2);
                GetClientRect(m_current->hwnd, &rc2);
                if (PtInRect(&rc2, pt2))
                    SendMessage(m_current->hwnd, WM_MOUSEMOVE, 0, MAKELPARAM(pt2.x, pt2.y));
                else
                    SendMessage(m_current->hwnd, WM_MOUSELEAVE, 0, 0);
            }
        }
    }

    _ASSERT(!m_parent || m_parent->type != TrackedMenuEntry);

    return S_OK;
}
Esempio n. 13
0
LRESULT CMenuFocusManager::ProcessMouseMove(MSG* msg)
{
    HWND child;
    int iHitTestResult = -1;

    POINT pt2 = { GET_X_LPARAM(msg->lParam), GET_Y_LPARAM(msg->lParam) };
    ClientToScreen(msg->hwnd, &pt2);

    // Don't do anything if the mouse has not been moved
    POINT pt = msg->pt;
    if (pt.x == m_ptPrev.x && pt.y == m_ptPrev.y)
        return TRUE;

    // Don't do anything if another window is capturing the mouse.
    HWND cCapture = ::GetCapture();
    if (cCapture && cCapture != m_captureHwnd && m_current->type != TrackedMenuEntry)
        return TRUE;

    m_movedSinceDown = TRUE;

    m_ptPrev = pt;

    child = WindowFromPoint(pt);

    StackEntry * entry = NULL;
    if (IsTrackedWindow(child, &entry) == S_OK)
    {
        TRACE("MouseMove %d\n", m_isLButtonDown);
    }

    BOOL isTracking = FALSE;
    if (entry && (entry->type == MenuBarEntry || m_current->type != TrackedMenuEntry))
    {
        ScreenToClient(child, &pt);
        iHitTestResult = SendMessageW(child, TB_HITTEST, 0, (LPARAM) &pt);
        isTracking = entry->mb->_IsTracking();

        if (SendMessage(child, WM_USER_ISTRACKEDITEM, iHitTestResult, 0) == S_FALSE)
        {
            // The current tracked item has changed, notify the toolbar

            TRACE("Hot item tracking detected a change (capture=%p / cCapture=%p)...\n", m_captureHwnd, cCapture);
            DisableMouseTrack(NULL, FALSE);
            if (isTracking && iHitTestResult >= 0 && m_current->type == TrackedMenuEntry)
                SendMessage(entry->hwnd, WM_CANCELMODE, 0, 0);
            PostMessage(child, WM_USER_CHANGETRACKEDITEM, iHitTestResult, MAKELPARAM(isTracking, TRUE));
            if (m_current->type == TrackedMenuEntry)
                return FALSE;
        }
    }

    if (m_entryUnderMouse != entry)
    {
        // Mouse moved away from a tracked window
        if (m_entryUnderMouse)
        {
            m_entryUnderMouse->mb->_ChangeHotItem(NULL, -1, HICF_MOUSE);
        }
    }

    if (m_hwndUnderMouse != child)
    {
        if (entry)
        {
            // Mouse moved to a tracked window
            if (m_current->type == MenuPopupEntry)
            {
                ScreenToClient(child, &pt2);
                SendMessage(child, WM_MOUSEMOVE, msg->wParam, MAKELPARAM(pt2.x, pt2.y));
            }
        }

        m_hwndUnderMouse = child;
        m_entryUnderMouse = entry;
    }

    if (m_current->type == MenuPopupEntry)
    {
        HWND parent = GetAncestor(child, GA_ROOT);
        DisableMouseTrack(parent, FALSE);
    }

    return TRUE;
}
Esempio n. 14
0
static int ListWndInfoApply(void)
{
	RECT rc;
	HFONT hFontPre = NULL;
	DWORD fdwPitch = (ListWndInfo.fontFlags&FONT_FLAGS_FIXED)?FIXED_PITCH:VARIABLE_PITCH;	
	DWORD fdwItalic = (ListWndInfo.fontFlags&FONT_FLAGS_ITALIC)?TRUE:FALSE;
	HFONT hFont =
		CreateFont(ListWndInfo.fontHeight,ListWndInfo.fontWidth,0,0,FW_DONTCARE,fdwItalic,FALSE,FALSE,
			DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,
	      	fdwPitch | FF_DONTCARE,ListWndInfo.fontName);
	if(hFont != NULL){
		hFontPre = ListWndInfo.hFontListBox;
		ListWndInfo.hFontListBox = hFont;
		SendMessage(ListWndInfo.hwndListBox,WM_SETFONT,(WPARAM)ListWndInfo.hFontListBox,(LPARAM)MAKELPARAM(TRUE,0));
	}
	GetWindowRect(ListWndInfo.hwnd,&rc);
	MoveWindow(ListWndInfo.hwnd,rc.left,rc.top,ListWndInfo.Width,ListWndInfo.Height,TRUE);
//	InvalidateRect(hwnd,&rc,FALSE);
//	UpdateWindow(hwnd);
	if(hFontPre!=NULL) CloseHandle(hFontPre);
	INISaveListWnd();
	return 0;
}
Esempio n. 15
0
static
LRESULT
CALLBACK
GROUP_GroupWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    PROGGROUP* group;
    INT iItem;
    LVITEMW lvItem;
    POINT pt;

    group = (PROGGROUP*)GetWindowLongPtrW(hWnd, 0);

    switch (uMsg)
    {
        case WM_NCCREATE:
        {
            LPCREATESTRUCTW pcs = (LPCREATESTRUCTW)lParam;
            LPMDICREATESTRUCTW pMDIcs = (LPMDICREATESTRUCTW)pcs->lpCreateParams;
            group = (PROGGROUP*)pMDIcs->lParam;
            SetWindowLongPtrW(hWnd, 0, (LONG_PTR)group);

            if (group->bIsCommonGroup)
            {
                DefMDIChildProcW(hWnd, WM_SETICON, ICON_BIG,
                                 (LPARAM)CopyImage(Globals.hCommonGroupIcon,
                                                   IMAGE_ICON,
                                                   GetSystemMetrics(SM_CXICON),
                                                   GetSystemMetrics(SM_CYICON),
                                                   LR_COPYFROMRESOURCE));
                DefMDIChildProcW(hWnd, WM_SETICON, ICON_SMALL,
                                 (LPARAM)CopyImage(Globals.hCommonGroupIcon,
                                                   IMAGE_ICON,
                                                   GetSystemMetrics(SM_CXSMICON),
                                                   GetSystemMetrics(SM_CYSMICON),
                                                   LR_COPYFROMRESOURCE));
            }
            else
            {
                DefMDIChildProcW(hWnd, WM_SETICON, ICON_BIG,
                                 (LPARAM)CopyImage(Globals.hPersonalGroupIcon,
                                                   IMAGE_ICON,
                                                   GetSystemMetrics(SM_CXICON),
                                                   GetSystemMetrics(SM_CYICON),
                                                   LR_COPYFROMRESOURCE));
                DefMDIChildProcW(hWnd, WM_SETICON, ICON_SMALL,
                                 (LPARAM)CopyImage(Globals.hPersonalGroupIcon,
                                                   IMAGE_ICON,
                                                   GetSystemMetrics(SM_CXSMICON),
                                                   GetSystemMetrics(SM_CYSMICON),
                                                   LR_COPYFROMRESOURCE));
            }
            break;
        }

        case WM_NCDESTROY:
            SetWindowLongPtrW(hWnd, 0, 0);
            break;

        case WM_CREATE:
        {
            DWORD dwStyle;
            RECT rect;
            GetClientRect(hWnd, &rect);
            group->hListView = CreateWindowW(WC_LISTVIEW,
                                             NULL,
                                             WS_CHILD | WS_VISIBLE | WS_OVERLAPPED,
                                             0, 0,
                                             rect.right - rect.left,
                                             rect.bottom - rect.top,
                                             hWnd,
                                             NULL,
                                             Globals.hInstance,
                                             NULL);
            dwStyle = (GetWindowLongPtrW(group->hListView, GWL_STYLE) | LVS_SHOWSELALWAYS) & ~LVS_AUTOARRANGE;
            SetWindowLongPtrW(group->hListView, GWL_STYLE, dwStyle);
            dwStyle = SendMessageA(group->hListView, LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0) | LVS_EX_BORDERSELECT;
            SendMessageA(group->hListView, LVM_SETEXTENDEDLISTVIEWSTYLE, LVS_EX_SNAPTOGRID, dwStyle);
            InitUxTheme();
            SetWindowTheme(group->hListView, L"Explorer", NULL);
            group->hListLarge = ImageList_Create(GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), ILC_COLOR24 | ILC_MASK, 1, 1);
            SendMessageA(group->hListView, LVM_SETIMAGELIST, 0, (LPARAM)group->hListLarge);
            SendMessageA(group->hListView, LVM_SETICONSPACING, 0, MAKELPARAM(80, 64));
            break;
        }

        case WM_DESTROY:
        {
            SendMessageA(group->hListView, LVM_SETIMAGELIST, 0, 0);
            ImageList_Destroy(group->hListLarge);
            DestroyWindow(group->hListView);
            break;
        }

        case WM_SIZE:
        {
            RECT rect;
            rect.left = 0;
            rect.top  = 0;
            rect.right  = LOWORD(lParam);
            rect.bottom = HIWORD(lParam);
            AdjustWindowRectEx(&rect, GetWindowLongPtrW(group->hListView, GWL_STYLE), FALSE, GetWindowLongPtrW(group->hListView, GWL_EXSTYLE));
            MoveWindow(group->hListView, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
            break;
        }

        case WM_CLOSE:
            SendMessageW(hWnd, WM_SYSCOMMAND, SC_MINIMIZE, 0);
            break;

        case WM_SYSCOMMAND:
            if (wParam == SC_CLOSE) wParam = SC_MINIMIZE;
            break;

        case WM_CHILDACTIVATE:
        case WM_NCLBUTTONDOWN:
            Globals.hActiveGroup = (PROGGROUP*)GetWindowLongPtrW(hWnd, 0);
            Globals.hActiveGroup->hActiveProgram = NULL;
            break;

        case WM_NOTIFY:
            switch (((LPNMHDR)lParam)->code)
            {
                case NM_CLICK:
                {
                    iItem = ((LPNMITEMACTIVATE)lParam)->iItem;
                    if (iItem == -1)
                    {
                        group->hActiveProgram = NULL;
                        break;
                    }

                    lvItem.mask  = LVIF_PARAM;
                    lvItem.iItem = iItem;
                    SendMessageW(group->hListView, LVM_GETITEMW, 0, (LPARAM)&lvItem);
                    group->hActiveProgram = (PROGRAM*)lvItem.lParam;
                    break;
                }

                case NM_DBLCLK:
                {
                    iItem = ((LPNMITEMACTIVATE)lParam)->iItem;
                    if (iItem == -1)
                        break;

                    lvItem.mask  = LVIF_PARAM;
                    lvItem.iItem = iItem;
                    SendMessageW(group->hListView, LVM_GETITEMW, 0, (LPARAM)&lvItem);
                    /* ... or use group->hActiveProgram */
                    PROGRAM_ExecuteProgram((PROGRAM*)lvItem.lParam);
                    break;
                }

                case LVN_BEGINDRAG:
                {
                    POINT ptMin;

                    BOOL bFirst = TRUE;
                    for (iItem = SendMessageA(group->hListView, LVM_GETNEXTITEM, -1, LVNI_SELECTED);
                         iItem != -1;
                         iItem = SendMessageA(group->hListView, LVM_GETNEXTITEM, iItem, LVNI_SELECTED))
                    {
                        if (bFirst)
                        {
                            group->hDragImageList = (HIMAGELIST)SendMessageA(group->hListView,
                                                                             LVM_CREATEDRAGIMAGE,
                                                                             iItem,
                                                                             (LPARAM)&pt);
                            ptMin  = pt;
                            bFirst = FALSE;
                        }
                        else
                        {
                            HIMAGELIST hOneImageList, hTempImageList;

                            hOneImageList = (HIMAGELIST)SendMessageA(group->hListView,
                                                                     LVM_CREATEDRAGIMAGE,
                                                                     iItem,
                                                                     (LPARAM)&pt);
                            hTempImageList = ImageList_Merge(group->hDragImageList,
                                                             0,
                                                             hOneImageList,
                                                             0,
                                                             pt.x - ptMin.x,
                                                             pt.y - ptMin.y);
                            ImageList_Destroy(group->hDragImageList);
                            ImageList_Destroy(hOneImageList);
                            group->hDragImageList = hTempImageList;
                            ptMin.x = min(ptMin.x, pt.x);
                            ptMin.y = min(ptMin.y, pt.y);
                        }
                    }
                    // pt = ((LPNMLISTVIEW)lParam)->ptAction;
                    pt.x = ((LPNMLISTVIEW)lParam)->ptAction.x;
                    pt.y = ((LPNMLISTVIEW)lParam)->ptAction.y;
                    group->ptStart = pt;
                    pt.x -= ptMin.x;
                    pt.y -= ptMin.y;
                    ImageList_BeginDrag(group->hDragImageList, 0, pt.x, pt.y);
                    MapWindowPoints(group->hListView, Globals.hMDIWnd, &pt, 1);
                    ImageList_DragEnter(Globals.hMDIWnd, pt.x, pt.y);
                    group->bDragging = TRUE;
                    group->hOldCursor = GetCursor();
                    SetCapture(group->hWnd);

                    break;
                }
            }
            break;

        case WM_MOUSEMOVE:
            if (group->bDragging)
            {
                pt.x = GET_X_LPARAM(lParam);
                pt.y = GET_Y_LPARAM(lParam);
                MapWindowPoints(group->hWnd, Globals.hMDIWnd, &pt, 1);
                ImageList_DragMove(pt.x, pt.y);
            }
            break;

        case WM_LBUTTONUP:
            if (group->bDragging)
            {
                // LVHITTESTINFO lvhti;
                POINT ptHit;

                group->bDragging = FALSE;
                ImageList_DragLeave(Globals.hMDIWnd);
                ImageList_EndDrag();
                ImageList_Destroy(group->hDragImageList);
                ReleaseCapture();
                SetCursor(group->hOldCursor);
                ptHit.x = GET_X_LPARAM(lParam);
                ptHit.y = GET_Y_LPARAM(lParam);
                MapWindowPoints(group->hWnd, group->hListView, &ptHit, 1);
                for (iItem = SendMessageA(group->hListView, LVM_GETNEXTITEM, -1, LVNI_SELECTED);
                     iItem != -1;
                     iItem = SendMessageA(group->hListView, LVM_GETNEXTITEM, iItem, LVNI_SELECTED))
                {
                    SendMessageA(group->hListView, LVM_GETITEMPOSITION, iItem, (LPARAM)&pt);
                    pt.x += ptHit.x - group->ptStart.x;
                    pt.y += ptHit.y - group->ptStart.y;
                    SendMessageA(group->hListView, LVM_SETITEMPOSITION, iItem, MAKELPARAM(pt.x, pt.y));
                }
            }
            break;
    }

    return DefMDIChildProcW(hWnd, uMsg, wParam, lParam);
}
Esempio n. 16
0
void CMainUIDlg::MoveMainDlg(int iArg1 , int iArg2)
{
    PostMessage(WM_NCLBUTTONDOWN,HTCAPTION,MAKELPARAM(iArg1,iArg2));
    return;
}
/// <summary>
/// Initialize the UI
/// </summary>
void CKinectFusionExplorer::InitializeUIControls()
{
    // Create NuiSensorChooser UI control
    RECT rc;
    GetClientRect(m_hWnd, &rc);

    POINT ptCenterTop;
    ptCenterTop.x = (rc.right - rc.left)/2;
    ptCenterTop.y = 0;

    // Create the sensor chooser UI control to show sensor status
    m_pSensorChooserUI = new NuiSensorChooserUI(m_hWnd, IDC_SENSORCHOOSER, ptCenterTop);
    m_pSensorChooserUI->UpdateSensorStatus(NuiSensorChooserStatusInitializing);

    // Set slider ranges
    SendDlgItemMessage(
        m_hWnd,
        IDC_SLIDER_DEPTH_MIN,
        TBM_SETRANGE,
        TRUE,
        MAKELPARAM(MIN_DEPTH_DISTANCE_MM, MAX_DEPTH_DISTANCE_MM));

    SendDlgItemMessage(m_hWnd,
        IDC_SLIDER_DEPTH_MAX,
        TBM_SETRANGE,
        TRUE,
        MAKELPARAM(MIN_DEPTH_DISTANCE_MM, MAX_DEPTH_DISTANCE_MM));

    SendDlgItemMessage(
        m_hWnd,
        IDC_INTEGRATION_WEIGHT_SLIDER,
        TBM_SETRANGE,
        TRUE,
        MAKELPARAM(MIN_INTEGRATION_WEIGHT, MAX_INTEGRATION_WEIGHT));

    // Set slider positions
    SendDlgItemMessage(
        m_hWnd,
        IDC_SLIDER_DEPTH_MAX,
        TBM_SETPOS,
        TRUE,
        (UINT)m_params.m_fMaxDepthThreshold * 1000);

    SendDlgItemMessage(
        m_hWnd,
        IDC_SLIDER_DEPTH_MIN,
        TBM_SETPOS,
        TRUE,
        (UINT)m_params.m_fMinDepthThreshold * 1000);

    SendDlgItemMessage(
        m_hWnd,
        IDC_INTEGRATION_WEIGHT_SLIDER,
        TBM_SETPOS,
        TRUE,
        (UINT)m_params.m_cMaxIntegrationWeight);

    // Set intermediate slider tics at meter intervals
    for (int i=1; i<(MAX_DEPTH_DISTANCE_MM/1000); i++)
    {
        SendDlgItemMessage(m_hWnd, IDC_SLIDER_DEPTH_MAX, TBM_SETTIC, 0, i*1000);
        SendDlgItemMessage(m_hWnd, IDC_SLIDER_DEPTH_MIN, TBM_SETTIC, 0, i*1000);
    }

    // Update slider text
    WCHAR str[MAX_PATH];
    swprintf_s(str, ARRAYSIZE(str), L"%4.2fm", m_params.m_fMinDepthThreshold);
    SetDlgItemText(m_hWnd, IDC_MIN_DIST_TEXT, str);
    swprintf_s(str, ARRAYSIZE(str), L"%4.2fm", m_params.m_fMaxDepthThreshold);
    SetDlgItemText(m_hWnd, IDC_MAX_DIST_TEXT, str);

    swprintf_s(str, ARRAYSIZE(str), L"%d", m_params.m_cMaxIntegrationWeight);
    SetDlgItemText(m_hWnd, IDC_INTEGRATION_WEIGHT_TEXT, str);

    // Set the radio buttons for Volume Parameters
    switch((int)m_params.m_reconstructionParams.voxelsPerMeter)
    {
    case 768:
        CheckDlgButton(m_hWnd, IDC_VPM_768, BST_CHECKED);
        break;
    case 640:
        CheckDlgButton(m_hWnd, IDC_VPM_640, BST_CHECKED);
        break;
    case 512:
        CheckDlgButton(m_hWnd, IDC_VPM_512, BST_CHECKED);
        break;
    case 384:
        CheckDlgButton(m_hWnd, IDC_VPM_384, BST_CHECKED);
        break;
    case 256:
        CheckDlgButton(m_hWnd, IDC_VPM_256, BST_CHECKED);
        break;
    case 128:
        CheckDlgButton(m_hWnd, IDC_VPM_128, BST_CHECKED);
        break;
    default:
        m_params.m_reconstructionParams.voxelsPerMeter = 256.0f;	// set to medium default
        CheckDlgButton(m_hWnd, IDC_VPM_256, BST_CHECKED);
        break;
    }

    switch((int)m_params.m_reconstructionParams.voxelCountX)
    {
    case 640:
        CheckDlgButton(m_hWnd, IDC_VOXELS_X_640, BST_CHECKED);
        break;
    case 512:
        CheckDlgButton(m_hWnd, IDC_VOXELS_X_512, BST_CHECKED);
        break;
    case 384:
        CheckDlgButton(m_hWnd, IDC_VOXELS_X_384, BST_CHECKED);
        break;
    case 256:
        CheckDlgButton(m_hWnd, IDC_VOXELS_X_256, BST_CHECKED);
        break;
    case 128:
        CheckDlgButton(m_hWnd, IDC_VOXELS_X_128, BST_CHECKED);
        break;
    default:
        m_params.m_reconstructionParams.voxelCountX = 384;	// set to medium default
        CheckDlgButton(m_hWnd, IDC_VOXELS_X_384, BST_CHECKED);
        break;
    }

    switch((int)m_params.m_reconstructionParams.voxelCountY)
    {
    case 640:
        CheckDlgButton(m_hWnd, IDC_VOXELS_Y_640, BST_CHECKED);
        break;
    case 512:
        CheckDlgButton(m_hWnd, IDC_VOXELS_Y_512, BST_CHECKED);
        break;
    case 384:
        CheckDlgButton(m_hWnd, IDC_VOXELS_Y_384, BST_CHECKED);
        break;
    case 256:
        CheckDlgButton(m_hWnd, IDC_VOXELS_Y_256, BST_CHECKED);
        break;
    case 128:
        CheckDlgButton(m_hWnd, IDC_VOXELS_Y_128, BST_CHECKED);
        break;
    default:
        m_params.m_reconstructionParams.voxelCountX = 384;	// set to medium default
        CheckDlgButton(m_hWnd, IDC_VOXELS_Y_384, BST_CHECKED);
        break;
    }

    switch((int)m_params.m_reconstructionParams.voxelCountZ)
    {
    case 640:
        CheckDlgButton(m_hWnd, IDC_VOXELS_Z_640, BST_CHECKED);
        break;
    case 512:
        CheckDlgButton(m_hWnd, IDC_VOXELS_Z_512, BST_CHECKED);
        break;
    case 384:
        CheckDlgButton(m_hWnd, IDC_VOXELS_Z_384, BST_CHECKED);
        break;
    case 256:
        CheckDlgButton(m_hWnd, IDC_VOXELS_Z_256, BST_CHECKED);
        break;
    case 128:
        CheckDlgButton(m_hWnd, IDC_VOXELS_Z_128, BST_CHECKED);
        break;
    default:
        m_params.m_reconstructionParams.voxelCountX = 384;	// set to medium default
        CheckDlgButton(m_hWnd, IDC_VOXELS_Z_384, BST_CHECKED);
        break;
    }

    if (Stl == m_saveMeshFormat)
    {
        CheckDlgButton(m_hWnd, IDC_MESH_FORMAT_STL_RADIO, BST_CHECKED);
    }
    else if (Obj == m_saveMeshFormat)
    {
        CheckDlgButton(m_hWnd, IDC_MESH_FORMAT_OBJ_RADIO, BST_CHECKED);
    }
    else if (Ply == m_saveMeshFormat)
    {
        CheckDlgButton(m_hWnd, IDC_MESH_FORMAT_PLY_RADIO, BST_CHECKED);
    }

    if (m_params.m_bCaptureColor)
    {
        CheckDlgButton(m_hWnd, IDC_CHECK_CAPTURE_COLOR, BST_CHECKED);
    }

    if (m_params.m_bAutoFindCameraPoseWhenLost)
    {
        CheckDlgButton(m_hWnd, IDC_CHECK_CAMERA_POSE_FINDER, BST_CHECKED);
    }
}
Esempio n. 18
0
NTSTATUS FASTCALL
UserAttachThreadInput(PTHREADINFO ptiFrom, PTHREADINFO ptiTo, BOOL fAttach)
{
    MSG msg;
    PATTACHINFO pai;

    /* Can not be the same thread. */
    if (ptiFrom == ptiTo) return STATUS_INVALID_PARAMETER;

    /* Do not attach to system threads or between different desktops. */
    if (ptiFrom->TIF_flags & TIF_DONTATTACHQUEUE ||
        ptiTo->TIF_flags & TIF_DONTATTACHQUEUE ||
        ptiFrom->rpdesk != ptiTo->rpdesk)
        return STATUS_ACCESS_DENIED;

    /* MSDN Note:
       Keyboard and mouse events received by both threads are processed by the thread specified by the idAttachTo.
     */

    /* If Attach set, allocate and link. */
    if (fAttach)
    {
        pai = ExAllocatePoolWithTag(PagedPool, sizeof(ATTACHINFO), USERTAG_ATTACHINFO);
        if (!pai) return STATUS_NO_MEMORY;

        pai->paiNext = gpai;
        pai->pti1 = ptiFrom;
        pai->pti2 = ptiTo;
        gpai = pai;
        paiCount++;
        ERR("Attach Allocated! ptiFrom 0x%p  ptiTo 0x%p paiCount %d\n",ptiFrom,ptiTo,paiCount);

        if (ptiTo->MessageQueue != ptiFrom->MessageQueue)
        {

           ptiTo->MessageQueue->iCursorLevel -= ptiFrom->iCursorLevel;

           // FIXME: conditions?
           if (ptiTo->MessageQueue == gpqForeground)
           {
              ERR("ptiTo is Foreground\n");
           }
           else
           {
              ERR("ptiTo NOT Foreground\n");
           }

           if (ptiFrom->MessageQueue == gpqForeground)
           {
              ERR("ptiFrom is Foreground\n");
              ptiTo->MessageQueue->spwndActive  = ptiFrom->MessageQueue->spwndActive;
              ptiTo->MessageQueue->spwndFocus   = ptiFrom->MessageQueue->spwndFocus;
              ptiTo->MessageQueue->CursorObject = ptiFrom->MessageQueue->CursorObject;
              ptiTo->MessageQueue->spwndCapture = ptiFrom->MessageQueue->spwndCapture;
              ptiTo->MessageQueue->QF_flags    ^= ((ptiTo->MessageQueue->QF_flags ^ ptiFrom->MessageQueue->QF_flags) & QF_CAPTURELOCKED);
              ptiTo->MessageQueue->CaretInfo    = ptiFrom->MessageQueue->CaretInfo;
              IntSetFocusMessageQueue(NULL);
              IntSetFocusMessageQueue(ptiTo->MessageQueue);
              gptiForeground = ptiTo;
           }
           else
           {
              ERR("ptiFrom NOT Foreground\n");
           }

           MsqDestroyMessageQueue(ptiFrom);

           ptiFrom->MessageQueue = ptiTo->MessageQueue;

           ptiFrom->MessageQueue->cThreads++;
           ERR("ptiTo S Share count %d\n", ptiFrom->MessageQueue->cThreads);

           IntReferenceMessageQueue(ptiTo->MessageQueue);
        }
        else
        {
           ERR("Attach Threads are already associated!\n");
        }
    }
    else /* If clear, unlink and free it. */
    {
        BOOL Hit = FALSE;
        PATTACHINFO *ppai;

        if (!gpai) return STATUS_INVALID_PARAMETER;

        /* Search list and free if found or return false. */
        ppai = &gpai;
        while (*ppai != NULL)
        {
           if ( (*ppai)->pti2 == ptiTo && (*ppai)->pti1 == ptiFrom )
           {
              pai = *ppai;
              /* Remove it from the list */
              *ppai = (*ppai)->paiNext;
              ExFreePoolWithTag(pai, USERTAG_ATTACHINFO);
              paiCount--;
              Hit = TRUE;
              break;
           }
           ppai = &((*ppai)->paiNext);
        }

        if (!Hit) return STATUS_INVALID_PARAMETER;
 
        ERR("Attach Free! ptiFrom 0x%p  ptiTo 0x%p paiCount %d\n",ptiFrom,ptiTo,paiCount);
 
        if (ptiTo->MessageQueue == ptiFrom->MessageQueue)
        {
           if (gptiForeground == ptiFrom)
           {
              ERR("ptiTo is now pti FG.\n");
              // MessageQueue foreground is set so switch threads.
              gptiForeground = ptiTo;
           }
           ptiTo->MessageQueue->cThreads--;
           ERR("ptiTo E Share count %d\n", ptiTo->MessageQueue->cThreads);
           ASSERT(ptiTo->MessageQueue->cThreads >= 1);

           IntDereferenceMessageQueue(ptiTo->MessageQueue);

           ptiFrom->MessageQueue = MsqCreateMessageQueue(ptiFrom);

           ptiTo->MessageQueue->iCursorLevel -= ptiFrom->iCursorLevel;
        }
        else
        {
           ERR("Detaching Threads are not associated!\n");
        }
    }
    /* Note that key state, which can be ascertained by calls to the GetKeyState
       or GetKeyboardState function, is reset after a call to AttachThreadInput.
       ATM which one?
     */
    RtlCopyMemory(ptiTo->MessageQueue->afKeyState, gafAsyncKeyState, sizeof(gafAsyncKeyState));

    /* Generate mouse move message */
    msg.message = WM_MOUSEMOVE;
    msg.wParam = UserGetMouseButtonsState();
    msg.lParam = MAKELPARAM(gpsi->ptCursor.x, gpsi->ptCursor.y);
    msg.pt = gpsi->ptCursor;
    co_MsqInsertMouseMessage(&msg, 0, 0, TRUE);

    return STATUS_SUCCESS;
}
Esempio n. 19
0
void ExtraImage_SetAllExtraIcons(HWND hwndList,HANDLE hContact)
{
	HANDLE hItem;
	int locApparentMode=0;
	char * locApparentModeProto=NULL;
	boolean hcontgiven=FALSE;
	char *szProto;
	char *(ImgIndex[64]);
	int maxpr,count,i;
	PROTOACCOUNT **accs;
	pdisplayNameCacheEntry pdnce;
	int em,pr,sms,a1,a2,w1,c1;
	int tick=0;
	g_mutex_bSetAllExtraIconsCycle=1;
	hcontgiven=(hContact!=0);

	if (pcli->hwndContactTree==0){return;};
	tick=GetTickCount();
	if (ImageCreated==FALSE) ExtraImage_ReloadExtraIcons();

	SetNewExtraColumnCount();

	BOOL hasExtraIconsService = HasExtraIconsService();
	if (!hasExtraIconsService)
	{
		em=ExtraImage_ExtraIDToColumnNum(EXTRA_ICON_EMAIL);	
		pr=ExtraImage_ExtraIDToColumnNum(EXTRA_ICON_PROTO);
		sms=ExtraImage_ExtraIDToColumnNum(EXTRA_ICON_SMS);
		a1=ExtraImage_ExtraIDToColumnNum(EXTRA_ICON_ADV1);
		a2=ExtraImage_ExtraIDToColumnNum(EXTRA_ICON_ADV2);
		w1=ExtraImage_ExtraIDToColumnNum(EXTRA_ICON_WEB);
		c1=ExtraImage_ExtraIDToColumnNum(EXTRA_ICON_CLIENT);

		memset( ImgIndex, 0, sizeof( ImgIndex ) );
		ProtoEnumAccounts( &count, &accs );
		maxpr=0;
		//calc only needed protocols
		for(i=0;i<count;i++) {
			if ( !IsAccountEnabled( accs[i] ) || CallProtoService(accs[i]->szModuleName,PS_GETCAPS,PFLAGNUM_2,0)==0) continue;
			ImgIndex[maxpr]=accs[i]->szModuleName;
			maxpr++;
		}
	}

	if (hContact==NULL)
	{
		hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDFIRST,0,0);
	}	

	do {

		szProto=NULL;
		hItem=hContact;
		if (hItem==0){continue;};
		pdnce=(pdisplayNameCacheEntry)pcli->pfnGetCacheEntry(hItem);
		if (pdnce==NULL) {continue;};

		//		szProto=(char*)CallService(MS_PROTO_GETCONTACTBASEPROTO,(WPARAM)hContact,0);		
		szProto=pdnce->m_cache_cszProto;

		if (!hasExtraIconsService)
		{
			{
				boolean showweb;	
				showweb=FALSE;     
				if (ExtraImage_ExtraIDToColumnNum(EXTRA_ICON_WEB)!=-1)
				{

					if (szProto != NULL)
					{
						char *homepage;
						homepage= ModernGetStringA(pdnce->m_cache_hContact,"UserInfo", "Homepage");
						if (!homepage)
							homepage= ModernGetStringA(pdnce->m_cache_hContact,pdnce->m_cache_cszProto, "Homepage");
						if (homepage!=NULL)
						{											
							showweb=TRUE;				
							mir_free_and_nill(homepage);
						}
					}
					SendMessage(hwndList,CLM_SETEXTRAIMAGE,(WPARAM)hItem,MAKELPARAM(ExtraImage_ExtraIDToColumnNum(EXTRA_ICON_WEB),(showweb)?2:0xFF));	
				}
			}		
			{
				DBVARIANT dbv={0};
				boolean showemail;	
				showemail=TRUE;
				if (ExtraImage_ExtraIDToColumnNum(EXTRA_ICON_EMAIL)!=-1)
				{

					if (szProto == NULL || ModernGetSettingString(hContact, szProto, "e-mail",&dbv)) 
					{
						ModernDBFreeVariant(&dbv);
						if (ModernGetSettingString(hContact, "UserInfo", "Mye-mail0", &dbv))
							showemail=FALSE;					
					}
					SendMessage(hwndList,CLM_SETEXTRAIMAGE,(WPARAM)hItem,MAKELPARAM(ExtraImage_ExtraIDToColumnNum(EXTRA_ICON_EMAIL),(showemail)?0:0xFF));	
					ModernDBFreeVariant(&dbv);
				}
			}

			{
				DBVARIANT dbv={0};
				boolean showsms;	
				showsms=TRUE;
				if (ExtraImage_ExtraIDToColumnNum(EXTRA_ICON_SMS)!=-1)
				{
					if (szProto == NULL || ModernGetSettingString(hContact, szProto, "Cellular",&dbv)) 
					{
						ModernDBFreeVariant(&dbv);
						if (ModernGetSettingString(hContact, "UserInfo", "MyPhone0", &dbv))
							showsms=FALSE;
					}
					SendMessage(hwndList,CLM_SETEXTRAIMAGE,(WPARAM)hItem,MAKELPARAM(ExtraImage_ExtraIDToColumnNum(EXTRA_ICON_SMS),(showsms)?1:0xFF));	
					ModernDBFreeVariant(&dbv);
				}
			}		

			if(ExtraImage_ExtraIDToColumnNum(EXTRA_ICON_PROTO)!=-1) 
			{					
				for (i=0;i<maxpr;i++)
				{
					if(!mir_strcmp(ImgIndex[i],szProto))
					{
						SendMessage(hwndList,CLM_SETEXTRAIMAGE,(WPARAM)hItem,MAKELPARAM(ExtraImage_ExtraIDToColumnNum(EXTRA_ICON_PROTO),i+3));	
						break;
					};
				};				
			};
			if(ExtraImage_ExtraIDToColumnNum(EXTRA_ICON_VISMODE)!=-1) 
			{
				BYTE iconIndex=0xFF;
				if (szProto != NULL)
				{
					if (!ModernGetSettingByte(hContact, szProto, "ChatRoom", 0))		
					{
						if (pdnce->ApparentMode==ID_STATUS_OFFLINE)
							iconIndex=ExtraImageIconsIndex[4];	
						else if (pdnce->ApparentMode==ID_STATUS_ONLINE)
						{
							if (szProto!=locApparentModeProto)
							{
								locApparentModeProto=szProto;
								locApparentMode=CallProtoService(locApparentModeProto,PS_GETSTATUS,0,0);
							}
							if(locApparentMode == ID_STATUS_INVISIBLE || ModernGetSettingByte(NULL,"CList","AlwaysShowAlwaysVisIcon",SETTING_ALWAYSVISICON_DEFAULT) == 1)
 								iconIndex=ExtraImageIconsIndex[3];						}
					}
					else 
					{
						if (pdnce->ApparentMode==ID_STATUS_OFFLINE)
							iconIndex=ExtraImageIconsIndex[5];	
						else iconIndex=255;	
					}
				}
				SendMessage(hwndList,CLM_SETEXTRAIMAGE,(WPARAM)hItem,MAKELPARAM(ExtraImage_ExtraIDToColumnNum(EXTRA_ICON_VISMODE),iconIndex));	
			}
		}
		NotifyEventHooks(g_CluiData.hEventExtraImageApplying,(WPARAM)hContact,0);
		if (hcontgiven) break;
		Sleep(0);
	} while(hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDNEXT,(WPARAM)hContact,0));

	tick=GetTickCount()-tick;
	g_mutex_bSetAllExtraIconsCycle=0;
	CLUI__cliInvalidateRect(hwndList,NULL,FALSE);
	Sleep(0);
}
Esempio n. 20
0
NPEvent toNP(const WebMouseEvent& event)
{
    NPEvent npEvent;

    npEvent.wParam = 0;
    if (event.controlKey())
        npEvent.wParam |= MK_CONTROL;
    if (event.shiftKey())
        npEvent.wParam |= MK_SHIFT;

    npEvent.lParam = MAKELPARAM(event.position().x(), event.position().y());

    switch (event.type()) {
    case WebEvent::MouseMove:
        npEvent.event = WM_MOUSEMOVE;
        switch (event.button()) {
        case WebMouseEvent::LeftButton:
            npEvent.wParam |= MK_LBUTTON;
            break;
        case WebMouseEvent::MiddleButton:
            npEvent.wParam |= MK_MBUTTON;
            break;
        case WebMouseEvent::RightButton:
            npEvent.wParam |= MK_RBUTTON;
            break;
        case WebMouseEvent::NoButton:
            break;
        }
        break;
    case WebEvent::MouseDown:
        switch (event.button()) {
        case WebMouseEvent::LeftButton:
            npEvent.event = WM_LBUTTONDOWN;
            break;
        case WebMouseEvent::MiddleButton:
            npEvent.event = WM_MBUTTONDOWN;
            break;
        case WebMouseEvent::RightButton:
            npEvent.event = WM_RBUTTONDOWN;
            break;
        case WebMouseEvent::NoButton:
            ASSERT_NOT_REACHED();
            break;
        }
        break;
    case WebEvent::MouseUp:
        switch (event.button()) {
        case WebMouseEvent::LeftButton:
            npEvent.event = WM_LBUTTONUP;
            break;
        case WebMouseEvent::MiddleButton:
            npEvent.event = WM_MBUTTONUP;
            break;
        case WebMouseEvent::RightButton:
            npEvent.event = WM_RBUTTONUP;
            break;
        case WebMouseEvent::NoButton:
            ASSERT_NOT_REACHED();
            break;
        }
        break;
    default:
        ASSERT_NOT_REACHED();
        break;
    }

    return npEvent;
}
Esempio n. 21
0
// This is an example of an exported function.
int  CDownload::HttpFileDownload(char* lpszServer, char* lpszDest, HWND hWndProgress, HWND hWndMsg)
{

  int bReturn = 0;
  
  HINTERNET hOpen = NULL, 
            hRequest = NULL;

  DWORD dwSize = 0, 
        dwFlags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE; 

  TCHAR szErrMsg[512];
  
  char *lpBufferA;

  LPTSTR AcceptTypes[10] = {TEXT("*/*"), NULL}; 

  hOpen = InternetOpen (TEXT("HttpFileDownload"), INTERNET_OPEN_TYPE_PRECONFIG , NULL, 0, 0);  

  if (!hOpen)
  {
    _stprintf_s(szErrMsg, TEXT("%s: %x\n"), TEXT("InternetOpen Error"),  GetLastError());
	OutputDebugString(szErrMsg);
    return 1;
  }
    DWORD dwRequestFlag = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;

	if(strstr(lpszServer,"https://")!=NULL) //check if it is a HTTPS server
		dwRequestFlag = INTERNET_FLAG_NO_AUTH | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID | INTERNET_FLAG_IGNORE_CERT_CN_INVALID;

	hRequest = InternetOpenUrl (hOpen, lpszServer, NULL, 0,dwRequestFlag, 0);
    if (hRequest==NULL)
    {
		_stprintf_s(szErrMsg, TEXT("%s: %x\n"), TEXT("InternetOpenUrl Error"),GetLastError());
		OutputDebugString(szErrMsg);
		bReturn = 2;
		goto exit;
    }
 
    char szLength[32];
	
	DWORD dwLength=0,dwBuffLen=sizeof(szLength);

   if(HttpQueryInfo (hRequest, HTTP_QUERY_CONTENT_LENGTH, &szLength,&dwBuffLen, NULL)==FALSE)
   {
		_stprintf_s(szErrMsg, TEXT("%s: %x\n"), TEXT("HttpQueryInfo Error"),GetLastError());
		OutputDebugString(szErrMsg);
   }
	dwLength = (DWORD)atol(szLength) ;
	_stprintf_s(szErrMsg, TEXT("Size to download %d\n"),dwLength);
	OutputDebugString(szErrMsg);

   FILE *stream = NULL;
   errno_t err = _set_fmode(_O_BINARY);
   if (err == EINVAL)
   { 
	  OutputDebugString("Invalid mode.\n");
      return 5;
   }
	if(hWndProgress!=NULL)
	 SendMessage(hWndProgress, PBM_SETRANGE, (WPARAM) 0,MAKELPARAM(0, 100));

		
	  DWORD dynamicByte = 32000;
	  DWORD downloadBytes = 0;
	  do
	  {
		 lpBufferA = new CHAR [dynamicByte];

		 sprintf_s(szErrMsg,sizeof(szErrMsg),"Downloaded %d of %d KBytes\n",downloadBytes/1000,dwLength/1000);
		 OutputDebugString(szErrMsg);

		 if(hWndProgress!=NULL)
		 {
			float percentage =  ((float)downloadBytes /  (float)dwLength) * 100.0f ;
			if(percentage>100.0f)
				percentage = 100;
			HWND hwnMsg = GetDlgItem(hWndProgress,IDC_STATIC_TEXT);
			SendMessage(hWndMsg,WM_SETTEXT,0,(LPARAM)szErrMsg);		
			SendMessage(hWndProgress, PBM_SETPOS, (WPARAM) percentage, 0);
		 }
		
		if (!InternetReadFile (hRequest, (LPVOID)lpBufferA, dynamicByte, &dwSize))
		{
			_stprintf_s(szErrMsg, TEXT("%s: %x\n"), TEXT("InternetReadFile Error"),GetLastError());
			OutputDebugString(szErrMsg);
		  delete[] lpBufferA;
		  goto exit;
		}

		if (dwSize != 0)    
		{	
			downloadBytes+=dwSize;
			//Quick check if HTML error has occured
			if(strncmp("<!DOCTYPE",lpBufferA,9)==0)
					bReturn = 100;
			if(strncmp("<HTM",lpBufferA,4)==0)
					bReturn = 100;
			if(strncmp("<htm",lpBufferA,4)==0)
					bReturn = 100;	

			if((stream==NULL) && (bReturn==0))
		   		fopen_s(&stream, lpszDest, "w+" );

			if(stream!=NULL)
				 fwrite( lpBufferA, sizeof( CHAR ), dwSize, stream );		
		}    
		delete[] lpBufferA; 
		dynamicByte+=1024;
		if(dynamicByte>128000)
			dynamicByte = 128000;
			

	  } while (dwSize);


	  if(stream!=NULL)
  		  fclose( stream );


  goto exitWithNoErr;
exit:
	bReturn = 1;
exitWithNoErr:
    if (hRequest)
  {
    if (!InternetCloseHandle (hRequest))
	{
		_stprintf_s(szErrMsg, TEXT("%s: %x"), TEXT("CloseHandle Error"), GetLastError());
		OutputDebugString(szErrMsg);

	}
  }

  // Close the Internet handles.
  if (hOpen)
  {
    if (!InternetCloseHandle (hOpen))
	{
		_stprintf_s(szErrMsg, TEXT("%s: %x"), TEXT("CloseHandle Error"), GetLastError());
		OutputDebugString(szErrMsg);

	}
  }
  
  _stprintf_s(szErrMsg, TEXT("Return %d"), bReturn);
  OutputDebugString(szErrMsg);
  return bReturn;
}
Esempio n. 22
0
HRESULT CBaseVideoFilter::ReconnectOutput(int w, int h, bool bSendSample, int realWidth, int realHeight)
{
    CMediaType& mt = m_pOutput->CurrentMediaType();

    bool m_update_aspect = false;
    if (f_need_set_aspect) {
        int wout = 0, hout = 0, arxout = 0, aryout = 0;
        ExtractDim(&mt, wout, hout, arxout, aryout);
        if (arxout != m_arx || aryout != m_ary) {
            TRACE(_T("\nCBaseVideoFilter::ReconnectOutput; wout = %d, hout = %d, current = %dx%d, set = %dx%d\n"), wout, hout, arxout, aryout, m_arx, m_ary);
            m_update_aspect = true;
        }
    }

    int w_org = m_w;
    int h_org = m_h;

    bool fForceReconnection = false;
    if (w != m_w || h != m_h) {
        fForceReconnection = true;
        m_w = w;
        m_h = h;
    }

    HRESULT hr = S_OK;

    if (m_update_aspect || fForceReconnection || m_w != m_wout || m_h != m_hout || m_arx != m_arxout || m_ary != m_aryout) {
        if (GetCLSID(m_pOutput->GetConnected()) == CLSID_VideoRenderer) {
            NotifyEvent(EC_ERRORABORT, 0, 0);
            return E_FAIL;
        }

        BITMAPINFOHEADER* bmi = NULL;

        if (mt.formattype == FORMAT_VideoInfo) {
            VIDEOINFOHEADER* vih = (VIDEOINFOHEADER*)mt.Format();
            if (realWidth > 0 && realHeight > 0) {
                SetRect(&vih->rcSource, 0, 0, realWidth, realHeight);
                SetRect(&vih->rcTarget, 0, 0, realWidth, realHeight);
            } else {
                SetRect(&vih->rcSource, 0, 0, m_w, m_h);
                SetRect(&vih->rcTarget, 0, 0, m_w, m_h);
            }
            bmi = &vih->bmiHeader;
            bmi->biXPelsPerMeter = m_w * m_ary;
            bmi->biYPelsPerMeter = m_h * m_arx;
        } else if (mt.formattype == FORMAT_VideoInfo2) {
            VIDEOINFOHEADER2* vih = (VIDEOINFOHEADER2*)mt.Format();
            if (realWidth > 0 && realHeight > 0) {
                SetRect(&vih->rcSource, 0, 0, realWidth, realHeight);
                SetRect(&vih->rcTarget, 0, 0, realWidth, realHeight);
            } else {
                SetRect(&vih->rcSource, 0, 0, m_w, m_h);
                SetRect(&vih->rcTarget, 0, 0, m_w, m_h);
            }
            bmi = &vih->bmiHeader;
            vih->dwPictAspectRatioX = m_arx;
            vih->dwPictAspectRatioY = m_ary;
        } else {
            return E_FAIL;  //should never be here? prevent null pointer refs for bmi
        }

        bmi->biWidth = m_w;
        bmi->biHeight = m_h;
        bmi->biSizeImage = m_w * m_h * bmi->biBitCount >> 3;

        hr = m_pOutput->GetConnected()->QueryAccept(&mt);
        ASSERT(SUCCEEDED(hr)); // should better not fail, after all "mt" is the current media type, just with a different resolution
        HRESULT hr1 = 0;
        CComPtr<IMediaSample> pOut;
        if (SUCCEEDED(hr1 = m_pOutput->GetConnected()->ReceiveConnection(m_pOutput, &mt))) {
            if (bSendSample) {
                HRESULT hr2 = 0;
                if (SUCCEEDED(hr2 = m_pOutput->GetDeliveryBuffer(&pOut, NULL, NULL, 0))) {
                    AM_MEDIA_TYPE* pmt;
                    if (SUCCEEDED(pOut->GetMediaType(&pmt)) && pmt) {
                        CMediaType mt2 = *pmt;
                        m_pOutput->SetMediaType(&mt2);
                        DeleteMediaType(pmt);
                    } else { // stupid overlay mixer won't let us know the new pitch...
                        long size = pOut->GetSize();
                        bmi->biWidth = size ? (size / abs(bmi->biHeight) * 8 / bmi->biBitCount) : bmi->biWidth;
                    }
                } else {
                    m_w = w_org;
                    m_h = h_org;
                    return E_FAIL;
                }
            }
        }

        m_wout = m_w;
        m_hout = m_h;
        m_arxout = m_arx;
        m_aryout = m_ary;

        // some renderers don't send this
        NotifyEvent(EC_VIDEO_SIZE_CHANGED, MAKELPARAM(m_w, m_h), 0);

        return S_OK;
    }

    return S_FALSE;
}
Esempio n. 23
0
 void SComboEdit::OnMouseHover( WPARAM wParam, CPoint ptPos )
 {
     __super::OnMouseHover(wParam,ptPos);
     GetOwner()->SSendMessage(WM_MOUSEHOVER,wParam,MAKELPARAM(ptPos.x,ptPos.y));
 }
Esempio n. 24
0
void SetAllExtraIcons(HWND hwndList,HANDLE hContact)
{
	HANDLE hItem;
	boolean hcontgiven=FALSE;
	char *szProto;
	char *(ImgIndex[64]);
	int maxpr,count,i;
	PROTOCOLDESCRIPTOR **protos;
pdisplayNameCacheEntry pdnce;
	int em,pr,sms,a1,a2,w1,c1;
	int tick=0;
	int inphcont=(int)hContact;
    ON_SETALLEXTRAICON_CYCLE=1;
	hcontgiven=(hContact!=0);

	if (hwndContactTree==0){return;};
	tick=GetTickCount();
	if (ImageCreated==FALSE) ReloadExtraIcons();

	SetNewExtraColumnCount();
	{
		em=ExtraToColumnNum(EXTRA_ICON_EMAIL);	
		pr=ExtraToColumnNum(EXTRA_ICON_PROTO);
		sms=ExtraToColumnNum(EXTRA_ICON_SMS);
		a1=ExtraToColumnNum(EXTRA_ICON_ADV1);
		a2=ExtraToColumnNum(EXTRA_ICON_ADV2);
        w1=ExtraToColumnNum(EXTRA_ICON_WEB);
        c1=ExtraToColumnNum(EXTRA_ICON_CLIENT);
	};

    	memset(&ImgIndex,0,sizeof(&ImgIndex));
		CallService(MS_PROTO_ENUMPROTOCOLS,(WPARAM)&count,(LPARAM)&protos);
		maxpr=0;
				//calc only needed protocols
				for(i=0;i<count;i++) {
				if(protos[i]->type!=PROTOTYPE_PROTOCOL || CallProtoService(protos[i]->szName,PS_GETCAPS,PFLAGNUM_2,0)==0) continue;
				ImgIndex[maxpr]=protos[i]->szName;
				maxpr++;
				}

	if (hContact==NULL)
	{
		hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDFIRST,0,0);
	}	
	
	do {

     	szProto=NULL;
		hItem=hContact;
		if (hItem==0){continue;};
		pdnce=GetDisplayNameCacheEntry(hItem);
		if (pdnce==NULL) {continue;};
		
//		szProto=(char*)CallService(MS_PROTO_GETCONTACTBASEPROTO,(WPARAM)hContact,0);		
		szProto=pdnce->szProto;

        	{
    	DBVARIANT dbv={0};
		boolean showweb;	
		showweb=FALSE;
		if (ExtraToColumnNum(EXTRA_ICON_WEB)!=-1)
		{
			
			if (szProto != NULL)
            {
				char *homepage;
				homepage=DBGetStringA(pdnce->hContact,"UserInfo", "Homepage");
                if (!homepage)
                    homepage=DBGetStringA(pdnce->hContact,pdnce->szProto, "Homepage");
				if (homepage!=NULL)
				{											
                    showweb=TRUE;				
                    mir_free(homepage);
                }
            }
			
			PostMessage(hwndList,CLM_SETEXTRAIMAGE,(WPARAM)hItem,MAKELPARAM(ExtraToColumnNum(EXTRA_ICON_WEB),(showweb)?2:0xFF));	
		if (dbv.pszVal!=NULL) mir_free(dbv.pszVal);
		}
		}		


		{
		DBVARIANT dbv={0};
		boolean showemail;	
		showemail=TRUE;
		if (ExtraToColumnNum(EXTRA_ICON_EMAIL)!=-1)
		{
			
  	if (szProto == NULL || DBGetContactSetting(hContact, szProto, "e-mail",&dbv)) 
    {
       if (dbv.pszVal) mir_free(dbv.pszVal);
	  	 if (DBGetContactSetting(hContact, "UserInfo", "Mye-mail0", &dbv))
       {
			  	showemail=FALSE;
          if (dbv.pszVal) mir_free(dbv.pszVal);
          DBFreeVariant(&dbv);
       }
			}
		SendMessage(hwndList,CLM_SETEXTRAIMAGE,(WPARAM)hItem,MAKELPARAM(ExtraToColumnNum(EXTRA_ICON_EMAIL),(showemail)?0:0xFF));	
		if (dbv.pszVal!=NULL) mir_free(dbv.pszVal);
    DBFreeVariant(&dbv);
		}
		}

		{
		DBVARIANT dbv={0};
		boolean showsms;	
		showsms=TRUE;
		if (ExtraToColumnNum(EXTRA_ICON_SMS)!=-1)
		{
			if (szProto == NULL || DBGetContactSetting(hContact, szProto, "Cellular",&dbv)) {
          if (dbv.pszVal) mir_free(dbv.pszVal);
					if (DBGetContactSetting(hContact, "UserInfo", "MyPhone0", &dbv))
          {
						showsms=FALSE;
            if (dbv.pszVal) mir_free(dbv.pszVal);
            DBFreeVariant(&dbv);
          }
				}
			 SendMessage(hwndList,CLM_SETEXTRAIMAGE,(WPARAM)hItem,MAKELPARAM(ExtraToColumnNum(EXTRA_ICON_SMS),(showsms)?1:0xFF));	
		if (dbv.pszVal!=NULL) mir_free(dbv.pszVal);
    DBFreeVariant(&dbv);
		}
		}		

		if(ExtraToColumnNum(EXTRA_ICON_CLIENT)!=-1) {
			if(szProto==NULL) {continue;};	
			if (pdnce->ci.idxClientIcon!=0&&pdnce->ci.idxClientIcon!=-1)
			{			
							SendMessage(hwndList,CLM_SETEXTRAIMAGE,(WPARAM)hItem,MAKELPARAM(ExtraToColumnNum(EXTRA_ICON_CLIENT),pdnce->ci.idxClientIcon));	
			}
        if(ExtraToColumnNum(EXTRA_ICON_PROTO)!=-1) 
			{					
				for (i=0;i<maxpr;i++)
    			{
	    			if(!MyStrCmp(ImgIndex[i],szProto))
		    		{
			    			SendMessage(hwndList,CLM_SETEXTRAIMAGE,(WPARAM)hItem,MAKELPARAM(ExtraToColumnNum(EXTRA_ICON_PROTO),i+3));	
				        	break;
				    };
			    };				
            };
		};
		NotifyEventHooks(hExtraImageApplying,(WPARAM)hContact,0);
	  if (hcontgiven) break;
	Sleep(0);
	} while(hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDNEXT,(WPARAM)hContact,0));
	
	tick=GetTickCount()-tick;
	if (tick>0)
	{
		char buf[256];
		mir_snprintf(buf,sizeof(buf),"SetAllExtraIcons %d ms, for %x\r\n",tick,inphcont);
		TRACE(buf);
		DBWriteContactSettingDword((HANDLE)0,"CLUI","PF:Last SetAllExtraIcons Time:",tick);
	}	
    ON_SETALLEXTRAICON_CYCLE=0;
    //InvalidateRectZ(hwndList,NULL,FALSE);
    Sleep(0);

  
}
Esempio n. 25
0
void InitialiseFonts(RECT rc)
{ //this routine must be called only at start/restart b/c there are many pointers to these fonts

  if (TitleWindowFont)	 DeleteObject(TitleWindowFont);
  if (MapWindowFont)	 DeleteObject(MapWindowFont);
  if (MapWindowBoldFont) DeleteObject(MapWindowBoldFont);
  if (CDIWindowFont)	 DeleteObject(CDIWindowFont);
  if (MapLabelFont)	 DeleteObject(MapLabelFont);
  if (StatisticsFont)	 DeleteObject(StatisticsFont);

  LOGFONT hardTitleWindowLogFont;
  LOGFONT hardMapWindowLogFont;
  LOGFONT hardMapWindowBoldLogFont;
  LOGFONT hardCDIWindowLogFont; 
  LOGFONT hardMapLabelLogFont;
  LOGFONT hardStatisticsLogFont;

  memset ((char *)&hardTitleWindowLogFont, 0, sizeof (LOGFONT));
  memset ((char *)&hardMapWindowLogFont, 0, sizeof (LOGFONT));
  memset ((char *)&hardMapWindowBoldLogFont, 0, sizeof (LOGFONT));
  memset ((char *)&hardCDIWindowLogFont, 0, sizeof (LOGFONT));
  memset ((char *)&hardMapLabelLogFont, 0, sizeof (LOGFONT));
  memset ((char *)&hardStatisticsLogFont, 0, sizeof (LOGFONT));

  InitialiseFontsHardCoded(rc,
                        &hardTitleWindowLogFont,
                        &hardMapWindowLogFont,
                        &hardMapWindowBoldLogFont,
                        &hardCDIWindowLogFont, // New
                        &hardMapLabelLogFont,
                        &hardStatisticsLogFont);

  //
  // Merge the "hard" into the "auto" if one exists 
  //


  if (!IsNullLogFont(hardTitleWindowLogFont))
    autoTitleWindowLogFont = hardTitleWindowLogFont;

  if (!IsNullLogFont(hardMapWindowLogFont))
    autoMapWindowLogFont = hardMapWindowLogFont;


  if (!IsNullLogFont(hardMapWindowBoldLogFont))
    autoMapWindowBoldLogFont = hardMapWindowBoldLogFont;

  if (!IsNullLogFont(hardCDIWindowLogFont))
    autoCDIWindowLogFont = hardCDIWindowLogFont;

  if (!IsNullLogFont(hardMapLabelLogFont))
    autoMapLabelLogFont = hardMapLabelLogFont;

  if (!IsNullLogFont(hardStatisticsLogFont))
    autoStatisticsLogFont = hardStatisticsLogFont;


  InitializeOneFont (&TitleWindowFont, 
                        NULL,
                        autoTitleWindowLogFont,
                        NULL);

  InitializeOneFont (&CDIWindowFont, 
                        NULL,
                        autoCDIWindowLogFont,
                        NULL);

  InitializeOneFont (&MapLabelFont, 
                        szRegistryFontMapLabelFont, 
                        autoMapLabelLogFont,
                        NULL);

  InitializeOneFont (&StatisticsFont, 
                        NULL,
                        autoStatisticsLogFont,
                        NULL);

  InitializeOneFont (&MapWindowFont, 
                        szRegistryFontMapWindowFont, 
                        autoMapWindowLogFont,
                        NULL);

  InitializeOneFont (&MapWindowBoldFont, 
                        NULL,
                        autoMapWindowBoldLogFont,
                        NULL);

  SendMessage(hWndMapWindow,WM_SETFONT,
              (WPARAM)MapWindowFont,MAKELPARAM(TRUE,0));

}
Esempio n. 26
0
static void test_WM_LBUTTONDOWN(void)
{
    HWND hCombo, hEdit, hList;
    COMBOBOXINFO cbInfo;
    UINT x, y, item_height;
    LRESULT result;
    int i, idx;
    RECT rect;
    CHAR buffer[3];
    static const UINT choices[] = {8,9,10,11,12,14,16,18,20,22,24,26,28,36,48,72};
    static const CHAR stringFormat[] = "%2d";
    BOOL ret;
    BOOL (WINAPI *pGetComboBoxInfo)(HWND, PCOMBOBOXINFO);

    pGetComboBoxInfo = (void*)GetProcAddress(GetModuleHandleA("user32.dll"), "GetComboBoxInfo");
    if (!pGetComboBoxInfo){
        win_skip("GetComboBoxInfo is not available\n");
        return;
    }

    hCombo = CreateWindowA("ComboBox", "Combo", WS_VISIBLE|WS_CHILD|CBS_DROPDOWN,
            0, 0, 200, 150, hMainWnd, (HMENU)COMBO_ID, NULL, 0);

    for (i = 0; i < sizeof(choices)/sizeof(UINT); i++){
        sprintf(buffer, stringFormat, choices[i]);
        result = SendMessageA(hCombo, CB_ADDSTRING, 0, (LPARAM)buffer);
        ok(result == i,
           "Failed to add item %d\n", i);
    }

    cbInfo.cbSize = sizeof(COMBOBOXINFO);
    SetLastError(0xdeadbeef);
    ret = pGetComboBoxInfo(hCombo, &cbInfo);
    ok(ret, "Failed to get combobox info structure. LastError=%d\n",
       GetLastError());
    hEdit = cbInfo.hwndItem;
    hList = cbInfo.hwndList;

    trace("hMainWnd=%p, hCombo=%p, hList=%p, hEdit=%p\n", hMainWnd, hCombo, hList, hEdit);
    ok(GetFocus() == hMainWnd, "Focus not on Main Window, instead on %p\n", GetFocus());

    /* Click on the button to drop down the list */
    x = cbInfo.rcButton.left + (cbInfo.rcButton.right-cbInfo.rcButton.left)/2;
    y = cbInfo.rcButton.top + (cbInfo.rcButton.bottom-cbInfo.rcButton.top)/2;
    result = SendMessageA(hCombo, WM_LBUTTONDOWN, 0, MAKELPARAM(x, y));
    ok(result, "WM_LBUTTONDOWN was not processed. LastError=%d\n",
       GetLastError());
    ok(SendMessageA(hCombo, CB_GETDROPPEDSTATE, 0, 0),
       "The dropdown list should have appeared after clicking the button.\n");

    ok(GetFocus() == hEdit,
       "Focus not on ComboBox's Edit Control, instead on %p\n", GetFocus());
    result = SendMessageA(hCombo, WM_LBUTTONUP, 0, MAKELPARAM(x, y));
    ok(result, "WM_LBUTTONUP was not processed. LastError=%d\n",
       GetLastError());
    ok(GetFocus() == hEdit,
       "Focus not on ComboBox's Edit Control, instead on %p\n", GetFocus());

    /* Click on the 5th item in the list */
    item_height = SendMessageA(hCombo, CB_GETITEMHEIGHT, 0, 0);
    ok(GetClientRect(hList, &rect), "Failed to get list's client rect.\n");
    x = rect.left + (rect.right-rect.left)/2;
    y = item_height/2 + item_height*4;
    result = SendMessageA(hList, WM_LBUTTONDOWN, 0, MAKELPARAM(x, y));
    ok(!result, "WM_LBUTTONDOWN was not processed. LastError=%d\n",
       GetLastError());
    ok(GetFocus() == hEdit,
       "Focus not on ComboBox's Edit Control, instead on %p\n", GetFocus());

    result = SendMessageA(hList, WM_MOUSEMOVE, 0, MAKELPARAM(x, y));
    ok(!result, "WM_MOUSEMOVE was not processed. LastError=%d\n",
       GetLastError());
    ok(GetFocus() == hEdit,
       "Focus not on ComboBox's Edit Control, instead on %p\n", GetFocus());
    ok(SendMessageA(hCombo, CB_GETDROPPEDSTATE, 0, 0),
       "The dropdown list should still be visible.\n");

    result = SendMessageA(hList, WM_LBUTTONUP, 0, MAKELPARAM(x, y));
    ok(!result, "WM_LBUTTONUP was not processed. LastError=%d\n",
       GetLastError());
    ok(GetFocus() == hEdit,
       "Focus not on ComboBox's Edit Control, instead on %p\n", GetFocus());
    ok(!SendMessageA(hCombo, CB_GETDROPPEDSTATE, 0, 0),
       "The dropdown list should have been rolled up.\n");
    idx = SendMessageA(hCombo, CB_GETCURSEL, 0, 0);
    ok(idx, "Current Selection: expected %d, got %d\n", 4, idx);

    DestroyWindow(hCombo);
}
Esempio n. 27
0
// same as AddPage() but does it at given position
bool wxNotebook::InsertPage(size_t nPage,
                            wxNotebookPage *pPage,
                            const wxString& strText,
                            bool bSelect,
                            int imageId)
{
    wxCHECK_MSG( pPage != NULL, false, wxT("NULL page in wxNotebook::InsertPage") );
    wxCHECK_MSG( IS_VALID_PAGE(nPage) || nPage == GetPageCount(), false,
                 wxT("invalid index in wxNotebook::InsertPage") );

    wxASSERT_MSG( pPage->GetParent() == this,
                  wxT("notebook pages must have notebook as parent") );

    // add a new tab to the control
    // ----------------------------

    // init all fields to 0
    TC_ITEM tcItem;
    wxZeroMemory(tcItem);

    // set the image, if any
    if ( imageId != -1 )
    {
        tcItem.mask |= TCIF_IMAGE;
        tcItem.iImage  = imageId;
    }

    // and the text
    if ( !strText.empty() )
    {
        tcItem.mask |= TCIF_TEXT;
        tcItem.pszText = wxMSW_CONV_LPTSTR(strText);
    }

    // hide the page: unless it is selected, it shouldn't be shown (and if it
    // is selected it will be shown later)
    HWND hwnd = GetWinHwnd(pPage);
    SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_VISIBLE);

    // this updates internal flag too -- otherwise it would get out of sync
    // with the real state
    pPage->Show(false);


    // fit the notebook page to the tab control's display area: this should be
    // done before adding it to the notebook or TabCtrl_InsertItem() will
    // change the notebooks size itself!
    AdjustPageSize(pPage);

    // finally do insert it
    if ( TabCtrl_InsertItem(GetHwnd(), nPage, &tcItem) == -1 )
    {
        wxLogError(wxT("Can't create the notebook page '%s'."), strText.c_str());

        return false;
    }

    // need to update the bg brush when the first page is added
    // so the first panel gets the correct themed background
    if ( m_pages.empty() )
    {
#if wxUSE_UXTHEME
        UpdateBgBrush();
#endif // wxUSE_UXTHEME
    }

    // succeeded: save the pointer to the page
    m_pages.Insert(pPage, nPage);

    // we may need to adjust the size again if the notebook size changed:
    // normally this only happens for the first page we add (the tabs which
    // hadn't been there before are now shown) but for a multiline notebook it
    // can happen for any page at all as a new row could have been started
    if ( m_pages.GetCount() == 1 || HasFlag(wxNB_MULTILINE) )
    {
        AdjustPageSize(pPage);

        // Additionally, force the layout of the notebook itself by posting a
        // size event to it. If we don't do it, notebooks with pages on the
        // left or the right side may fail to account for the fact that they
        // are now big enough to fit all all of their pages on one row and
        // still reserve space for the second row of tabs, see #1792.
        const wxSize s = GetSize();
        ::PostMessage(GetHwnd(), WM_SIZE, SIZE_RESTORED, MAKELPARAM(s.x, s.y));
    }

    // now deal with the selection
    // ---------------------------

    // if the inserted page is before the selected one, we must update the
    // index of the selected page
    if ( int(nPage) <= m_selection )
    {
        // one extra page added
        m_selection++;
    }

    DoSetSelectionAfterInsertion(nPage, bSelect);

    InvalidateBestSize();

    return true;
}
Esempio n. 28
0
void CToolBarCtrlX::SetPadding(CSize sizPadding)
{
	SendMessage(TB_SETPADDING, 0, MAKELPARAM(sizPadding.cx, sizPadding.cy));
}
Esempio n. 29
0
HWND CreateCancelDialog(void)
{
	HWND hwndButton,dlgHdl;

	WORD *p, *pdlgtemplate,baseunitX,baseunitY;
	int nchar;
	int scrnWidth,scrnHeight;
	int buttonX, buttonY, buttonWidth, buttonHeight;
	int textX, textY, textWidth, textHeight;
	DWORD lStyle,baseunits;
	HDC screen;
	LOGFONT lf;

	/* allocate some memory to play with  */
	pdlgtemplate = p = (PWORD) rmalloc (1000);

	screen = CreateDC ("DISPLAY", NULL, NULL, NULL);
	scrnWidth  = GetDeviceCaps (screen, HORZRES);
	scrnHeight = GetDeviceCaps (screen, VERTRES);
	DeleteDC (screen);
	baseunits = GetDialogBaseUnits();

	/* start to fill in the dlgtemplate information.  addressing by WORDs */
	lStyle = WS_CAPTION | DS_MODALFRAME | WS_SYSMENU;

	baseunitX=LOWORD(baseunits);
	baseunitY=HIWORD(baseunits);

	*p++ = LOWORD (lStyle);
	*p++ = HIWORD (lStyle);
	*p++ = 0;		/* LOWORD (lExtendedStyle) */
	*p++ = 0;		/* HIWORD (lExtendedStyle) */
	*p++ = 0;		/* NumberOfItems */
	*p++ = ((scrnWidth*4)/3)/baseunitX;		// x
	*p++ = ((scrnHeight*8)/3)/baseunitY;	// y
	*p++ = DIALOG_WIDTH;	/* cx */
	*p++ = DIALOG_HEIGHT;	/* cy */
	*p++ = 0;		/* Menu */
	*p++ = 0;		/* Class */

	/* copy the title of the dialog */
	nchar = nCopyAnsiToWideChar (p, (char *) "Printing in Progress");
	p += nchar;

	dlgHdl = CreateDialogIndirectParam (ghInst, (LPDLGTEMPLATE) pdlgtemplate, ghMainWindow,
										(DLGPROC) PrintDlgProc, (LPARAM) 0);

	rfree(pdlgtemplate);

	// Add a text field
	textWidth = 19*baseunitX;
	textHeight = baseunitY;
	textX =    (((DIALOG_WIDTH*baseunitX)/4) - textWidth)
		       / 2;
	textY =    (((DIALOG_HEIGHT*baseunitY)/8) - textHeight)
			   / 4;
	hwndText = CreateWindow ("static", "",WS_VISIBLE | WS_CHILD | SS_CENTER,
									textX, textY, textWidth, textHeight,
									dlgHdl, (HMENU) 0, ghInst, 0);


	// Add a Cancel button:
	buttonWidth = 10*baseunitX;
	buttonHeight = (3*baseunitY)/2;
	buttonX =    (((DIALOG_WIDTH*baseunitX)/4) - buttonWidth)
		       / 2;
	buttonY =  (3 *  (((DIALOG_HEIGHT*baseunitY)/8) - buttonHeight))
			   / 5;
	hwndButton = CreateWindow ("button", "Cancel", WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
									buttonX, buttonY, buttonWidth, buttonHeight,
									dlgHdl, (HMENU) 0, ghInst, 0);
	SetLogFontData (&lf,"MS Sans Serif",0,8);
	SendMessage(hwndButton,WM_SETFONT,(WPARAM)CreateFontIndirect (&lf),MAKELPARAM (TRUE,0));
	SendMessage(hwndText,WM_SETFONT,(WPARAM)CreateFontIndirect (&lf),MAKELPARAM (TRUE,0));

	ShowWindow (dlgHdl,SW_SHOWNORMAL);

	return dlgHdl;
}
Esempio n. 30
0
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    HINSTANCE hInst;
    RECT rect;
    static HCURSOR 	hCursor;
    static BOOL	bSplitterMoving;
    static DWORD dwSplitterPos;

    switch (uMsg)
    {
    case WM_CREATE:
    {
        hInst = ((LPCREATESTRUCT)lParam)->hInstance;
#pragma warning(push)
#pragma warning (disable:4302)
        hCursor = LoadCursor(NULL, MAKEINTRESOURCE(IDC_SIZENS));
#pragma warning (pop)

        bAssemble = CreateWindowEx(0, "Button", "Assemble (F5)", WS_CHILD | WS_VISIBLE, 0, 0, 0, 0, hWnd, (HMENU)IDM_COMPILE, hInst, 0);
        CreateASMEditor(hWnd, hInst);
        CreateOutputWindow(hWnd, hInst);
        SetWindowsHookEx(WH_KEYBOARD, &hookWndProc, NULL, GetCurrentThreadId());

        bSplitterMoving = FALSE;
        dwSplitterPos = 250;
        return 0;
    } break;
    case WM_SIZE:
    {
        if ((wParam != SIZE_MINIMIZED) && (HIWORD(lParam) < dwSplitterPos))
            dwSplitterPos = HIWORD(lParam) - 10;

        // Adjust the children's size and position
        MoveWindow(bAssemble,  0,  0, LOWORD(lParam), 25, TRUE);
        MoveWindow(hWinInput,  0, 25, LOWORD(lParam), dwSplitterPos - 1, TRUE);
        MoveWindow(hWinOutput, 0, 25 + dwSplitterPos + 2, LOWORD(lParam), HIWORD(lParam) - dwSplitterPos - 2 - 25, TRUE);
        return 0;
    }break;
    case WM_MOUSEMOVE:
        if (HIWORD(lParam) > 10) // do not allow above this mark
        {
            SetCursor(hCursor);
            if (wParam == MK_LBUTTON && bSplitterMoving)
            {
                GetClientRect(hWnd, &rect);
                if (HIWORD(lParam) > rect.bottom)
                    return 0;

                dwSplitterPos = HIWORD(lParam);
                SendMessage(hWnd, WM_SIZE, 0, MAKELPARAM(rect.right, rect.bottom));
            }
        }
        return 0;
    case WM_COMMAND:
        if (wParam == IDM_COMPILE)
            FasmCompile();
        break;
    case WM_LBUTTONDOWN:
        SetCursor(hCursor);
        bSplitterMoving = TRUE;
        SetCapture(hWnd);
        return 0;
    case WM_LBUTTONUP:
        ReleaseCapture();
        bSplitterMoving = FALSE;
        return 0;
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    }
    return DefWindowProc(hWnd, uMsg, wParam, lParam);
}