Exemplo n.º 1
0
void cheat_handle_debug ( HWND wnd )
{
	static const int	data_size[4] = { 1, 2, 4, 4 };
	struct debug_info	*debug = &cheat_state->debug;
	int					move = 0, hist_chng = 0;

	if ( !cheat_state->debug_enabled )
		return;

	/* go to pointer */
	if ( KEY_PRESSED(VK_NUMPAD1) )
	{
		setDebugPointer( *(void **)debug->cursor_data );
		hist_chng = 1;
	}

	/* go back */
	if ( KEY_PRESSED(VK_NUMPAD7) )
	{
		if ( debug->hist_pos > 0 )
		{
			debug->hist_pos--;
			hist_chng = 1;
		}
		else if ( debug->hist_pos == 0 )
			setDebugPointer( (void *)NULL );
	}

	/* change data type */
	if ( KEY_PRESSED(VK_DIVIDE) )
		debug->data_type = ( debug->data_type + 1 ) % 4;

	/* inc/dec value */
	if ( KEY_DOWN(VK_ADD) || KEY_DOWN(VK_SUBTRACT) )
	{
		const int	value = KEY_DOWN( VK_ADD ) ? 1 : -1;
		uint8_t		data[4] = { 0, 0, 0, 0 };

		if ( memcpy_safe(data, debug->ptr[debug->hist_pos] + debug->offset[debug->hist_pos], data_size[debug->data_type]) )
		{
			switch ( debug->data_type )
			{
#pragma warning( disable : 4244 )

			case 0:
				( *(uint8_t *)data ) += ( uint8_t ) value;
				break;

			case 1:
				( *(uint16_t *)data ) += ( uint16_t ) value;
				break;

			case 2:
				( *(uint32_t *)data ) += ( uint32_t ) value;
				break;

			case 3:
				( *(float *)data ) += (float)value / 10.0f;
				break;
			}

			memcpy_safe( debug->ptr[debug->hist_pos] + debug->offset[debug->hist_pos], data, data_size[debug->data_type] );
		}
	}

	/* copy info to clipboard */
	if ( KEY_PRESSED(VK_MULTIPLY) )
	{
		if ( OpenClipboard(wnd) )
		{
			HGLOBAL mem = GlobalAlloc( GMEM_MOVEABLE, sizeof(debug->ptr_hist_str) );

			if ( mem != NULL )
			{
				char	*str = (char *)GlobalLock( mem );

				strlcpy( str, debug->ptr_hist_str, sizeof(debug->ptr_hist_str) );
				Log( "%s", str );
				GlobalUnlock( str );

				EmptyClipboard();

				if ( !SetClipboardData(CF_TEXT, mem) )
					Log( "SetClipboardData() %d", GetLastError() );

				/*SetClipboardData(CF_TEXT, mem);*/
			}

			CloseClipboard();
		}
		else
		{
			Log( "OpenClipboard() %d", GetLastError() );
		}
	}

	if ( KEY_PRESSED(VK_NUMPAD4) )
		move -= data_size[debug->data_type];
	if ( KEY_PRESSED(VK_NUMPAD6) )
		move += data_size[debug->data_type];
	if ( KEY_PRESSED(VK_NUMPAD8) )
		move += -16;
	if ( KEY_PRESSED(VK_NUMPAD2) )
		move += 16;
	if ( KEY_PRESSED(VK_NUMPAD9) )
		move += -160;
	if ( KEY_PRESSED(VK_NUMPAD3) )
		move += 160;

	debug->offset[debug->hist_pos] += move;

	if ( move != 0 || hist_chng )
	{
		memset( debug->modify_time, 0, DEBUG_DATA_SIZE * sizeof(uint32_t) );
		debug->data_prev_clear = 1;
	}

	for ( int i = 0; i < 9; i++ )
		KEY_CONSUME( VK_NUMPAD1 + i );
	KEY_CONSUME( VK_MULTIPLY );
	KEY_CONSUME( VK_DIVIDE );
	KEY_CONSUME( VK_ADD );
	KEY_CONSUME( VK_SUBTRACT );
}
Exemplo n.º 2
0
bool CDeskBand::WriteStringToClipboard(const std::wstring& sClipdata, HWND hOwningWnd)
{
    // copy the string in ASCII and UNICODE to the clipboard

    // convert the unicode string to ASCII
    std::string sClipdataA;
    int len = (int)sClipdata.size();
    if (len==0)
        return false;

    int size = len*4;
    char * narrow = new char[size];
    int ret = WideCharToMultiByte(CP_ACP, 0, sClipdata.c_str(), len, narrow, size-1, NULL, NULL);
    narrow[ret] = 0;
    sClipdataA = std::string(narrow);
    delete [] narrow;

    if (OpenClipboard(hOwningWnd))
    {
        EmptyClipboard();
        HGLOBAL hClipboardData;
        hClipboardData = GlobalAlloc(GMEM_DDESHARE, sClipdataA.size()+1);
        if (hClipboardData)
        {
            char * pchData;
            pchData = (char*)GlobalLock(hClipboardData);
            if (pchData)
            {
                strcpy_s(pchData, sClipdataA.size()+1, sClipdataA.c_str());
                if (GlobalUnlock(hClipboardData))
                {
                    if (SetClipboardData(CF_TEXT,hClipboardData)==NULL)
                    {
                        CloseClipboard();
                        return false;
                    }
                }
                else
                {
                    CloseClipboard();
                    return false;
                }
            }
            else
            {
                CloseClipboard();
                return false;
            }
        }
        else
        {
            CloseClipboard();
            return false;
        }

        hClipboardData = GlobalAlloc(GMEM_DDESHARE, sClipdataA.size()*sizeof(TCHAR)+2);
        if (hClipboardData)
        {
            TCHAR * pchData;
            pchData = (TCHAR*)GlobalLock(hClipboardData);
            if (pchData)
            {
                _tcscpy_s(pchData, sClipdata.size()+1, sClipdata.c_str());
                if (GlobalUnlock(hClipboardData))
                {
                    if (SetClipboardData(CF_UNICODETEXT,hClipboardData)==NULL)
                    {
                        CloseClipboard();
                        return false;
                    }
                }
                else
                {
                    CloseClipboard();
                    return false;
                }
            }
            else
            {
                CloseClipboard();
                return false;
            }
        }
        else
        {
            CloseClipboard();
            return false;
        }
        CloseClipboard();
        return true;
    }
    return false;
}
Exemplo n.º 3
0
static INT_PTR CALLBACK CopyAwayMsgDlgProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	AwayMsgDlgData *dat = (AwayMsgDlgData *)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);

	switch (message) {
		case WM_INITDIALOG:
		{
			TCHAR str[256], format[128];
			TCHAR *contactName;

			TranslateDialogDefault(hwndDlg);
			dat = (AwayMsgDlgData *)mir_alloc(sizeof(AwayMsgDlgData));
			SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)dat);

			dat->hContact = lParam;
			dat->hSeq = (HANDLE)CallContactService(dat->hContact, PSS_GETAWAYMSG, 0, 0);
			dat->hAwayMsgEvent = dat->hSeq ? HookEventMessage(ME_PROTO_ACK, hwndDlg, HM_AWAYMSG) : NULL;
			WindowList_Add(hWindowList2, hwndDlg, dat->hContact);
			contactName = (TCHAR *)pcli->pfnGetContactDisplayName(dat->hContact, 0);
			GetWindowText(hwndDlg, format, _countof(format));
			mir_sntprintf(str, format, contactName);
			SetWindowText(hwndDlg, str);
			if (!dat->hSeq)
				DestroyWindow(hwndDlg);
			return TRUE;
		}

		case HM_AWAYMSG:
		{
			ACKDATA *ack = (ACKDATA *)lParam;
			if (ack->hContact != dat->hContact || ack->type != ACKTYPE_AWAYMSG) {
				DestroyWindow(hwndDlg);
				break;
			}
			if (ack->result != ACKRESULT_SUCCESS) {
				DestroyWindow(hwndDlg);
				break;
			}
			if (dat->hAwayMsgEvent && ack->hProcess == dat->hSeq) {
				UnhookEvent(dat->hAwayMsgEvent);
				dat->hAwayMsgEvent = NULL;
			}

			if (!OpenClipboard(hwndDlg)) {
				DestroyWindow(hwndDlg);
				break;
			}
			if (EmptyClipboard()) {
				TCHAR msg[1024];
				TCHAR *tszMsg = StrNormNewline((TCHAR *)ack->lParam);
				_tcsncpy_s(msg, tszMsg, _TRUNCATE);
				mir_free(tszMsg);
				size_t len = mir_tstrlen(msg);
				if (len) {
					LPTSTR lptstrCopy;
					HGLOBAL hglbCopy = GlobalAlloc(GMEM_MOVEABLE, (len + 1) * sizeof(TCHAR));
					if (hglbCopy == NULL) {
						CloseClipboard();
						DestroyWindow(hwndDlg);
						break;
					}
					lptstrCopy = (LPTSTR)GlobalLock(hglbCopy);
					memcpy(lptstrCopy, msg, len * sizeof(TCHAR));
					lptstrCopy[len] = (TCHAR)0;
					GlobalUnlock(hglbCopy);

					SetClipboardData(CF_UNICODETEXT, hglbCopy);
				}
			}
			CloseClipboard();
			DestroyWindow(hwndDlg);
			break;
		}

		case WM_COMMAND:
			switch (LOWORD(wParam)) {
				case IDCANCEL:
				case IDOK:
					DestroyWindow(hwndDlg);
				break;
			}
			break;

		case WM_CLOSE:
			DestroyWindow(hwndDlg);
			break;

		case WM_DESTROY:
			if (dat->hAwayMsgEvent) UnhookEvent(dat->hAwayMsgEvent);
			WindowList_Remove(hWindowList2, hwndDlg);
			mir_free(dat);
			break;
	}
	return FALSE;
}
Exemplo n.º 4
0
LRESULT CMainWindow::OnCommand(UINT nMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
    switch (LOWORD(wParam))
    {
        case IDM_HELPINFO:
        {
            HICON paintIcon = LoadIcon(hProgInstance, MAKEINTRESOURCE(IDI_APPICON));
            TCHAR infotitle[100];
            TCHAR infotext[200];
            LoadString(hProgInstance, IDS_INFOTITLE, infotitle, SIZEOF(infotitle));
            LoadString(hProgInstance, IDS_INFOTEXT, infotext, SIZEOF(infotext));
            ShellAbout(m_hWnd, infotitle, infotext, paintIcon);
            DeleteObject(paintIcon);
            break;
        }
        case IDM_HELPHELPTOPICS:
            HtmlHelp(m_hWnd, _T("help\\Paint.chm"), 0, 0);
            break;
        case IDM_FILEEXIT:
            SendMessage(WM_CLOSE, wParam, lParam);
            break;
        case IDM_FILENEW:
        {
            BOOL reset = TRUE;
            if (!imageModel.IsImageSaved())
            {
                TCHAR programname[20];
                TCHAR saveprompttext[100];
                TCHAR temptext[500];
                LoadString(hProgInstance, IDS_PROGRAMNAME, programname, SIZEOF(programname));
                LoadString(hProgInstance, IDS_SAVEPROMPTTEXT, saveprompttext, SIZEOF(saveprompttext));
                _stprintf(temptext, saveprompttext, filename);
                switch (MessageBox(temptext, programname, MB_YESNOCANCEL | MB_ICONQUESTION))
                {
                    case IDNO:
                        imageModel.imageSaved = TRUE; //TODO: move to ImageModel
                        break;
                    case IDYES:
                        saveImage(FALSE);
                        break;
                    case IDCANCEL:
                        reset = FALSE;
                        break;
                }
            }
            if (reset && imageModel.IsImageSaved()) //TODO: move to ImageModel
            {
                imageModel.Clear();
                imageModel.ClearHistory();
            }
            break;
        }
        case IDM_FILEOPEN:
            if (GetOpenFileName(&ofn) != 0)
            {
                HBITMAP bmNew = NULL;
                LoadDIBFromFile(&bmNew, ofn.lpstrFile, &fileTime, &fileSize, &fileHPPM, &fileVPPM);
                if (bmNew != NULL)
                {
                    UpdateApplicationProperties(bmNew, ofn.lpstrFileTitle, ofn.lpstrFileTitle);
                }
            }
            break;
        case IDM_FILESAVE:
            saveImage(TRUE);
            break;
        case IDM_FILESAVEAS:
            saveImage(FALSE);
            break;
        case IDM_FILEPAGESETUP:
            // DUMMY: Shows the dialog only, no functionality
            PAGESETUPDLG psd;
            ZeroMemory(&psd, sizeof(psd));
            psd.lStructSize = sizeof(psd);
            psd.hwndOwner = m_hWnd;
            PageSetupDlg(&psd);
            break;
        case IDM_FILEPRINT:
            // TODO: Test whether it actually works
            PRINTDLG pd;
            ZeroMemory(&pd, sizeof(pd));
            pd.lStructSize = sizeof(pd);
            pd.hwndOwner = m_hWnd;
            pd.hDevMode = NULL;  // freed by user
            pd.hDevNames = NULL;  // freed by user
            pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC;
            pd.nCopies = 1;
            pd.nFromPage = 0xffff;
            pd.nToPage = 0xffff;
            pd.nMinPage = 1;
            pd.nMaxPage = 0xffff;
            if (PrintDlg(&pd) == TRUE)
            {
                BitBlt(pd.hDC, 0, 0, imageModel.GetWidth(), imageModel.GetHeight(), imageModel.GetDC(), 0, 0, SRCCOPY);
                DeleteDC(pd.hDC);
            }
            if (pd.hDevMode)
                GlobalFree(pd.hDevMode);
            if (pd.hDevNames)
                GlobalFree(pd.hDevNames);
            break;
        case IDM_FILEASWALLPAPERPLANE:
            RegistrySettings::SetWallpaper(filepathname, 1, 1);
            break;
        case IDM_FILEASWALLPAPERCENTERED:
            RegistrySettings::SetWallpaper(filepathname, 1, 0);
            break;
        case IDM_FILEASWALLPAPERSTRETCHED:
            RegistrySettings::SetWallpaper(filepathname, 2, 0);
            break;
        case IDM_EDITUNDO:
            imageModel.Undo();
            imageArea.Invalidate(FALSE);
            break;
        case IDM_EDITREDO:
            imageModel.Redo();
            imageArea.Invalidate(FALSE);
            break;
        case IDM_EDITCOPY:
            OpenClipboard();
            EmptyClipboard();
            SetClipboardData(CF_BITMAP, CopyImage(selectionModel.GetBitmap(), IMAGE_BITMAP, 0, 0, LR_COPYRETURNORG));
            CloseClipboard();
            break;
        case IDM_EDITCUT:
            /* Copy */
            SendMessage(WM_COMMAND, IDM_EDITCOPY, 0);
            /* Delete selection */
            SendMessage(WM_COMMAND, IDM_EDITDELETESELECTION, 0);
            break;
        case IDM_EDITPASTE:
            OpenClipboard();
            if (GetClipboardData(CF_BITMAP) != NULL)
            {
                InsertSelectionFromHBITMAP((HBITMAP) GetClipboardData(CF_BITMAP), m_hWnd);
            }
            CloseClipboard();
            break;
        case IDM_EDITDELETESELECTION:
        {
            /* remove selection window and already painted content using undo */
            imageModel.Undo();
            break;
        }
        case IDM_EDITSELECTALL:
        {
            HWND hToolbar = FindWindowEx(toolBoxContainer.m_hWnd, NULL, TOOLBARCLASSNAME, NULL);
            SendMessage(hToolbar, TB_CHECKBUTTON, ID_RECTSEL, MAKELPARAM(TRUE, 0));
            toolBoxContainer.SendMessage(WM_COMMAND, ID_RECTSEL);
            //TODO: do this properly
            startPaintingL(imageModel.GetDC(), 0, 0, paletteModel.GetFgColor(), paletteModel.GetBgColor());
            whilePaintingL(imageModel.GetDC(), imageModel.GetWidth(), imageModel.GetHeight(), paletteModel.GetFgColor(), paletteModel.GetBgColor());
            endPaintingL(imageModel.GetDC(), imageModel.GetWidth(), imageModel.GetHeight(), paletteModel.GetFgColor(), paletteModel.GetBgColor());
            break;
        }
        case IDM_EDITCOPYTO:
            if (GetSaveFileName(&ofn) != 0)
                SaveDIBToFile(selectionModel.GetBitmap(), ofn.lpstrFile, imageModel.GetDC(), NULL, NULL, fileHPPM, fileVPPM);
            break;
        case IDM_EDITPASTEFROM:
            if (GetOpenFileName(&ofn) != 0)
            {
                HBITMAP bmNew = NULL;
                LoadDIBFromFile(&bmNew, ofn.lpstrFile, &fileTime, &fileSize, &fileHPPM, &fileVPPM);
                if (bmNew != NULL)
                {
                    InsertSelectionFromHBITMAP(bmNew, m_hWnd);
                    DeleteObject(bmNew);
                }
            }
            break;
        case IDM_COLORSEDITPALETTE:
            if (ChooseColor(&choosecolor))
                paletteModel.SetFgColor(choosecolor.rgbResult);
            break;
        case IDM_COLORSMODERNPALETTE:
            paletteModel.SelectPalette(1);
            break;
        case IDM_COLORSOLDPALETTE:
            paletteModel.SelectPalette(2);
            break;
        case IDM_IMAGEINVERTCOLORS:
        {
            imageModel.InvertColors();
            break;
        }
        case IDM_IMAGEDELETEIMAGE:
            imageModel.CopyPrevious();
            Rect(imageModel.GetDC(), 0, 0, imageModel.GetWidth(), imageModel.GetHeight(), paletteModel.GetBgColor(), paletteModel.GetBgColor(), 0, TRUE);
            imageArea.Invalidate(FALSE);
            break;
        case IDM_IMAGEROTATEMIRROR:
            switch (mirrorRotateDlg())
            {
                case 1: /* flip horizontally */
                    if (selectionWindow.IsWindowVisible())
                        selectionModel.FlipHorizontally();
                    else
                        imageModel.FlipHorizontally();
                    break;
                case 2: /* flip vertically */
                    if (selectionWindow.IsWindowVisible())
                        selectionModel.FlipVertically();
                    else
                        imageModel.FlipVertically();
                    break;
                case 3: /* rotate 90 degrees */
                    break;
                case 4: /* rotate 180 degrees */
                    if (selectionWindow.IsWindowVisible())
                        selectionModel.RotateNTimes90Degrees(2);
                    else
                        imageModel.RotateNTimes90Degrees(2);
                    break;
                case 5: /* rotate 270 degrees */
                    break;
            }
            break;
        case IDM_IMAGEATTRIBUTES:
        {
            if (attributesDlg())
            {
                imageModel.Crop(widthSetInDlg, heightSetInDlg, 0, 0);
            }
            break;
        }
        case IDM_IMAGESTRETCHSKEW:
        {
            if (changeSizeDlg())
            {
                imageModel.StretchSkew(stretchSkew.percentage.x, stretchSkew.percentage.y,
                                       stretchSkew.angle.x, stretchSkew.angle.y);
            }
            break;
        }
        case IDM_IMAGEDRAWOPAQUE:
            toolsModel.SetBackgroundTransparent(!toolsModel.IsBackgroundTransparent());
            break;
        case IDM_IMAGECROP:
            imageModel.Insert((HBITMAP) CopyImage(selectionModel.GetBitmap(), IMAGE_BITMAP, 0, 0, LR_COPYRETURNORG));
            break;

        case IDM_VIEWTOOLBOX:
            toolBoxContainer.ShowWindow(toolBoxContainer.IsWindowVisible() ? SW_HIDE : SW_SHOW);
            alignChildrenToMainWindow();
            break;
        case IDM_VIEWCOLORPALETTE:
            paletteWindow.ShowWindow(paletteWindow.IsWindowVisible() ? SW_HIDE : SW_SHOW);
            alignChildrenToMainWindow();
            break;
        case IDM_VIEWSTATUSBAR:
            ::ShowWindow(hStatusBar, ::IsWindowVisible(hStatusBar) ? SW_HIDE : SW_SHOW);
            alignChildrenToMainWindow();
            break;
        case IDM_FORMATICONBAR:
            textEditWindow.ShowWindow(textEditWindow.IsWindowVisible() ? SW_HIDE : SW_SHOW);

        case IDM_VIEWSHOWGRID:
            showGrid = !showGrid;
            imageArea.Invalidate(FALSE);
            break;
        case IDM_VIEWSHOWMINIATURE:
            showMiniature = !showMiniature;
            miniature.ShowWindow(showMiniature ? SW_SHOW : SW_HIDE);
            break;

        case IDM_VIEWZOOM125:
            zoomTo(125, 0, 0);
            break;
        case IDM_VIEWZOOM25:
            zoomTo(250, 0, 0);
            break;
        case IDM_VIEWZOOM50:
            zoomTo(500, 0, 0);
            break;
        case IDM_VIEWZOOM100:
            zoomTo(1000, 0, 0);
            break;
        case IDM_VIEWZOOM200:
            zoomTo(2000, 0, 0);
            break;
        case IDM_VIEWZOOM400:
            zoomTo(4000, 0, 0);
            break;
        case IDM_VIEWZOOM800:
            zoomTo(8000, 0, 0);
            break;

        case IDM_VIEWFULLSCREEN:
            fullscreenWindow.ShowWindow(SW_SHOW);
            ShowWindow(SW_HIDE);
            break;
    }
    return 0;
}
Exemplo n.º 5
0
void CSmcView::OnLButtonUp(UINT nFlags, CPoint point) 
{
    CSmcDoc* pDoc = GetDocument();
    if ( m_bSelected ) {
        ReleaseCapture();
        m_bSelected = FALSE;
        InvalidateRect(NULL, FALSE);
        UpdateWindow();
        pDoc->m_bFrozen = FALSE;

        // Well, start forming text for Clipboard
        CString ResultStr;

        // Good, getting reall numbers of strings
        int ScrollIndex = GetScrollPos(SB_VERT)+1;
        ASSERT(m_nStartSelectY>=0);
        POSITION pos = m_strList.FindIndex(ScrollIndex+m_nStartSelectY);
        ASSERT(pos);
        int i = m_nStartSelectY;
        do { 
            CString tmpStr = m_strList.GetAt(pos);
            char* ptr = (LPSTR)(LPCSTR)tmpStr;
            int count = 0;
//            if (i == m_nStartSelectY && i == m_nEndSelectY) {
                // Skip to StartX character
                while ( count < m_nStartSelectX && *ptr){
                    if ( *ptr == 0x1B ){
                        ptr = SkipAnsi(ptr);
                    }
                    else {
                        count++;
                        ptr++;
                    }
                } 
                
//            }
            // characters skipped now copy nessesary info to string
            do {
                if ( *ptr == '\n' /*|| *ptr == '\r'*/ ) {
                    ptr++;
                    continue;
                }
                if ( *ptr == 0x1B ) {
                    ptr = SkipAnsi(ptr);
                    continue;
                }
                if ( i == m_nEndSelectY && count >= m_nEndSelectX ) 
                    break;
                ResultStr+= *ptr++;
                count++;
            } while ( *ptr );
            if ( i != m_nEndSelectY ) 
                ResultStr +="\r\n";
            i++;
            pos = m_strList.FindIndex(ScrollIndex+i);
        } while ( i<=m_nEndSelectY && pos );
        // Put to clipboard
		if (strlen(ResultStr) != 0)
		{
			VERIFY(OpenClipboard());

			VERIFY(EmptyClipboard());

			LCID lc = GetUserDefaultLCID();
			HANDLE hData = GlobalAlloc(GMEM_ZEROINIT, sizeof(lc) );
			LCID* pLc = (LCID*)GlobalLock(hData);
			*pLc = lc;
			GlobalUnlock(hData);
			SetClipboardData(CF_LOCALE, hData);
			hData = GlobalAlloc(GMEM_ZEROINIT, ResultStr.GetLength()+1 );
			char* buff = (char*)GlobalLock(hData);
			strcpy (buff, (LPSTR)(LPCSTR)ResultStr);
			GlobalUnlock(hData);
			SetClipboardData(CF_TEXT, hData);
			CloseClipboard();
		}
    }
	CView::OnLButtonUp(nFlags, point);
}
Exemplo n.º 6
0
bool checkLicense()
{
	CString strcpuid = GetCPUID();

	unsigned char szMDTemp[16];
	MD5_CTX Md5;
	Md5.MD5Update((unsigned char *)strcpuid.GetBuffer(),strcpuid.GetLength());
	Md5.MD5Final(szMDTemp);

	char m_szMD5Pass[50];
	for (int i = 0; i < 16; i ++) 
		wsprintf(&m_szMD5Pass[i * 2], "%02x", szMDTemp[i] );
	CString StrMd5CpuID = m_szMD5Pass;

	DWORD cfgHandle=cfgOpenFile("core.bcf");
	if(cfgHandle<0x10)
		return false;
	CString license = cfgGetValue(cfgHandle,"License","License","");
	cfgClose(cfgHandle);

	yxyDES des;
	string key = strcpuid.GetBuffer();
	des.InitializeKey(key);


	des.DecryptAnyLength(license.GetBuffer());
	string strtmp = des.GetPlaintextAnyLength();
	string lsecpuid;
	string date;
	if (strtmp.length() == 40)
	{
		lsecpuid = strtmp.substr(0, 32);
		date = strtmp.substr(32, 40);
	}



	string lcs = m_szMD5Pass;

	CTime tmnow = CTime::GetCurrentTime();
	string strNow = tmnow.Format("%Y%m%d").GetBuffer();


	if (lcs == lsecpuid &&  strNow <= date)
		return true;
	else
	{
		CString s;
		s.Format("您的服务器未注册或已过期,请与服务商联系。\n\n请将以下机器码发送给服务商,获取注册码文件:\n\n%s\n\n",strcpuid.GetBuffer());
		MessageBox(NULL, s,"提示",MB_ICONERROR);

		s="机器码已复制到您的剪贴板中,直接Ctrl+V粘贴机器码!";
		MessageBox(NULL, s,"提示",MB_ICONINFORMATION);

		OpenClipboard(NULL);
		EmptyClipboard();
		HANDLE hData=GlobalAlloc(GMEM_MOVEABLE, strcpuid.GetLength()+5); 
		if (hData==NULL)  
		{ 
			CloseClipboard(); 
			return TRUE; 
		}
		LPTSTR szMemName=(LPTSTR)GlobalLock(hData); 
		lstrcpy(szMemName,strcpuid); 
		SetClipboardData(CF_TEXT,hData); 
		GlobalUnlock(hData);  
		GlobalFree(hData); 
		CloseClipboard(); 
		return false;
	}
}
Exemplo n.º 7
0
bool BaseApp::onKey(const uint key, const bool pressed) {
//#if defined(DEBUG) && defined(WIN32)
#ifdef WIN32
    if (pressed && key == KEY_F12) {
        if (OpenClipboard(hwnd)) {
            EmptyClipboard();

            char str[256];
            int len = sprintf(str, "camPos = vec3(%.15ff, %.15ff, %.15ff);\r\nwx = %.15ff;\r\nwy = %.15ff;\r\n", camPos.x, camPos.y, camPos.z, wx, wy);

            HGLOBAL handle = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, len + 1);
            char *mem = (char *) GlobalLock(handle);
            if (mem != NULL) {
                strcpy(mem, str);
                GlobalUnlock(handle);
                SetClipboardData(CF_TEXT, handle);
            }
            CloseClipboard();
        }
    }
#endif

    if (pressed && key == screenshotKey) {
        if (!saveScreenshot()) {
            ErrorMsg("Couldn't save screenshot");
        }
        return true;
    }

    if (pressed && key == benchmarkKey) {
        if (benchMarkFile) {
            fclose(benchMarkFile);
            benchMarkFile = NULL;
        } else {
            benchMarkFile = fopen("Benchmark.xls", "w");
            fprintf(benchMarkFile, "Frames/s\n");
        }
        return true;
    }


    bool processed = false;

    if (!mouseCaptured) {
        if (widgets.goToFirst()) {
            do {
                Widget *widget = widgets.getCurrent();
                if (widget->isVisible() || widget->isCapturing()) {
                    widgets.moveCurrentToTop();
                    processed = widget->onKey(key, pressed);
                    break;
                }
            } while (widgets.goToNext());
        }
    }

    if (!processed) {
        if (pressed) {
            processed = true;
            if (key == KEY_ESCAPE) {
                if (!mouseCaptured || (fullscreen && mouseCaptured)) {
                    closeWindow(true, true);
                } else {
                    captureMouse(false);
                }
            } else if (key == fpsKey) {
                showFPS = !showFPS;
            } else if (key == resetKey) {
                resetCamera();
            } else if (key == optionsKey) {
                if (configDialog->isVisible()) {
                    configDialog->setVisible(false);
                    if (keysDialog) keysDialog->setVisible(false);
                    if (joystickDialog) joystickDialog->setVisible(false);
                } else {
                    captureMouse(false);
                    configDialog->setVisible(true);
                    if (keysDialog) keysDialog->setVisible(true);
                    if (joystickDialog) joystickDialog->setVisible(true);
                }
            } else {
                processed = false;
            }
        }
    }

    if (key < elementsOf(keys)) keys[key] = pressed;

    return processed;
}
Exemplo n.º 8
0
void DisplayView::MakeScreenshot()
{
    // find out the rectangle
    int	minx = 10000000;
    int	miny = 10000000;
    int maxx = 0;
    int maxy = 0;

    for (int i=0; i<graph.filters.GetCount(); i++) {
        Filter	*filter = graph.filters[i];
        if (filter->posx < minx) minx = filter->posx;
        if (filter->posy < miny) miny = filter->posy;
        if (filter->posx + filter->width > maxx) maxx = filter->posx+filter->width;
        if (filter->posy + filter->height > maxy) maxy = filter->posy+filter->height;
    }

    minx = minx &~ 0x07;
    minx -= 8;
    if (minx < 0) minx = 0;
    miny = miny &~ 0x07;
    miny -= 8;
    if (miny < 0) miny = 0;
    maxx = (maxx+7) &~ 0x07;
    maxx += 8;
    maxy = (maxy+7) &~ 0x07;
    maxy += 8;

    // now copy the bitmap
    int	cx = (maxx-minx);
    int cy = (maxy-miny);

    if (cx == 0 || cy == 0) {
        OpenClipboard();
        EmptyClipboard();
        CloseClipboard();
        return ;
    }

    CRect		imgrect(minx, miny, maxx, maxy);
    CRect		bufrect(0, 0, back_width, back_height);
    CDC			tempdc;
    CBitmap		tempbitmap;

    CRect		area=imgrect;
    area.IntersectRect(&imgrect, &bufrect);

    tempdc.CreateCompatibleDC(&memDC);
    tempbitmap.CreateBitmap(area.Width(), area.Height(), 1, 32, NULL);
    CBitmap *old = tempdc.SelectObject(&tempbitmap);
    tempdc.BitBlt(0, 0, area.Width(), area.Height(), &memDC, area.left, area.top, SRCCOPY);

    OpenClipboard();
    EmptyClipboard();
    SetClipboardData(CF_BITMAP, tempbitmap.GetSafeHandle());
    CloseClipboard();

    tempdc.SelectObject(old);
    tempbitmap.DeleteObject();
    tempdc.DeleteDC();

}
Exemplo n.º 9
0
LRESULT CALLBACK
winClipboardWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    static HWND s_hwndNextViewer;
    static Bool s_fCBCInitialized;
    static Display *pDisplay;
    static Window iWindow;
    static ClipboardAtoms *atoms;
    static Bool fRunning;

    /* Branch on message type */
    switch (message) {
    case WM_DESTROY:
    {
        winDebug("winClipboardWindowProc - WM_DESTROY\n");

        if (g_fHasModernClipboardApi)
            {
                /* Remove clipboard listener */
                g_fpRemoveClipboardFormatListener(hwnd);
            }
        else
            {
                /* Remove ourselves from the clipboard chain */
                ChangeClipboardChain(hwnd, s_hwndNextViewer);
            }

        s_hwndNextViewer = NULL;
    }
        return 0;

    case WM_WM_QUIT:
    {
        winDebug("winClipboardWindowProc - WM_WM_QUIT\n");
        fRunning = FALSE;
        PostQuitMessage(0);
    }
        return 0;

    case WM_CREATE:
    {
        ClipboardWindowCreationParams *cwcp = (ClipboardWindowCreationParams *)((CREATESTRUCT *)lParam)->lpCreateParams;

        winDebug("winClipboardWindowProc - WM_CREATE\n");

        pDisplay = cwcp->pClipboardDisplay;
        iWindow = cwcp->iClipboardWindow;
        atoms = cwcp->atoms;
        fRunning = TRUE;

        if (g_fHasModernClipboardApi)
            {
                g_fpAddClipboardFormatListener(hwnd);
            }
        else
            {
                HWND first, next;
                DWORD error_code = 0;

                first = GetClipboardViewer();   /* Get handle to first viewer in chain. */
                if (first == hwnd)
                    return 0;           /* Make sure it's not us! */
                /* Add ourselves to the clipboard viewer chain */
                next = SetClipboardViewer(hwnd);
                error_code = GetLastError();
                if (SUCCEEDED(error_code) && (next == first))   /* SetClipboardViewer must have succeeded, and the handle */
                    s_hwndNextViewer = next;    /* it returned must have been the first window in the chain */
                else
                    s_fCBCInitialized = FALSE;
            }
    }
        return 0;

    case WM_CHANGECBCHAIN:
    {
        winDebug("winClipboardWindowProc - WM_CHANGECBCHAIN: wParam(%p) "
                 "lParam(%p) s_hwndNextViewer(%p)\n",
                 (HWND)wParam, (HWND)lParam, s_hwndNextViewer);

        if ((HWND) wParam == s_hwndNextViewer) {
            s_hwndNextViewer = (HWND) lParam;
            if (s_hwndNextViewer == hwnd) {
                s_hwndNextViewer = NULL;
                ErrorF("winClipboardWindowProc - WM_CHANGECBCHAIN: "
                       "attempted to set next window to ourselves.");
            }
        }
        else if (s_hwndNextViewer)
            SendMessage(s_hwndNextViewer, message, wParam, lParam);

    }
        winDebug("winClipboardWindowProc - WM_CHANGECBCHAIN: Exit\n");
        return 0;

    case WM_WM_REINIT:
    {
        /* Ensure that we're in the clipboard chain.  Some apps,
         * WinXP's remote desktop for one, don't play nice with the
         * chain.  This message is called whenever we receive a
         * WM_ACTIVATEAPP message to ensure that we continue to
         * receive clipboard messages.
         *
         * It might be possible to detect if we're still in the chain
         * by calling SendMessage (GetClipboardViewer(),
         * WM_DRAWCLIPBOARD, 0, 0); and then seeing if we get the
         * WM_DRAWCLIPBOARD message.  That, however, might be more
         * expensive than just putting ourselves back into the chain.
         */

        HWND first, next;
        DWORD error_code = 0;

        winDebug("winClipboardWindowProc - WM_WM_REINIT: Enter\n");

        if (g_fHasModernClipboardApi)
            {
                return 0;
            }

        first = GetClipboardViewer();   /* Get handle to first viewer in chain. */
        if (first == hwnd)
            return 0;           /* Make sure it's not us! */
        winDebug("  WM_WM_REINIT: Replacing us(%p) with %p at head "
                 "of chain\n", hwnd, s_hwndNextViewer);
        s_fCBCInitialized = FALSE;
        ChangeClipboardChain(hwnd, s_hwndNextViewer);
        s_hwndNextViewer = NULL;
        s_fCBCInitialized = FALSE;
        winDebug("  WM_WM_REINIT: Putting us back at head of chain.\n");
        first = GetClipboardViewer();   /* Get handle to first viewer in chain. */
        if (first == hwnd)
            return 0;           /* Make sure it's not us! */
        next = SetClipboardViewer(hwnd);
        error_code = GetLastError();
        if (SUCCEEDED(error_code) && (next == first))   /* SetClipboardViewer must have succeeded, and the handle */
            s_hwndNextViewer = next;    /* it returned must have been the first window in the chain */
        else
            s_fCBCInitialized = FALSE;
    }
        winDebug("winClipboardWindowProc - WM_WM_REINIT: Exit\n");
        return 0;

    case WM_DRAWCLIPBOARD:
    case WM_CLIPBOARDUPDATE:
    {
        static Bool s_fProcessingDrawClipboard = FALSE;
        int iReturn;

        if (message == WM_DRAWCLIPBOARD)
            winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD: Enter\n");
        else
            winDebug("winClipboardWindowProc -  WM_CLIPBOARDUPDATE: Enter\n");

        if (!g_fHasModernClipboardApi)
            {
                /*
                 * We've occasionally seen a loop in the clipboard chain.
                 * Try and fix it on the first hint of recursion.
                 */
                if (!s_fProcessingDrawClipboard) {
                    s_fProcessingDrawClipboard = TRUE;
                }
                else {
                    /* Attempt to break the nesting by getting out of the chain, twice?, and then fix and bail */
                    s_fCBCInitialized = FALSE;
                    ChangeClipboardChain(hwnd, s_hwndNextViewer);
                    winFixClipboardChain();
                    ErrorF("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                           "Nested calls detected.  Re-initing.\n");
                    winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
                    s_fProcessingDrawClipboard = FALSE;
                    return 0;
                }

                /* Bail on first message */
                if (!s_fCBCInitialized) {
                    s_fCBCInitialized = TRUE;
                    s_fProcessingDrawClipboard = FALSE;
                    winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
                    return 0;
                }
            }

        /*
         * NOTE: We cannot bail out when NULL == GetClipboardOwner ()
         * because some applications deal with the clipboard in a manner
         * that causes the clipboard owner to be NULL when they are in
         * fact taking ownership.  One example of this is the Win32
         * native compile of emacs.
         */

        /* Bail when we still own the clipboard */
        if (hwnd == GetClipboardOwner()) {

            winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                     "We own the clipboard, returning.\n");
            winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
            s_fProcessingDrawClipboard = FALSE;
            if (s_hwndNextViewer)
                SendMessage(s_hwndNextViewer, message, wParam, lParam);
            return 0;
        }

        /* Bail when shutting down */
        if (!fRunning)
            return 0;

        /*
         * Do not take ownership of the X11 selections when something
         * other than CF_TEXT or CF_UNICODETEXT has been copied
         * into the Win32 clipboard.
         */
        if (!IsClipboardFormatAvailable(CF_TEXT)
            && !IsClipboardFormatAvailable(CF_UNICODETEXT)) {

            winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                     "Clipboard does not contain CF_TEXT nor "
                     "CF_UNICODETEXT.\n");

            /*
             * We need to make sure that the X Server has processed
             * previous XSetSelectionOwner messages.
             */
            XSync(pDisplay, FALSE);

            winDebug("winClipboardWindowProc - XSync done.\n");

            /* Release PRIMARY selection if owned */
            iReturn = XGetSelectionOwner(pDisplay, XA_PRIMARY);
            if (iReturn == iWindow) {
                winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                         "PRIMARY selection is owned by us.\n");
                XSetSelectionOwner(pDisplay, XA_PRIMARY, None, CurrentTime);
            }
            else if (BadWindow == iReturn || BadAtom == iReturn)
                ErrorF("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                       "XGetSelectionOwner failed for PRIMARY: %d\n",
                       iReturn);

            /* Release CLIPBOARD selection if owned */
            iReturn = XGetSelectionOwner(pDisplay, atoms->atomClipboard);
            if (iReturn == iWindow) {
                winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                         "CLIPBOARD selection is owned by us, releasing\n");
                XSetSelectionOwner(pDisplay, atoms->atomClipboard, None, CurrentTime);
            }
            else if (BadWindow == iReturn || BadAtom == iReturn)
                ErrorF("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                       "XGetSelectionOwner failed for CLIPBOARD: %d\n",
                       iReturn);

            winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
            s_fProcessingDrawClipboard = FALSE;
            if (s_hwndNextViewer)
                SendMessage(s_hwndNextViewer, message, wParam, lParam);
            return 0;
        }

        /* Reassert ownership of PRIMARY */
        iReturn = XSetSelectionOwner(pDisplay,
                                     XA_PRIMARY, iWindow, CurrentTime);
        if (iReturn == BadAtom || iReturn == BadWindow ||
            XGetSelectionOwner(pDisplay, XA_PRIMARY) != iWindow) {
            ErrorF("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                   "Could not reassert ownership of PRIMARY\n");
        }
        else {
            winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                     "Reasserted ownership of PRIMARY\n");
        }

        /* Reassert ownership of the CLIPBOARD */
        iReturn = XSetSelectionOwner(pDisplay,
                                     atoms->atomClipboard, iWindow, CurrentTime);

        if (iReturn == BadAtom || iReturn == BadWindow ||
            XGetSelectionOwner(pDisplay, atoms->atomClipboard) != iWindow) {
            ErrorF("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                    "Could not reassert ownership of CLIPBOARD\n");
        }
        else {
            winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
                     "Reasserted ownership of CLIPBOARD\n");
        }

        /* Flush the pending SetSelectionOwner event now */
        XFlush(pDisplay);

        s_fProcessingDrawClipboard = FALSE;
    }
        winDebug("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
        /* Pass the message on the next window in the clipboard viewer chain */
        if (s_hwndNextViewer)
            SendMessage(s_hwndNextViewer, message, wParam, lParam);
        return 0;

    case WM_DESTROYCLIPBOARD:
        /*
         * NOTE: Intentionally do nothing.
         * Changes in the Win32 clipboard are handled by WM_DRAWCLIPBOARD
         * above.  We only process this message to conform to the specs
         * for delayed clipboard rendering in Win32.  You might think
         * that we need to release ownership of the X11 selections, but
         * we do not, because a WM_DRAWCLIPBOARD message will closely
         * follow this message and reassert ownership of the X11
         * selections, handling the issue for us.
         */
        winDebug("winClipboardWindowProc - WM_DESTROYCLIPBOARD - Ignored.\n");
        return 0;

    case WM_RENDERALLFORMATS:
        winDebug("winClipboardWindowProc - WM_RENDERALLFORMATS - Hello.\n");

        /*
          WM_RENDERALLFORMATS is sent as we are shutting down, to render the
          clipboard so it's contents remains available to other applications.

          Unfortunately, this can't work without major changes. The server is
          already waiting for us to stop, so we can't ask for the rendering of
          clipboard text now.
        */

        return 0;

    case WM_RENDERFORMAT:
    {
        int iReturn;
        Bool fConvertToUnicode;
        Bool pasted = FALSE;
        Atom selection;
        ClipboardConversionData data;
        int best_target = 0;

        winDebug("winClipboardWindowProc - WM_RENDERFORMAT %d - Hello.\n",
                 (int)wParam);

        /* Flag whether to convert to Unicode or not */
        fConvertToUnicode = (CF_UNICODETEXT == wParam);

        selection = winClipboardGetLastOwnedSelectionAtom(atoms);
        if (selection == None) {
            ErrorF("winClipboardWindowProc - no monitored selection is owned\n");
            goto fake_paste;
        }

        winDebug("winClipboardWindowProc - requesting targets for selection from owner\n");

        /* Request the selection's supported conversion targets */
        XConvertSelection(pDisplay,
                          selection,
                          atoms->atomTargets,
                          atoms->atomLocalProperty,
                          iWindow, CurrentTime);

        /* Process X events */
        data.fUseUnicode = fConvertToUnicode;
        iReturn = winProcessXEventsTimeout(hwnd,
                                           iWindow,
                                           pDisplay,
                                           &data,
                                           atoms,
                                           WIN_POLL_TIMEOUT);

        if (WIN_XEVENTS_NOTIFY_TARGETS != iReturn) {
            ErrorF
                ("winClipboardWindowProc - timed out waiting for WIN_XEVENTS_NOTIFY_TARGETS\n");
            goto fake_paste;
        }

        /* Choose the most preferred target */
        {
            struct target_priority
            {
                Atom target;
                unsigned int priority;
            };

            struct target_priority target_priority_table[] =
                {
                    { atoms->atomCompoundText, 0 },
#ifdef X_HAVE_UTF8_STRING
                    { atoms->atomUTF8String,   1 },
#endif
                    { XA_STRING,               2 },
                };

            int best_priority = INT_MAX;

            int i,j;
            for (i = 0 ; data.targetList[i] != 0; i++)
                {
                    for (j = 0; j < sizeof(target_priority_table)/sizeof(struct target_priority); j ++)
                        {
                            if ((data.targetList[i] == target_priority_table[j].target) &&
                                (target_priority_table[j].priority < best_priority))
                                {
                                    best_target = target_priority_table[j].target;
                                    best_priority = target_priority_table[j].priority;
                                }
                        }
                }
        }

        free(data.targetList);
        data.targetList = 0;

        winDebug("winClipboardWindowProc - best target is %d\n", best_target);

        /* No useful targets found */
        if (best_target == 0)
          goto fake_paste;

        winDebug("winClipboardWindowProc - requesting selection from owner\n");

        /* Request the selection contents */
        XConvertSelection(pDisplay,
                          selection,
                          best_target,
                          atoms->atomLocalProperty,
                          iWindow, CurrentTime);

        /* Process X events */
        iReturn = winProcessXEventsTimeout(hwnd,
                                           iWindow,
                                           pDisplay,
                                           &data,
                                           atoms,
                                           WIN_POLL_TIMEOUT);

        /*
         * winProcessXEventsTimeout had better have seen a notify event,
         * or else we are dealing with a buggy or old X11 app.
         */
        if (WIN_XEVENTS_NOTIFY_DATA != iReturn) {
            ErrorF
                ("winClipboardWindowProc - timed out waiting for WIN_XEVENTS_NOTIFY_DATA\n");
        }
        else {
            pasted = TRUE;
        }

         /*
          * If we couldn't get the data from the X clipboard, we
          * have to paste some fake data to the Win32 clipboard to
          * satisfy the requirement that we write something to it.
          */
    fake_paste:
        if (!pasted)
          {
            /* Paste no data, to satisfy required call to SetClipboardData */
            SetClipboardData(CF_UNICODETEXT, NULL);
            SetClipboardData(CF_TEXT, NULL);
          }

        winDebug("winClipboardWindowProc - WM_RENDERFORMAT - Returning.\n");
        return 0;
    }
    }

    /* Let Windows perform default processing for unhandled messages */
    return DefWindowProc(hwnd, message, wParam, lParam);
}
Exemplo n.º 10
0
bool AlClipboard::writeToClipboard(char *pKey)
{
	logger->debug("AlClipboard::writeToClipboard:-- START\n");

	char tbuf[128];
	ZeroMemory(tbuf, sizeof(char) * 128);

	char tbuf2[128];
	ZeroMemory(tbuf2, sizeof(char) * 128);
	sprintf(tbuf, "%s/%s\0", DEFAULT_DIRECTORY_NAME, pKey);
	sprintf(tbuf2, "\t reading... '%s'\n\0", tbuf);
	logger->debug(tbuf2);
	FILE *fle = fopen(tbuf, "rt");
	if (!fle)
	{
		sprintf(tbuf2, "\t Opening file '%s' failed.\n\0", tbuf);
		logger->debug(tbuf2);
		return false;
	}
	fseek(fle, 0, SEEK_END);
	int maxSize = ftell(fle);
	fclose(fle);

	sprintf(tbuf2, "\t File size: '%i'.\n\0", maxSize);
	logger->debug(tbuf2);
	if (maxSize < 1)
	{
		sprintf(tbuf2, "\t file too small.\n\0", tbuf);
		logger->debug(tbuf2);
		return false;
	}

	char *pBuffer = NULL;
	pBuffer = new char[maxSize+1];
	ZeroMemory(pBuffer, sizeof(char) * (maxSize+1));
	if (!readFromDisk(pKey, pBuffer, maxSize))
	{
		return false;
	}

	if (!OpenClipboard(NULL))
	{
		logger->debug("\t OpenClipboard.. FAILED..\n");
		return false;
	}

	EmptyClipboard();
	HGLOBAL hClipboardData;
	hClipboardData = GlobalAlloc(GMEM_DDESHARE, maxSize+1);
	char * pchData;
	pchData = (char*)GlobalLock(hClipboardData);
	strcpy(pchData, pBuffer);
	GlobalUnlock(hClipboardData);
	SetClipboardData(CF_TEXT, hClipboardData);


	logger->debug("\t CloseClipboard()");
	CloseClipboard();
	SAFE_DEL(pBuffer);
	return true;
}
Exemplo n.º 11
0
int
winClipboardFlushXEvents(HWND hwnd,
                         int iWindow, Display * pDisplay, Bool fUseUnicode)
{
    static Atom atomLocalProperty;
    static Atom atomCompoundText;
    static Atom atomUTF8String;
    static Atom atomTargets;
    static int generation;

    if (generation != serverGeneration) {
        generation = serverGeneration;
        atomLocalProperty = XInternAtom(pDisplay, WIN_LOCAL_PROPERTY, False);
        atomUTF8String = XInternAtom(pDisplay, "UTF8_STRING", False);
        atomCompoundText = XInternAtom(pDisplay, "COMPOUND_TEXT", False);
        atomTargets = XInternAtom(pDisplay, "TARGETS", False);
    }

    /* Process all pending events */
    while (XPending(pDisplay)) {
        XTextProperty xtpText = { 0 };
        XEvent event;
        XSelectionEvent eventSelection;
        unsigned long ulReturnBytesLeft;
        char *pszReturnData = NULL;
        char *pszGlobalData = NULL;
        int iReturn;
        HGLOBAL hGlobal = NULL;
        XICCEncodingStyle xiccesStyle;
        int iConvertDataLen = 0;
        char *pszConvertData = NULL;
        char *pszTextList[2] = { NULL };
        int iCount;
        char **ppszTextList = NULL;
        wchar_t *pwszUnicodeStr = NULL;
        int iUnicodeLen = 0;
        int iReturnDataLen = 0;
        int i;
        Bool fAbort = FALSE;
        Bool fCloseClipboard = FALSE;
        Bool fSetClipboardData = TRUE;

        /* Get the next event - will not block because one is ready */
        XNextEvent(pDisplay, &event);

        /* Branch on the event type */
        switch (event.type) {
            /*
             * SelectionRequest
             */

        case SelectionRequest:
        {
            char *pszAtomName = NULL;

            winDebug("SelectionRequest - target %d\n",
                     event.xselectionrequest.target);

            pszAtomName = XGetAtomName(pDisplay,
                                       event.xselectionrequest.target);
            winDebug("SelectionRequest - Target atom name %s\n", pszAtomName);
            XFree(pszAtomName);
            pszAtomName = NULL;
        }

            /* Abort if invalid target type */
            if (event.xselectionrequest.target != XA_STRING
                && event.xselectionrequest.target != atomUTF8String
                && event.xselectionrequest.target != atomCompoundText
                && event.xselectionrequest.target != atomTargets) {
                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionRequest_Done;
            }

            /* Handle targets type of request */
            if (event.xselectionrequest.target == atomTargets) {
                Atom atomTargetArr[] = { atomTargets,
                    atomCompoundText,
                    atomUTF8String,
                    XA_STRING
                };

                /* Try to change the property */
                iReturn = XChangeProperty(pDisplay,
                                          event.xselectionrequest.requestor,
                                          event.xselectionrequest.property,
                                          XA_ATOM,
                                          32,
                                          PropModeReplace,
                                          (unsigned char *) atomTargetArr,
                                          (sizeof(atomTargetArr)
                                           / sizeof(atomTargetArr[0])));
                if (iReturn == BadAlloc
                    || iReturn == BadAtom
                    || iReturn == BadMatch
                    || iReturn == BadValue || iReturn == BadWindow) {
                    ErrorF("winClipboardFlushXEvents - SelectionRequest - "
                           "XChangeProperty failed: %d\n", iReturn);
                }

                /* Setup selection notify xevent */
                eventSelection.type = SelectionNotify;
                eventSelection.send_event = True;
                eventSelection.display = pDisplay;
                eventSelection.requestor = event.xselectionrequest.requestor;
                eventSelection.selection = event.xselectionrequest.selection;
                eventSelection.target = event.xselectionrequest.target;
                eventSelection.property = event.xselectionrequest.property;
                eventSelection.time = event.xselectionrequest.time;

                /*
                 * Notify the requesting window that
                 * the operation has completed
                 */
                iReturn = XSendEvent(pDisplay,
                                     eventSelection.requestor,
                                     False, 0L, (XEvent *) &eventSelection);
                if (iReturn == BadValue || iReturn == BadWindow) {
                    ErrorF("winClipboardFlushXEvents - SelectionRequest - "
                           "XSendEvent () failed\n");
                }
                break;
            }

            /* Close clipboard if we have it open already */
            if (GetOpenClipboardWindow() == hwnd) {
                CloseClipboard();
            }

            /* Access the clipboard */
            if (!OpenClipboard(hwnd)) {
                ErrorF("winClipboardFlushXEvents - SelectionRequest - "
                       "OpenClipboard () failed: %08lx\n", GetLastError());

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionRequest_Done;
            }

            /* Indicate that clipboard was opened */
            fCloseClipboard = TRUE;

            /* Check that clipboard format is available */
            if (fUseUnicode && !IsClipboardFormatAvailable(CF_UNICODETEXT)) {
                static int count;       /* Hack to stop acroread spamming the log */
                static HWND lasthwnd;   /* I've not seen any other client get here repeatedly? */

                if (hwnd != lasthwnd)
                    count = 0;
                count++;
                if (count < 6)
                    ErrorF("winClipboardFlushXEvents - CF_UNICODETEXT is not "
                           "available from Win32 clipboard.  Aborting %d.\n",
                           count);
                lasthwnd = hwnd;

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionRequest_Done;
            }
            else if (!fUseUnicode && !IsClipboardFormatAvailable(CF_TEXT)) {
                ErrorF("winClipboardFlushXEvents - CF_TEXT is not "
                       "available from Win32 clipboard.  Aborting.\n");

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionRequest_Done;
            }

            /* Setup the string style */
            if (event.xselectionrequest.target == XA_STRING)
                xiccesStyle = XStringStyle;
#ifdef X_HAVE_UTF8_STRING
            else if (event.xselectionrequest.target == atomUTF8String)
                xiccesStyle = XUTF8StringStyle;
#endif
            else if (event.xselectionrequest.target == atomCompoundText)
                xiccesStyle = XCompoundTextStyle;
            else
                xiccesStyle = XStringStyle;

            /* Get a pointer to the clipboard text, in desired format */
            if (fUseUnicode) {
                /* Retrieve clipboard data */
                hGlobal = GetClipboardData(CF_UNICODETEXT);
            }
            else {
                /* Retrieve clipboard data */
                hGlobal = GetClipboardData(CF_TEXT);
            }
            if (!hGlobal) {
                ErrorF("winClipboardFlushXEvents - SelectionRequest - "
                       "GetClipboardData () failed: %08lx\n", GetLastError());

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionRequest_Done;
            }
            pszGlobalData = (char *) GlobalLock(hGlobal);

            /* Convert the Unicode string to UTF8 (MBCS) */
            if (fUseUnicode) {
                iConvertDataLen = WideCharToMultiByte(CP_UTF8,
                                                      0,
                                                      (LPCWSTR) pszGlobalData,
                                                      -1, NULL, 0, NULL, NULL);
                /* NOTE: iConvertDataLen includes space for null terminator */
                pszConvertData = (char *) malloc(iConvertDataLen);
                WideCharToMultiByte(CP_UTF8,
                                    0,
                                    (LPCWSTR) pszGlobalData,
                                    -1,
                                    pszConvertData,
                                    iConvertDataLen, NULL, NULL);
            }
            else {
                pszConvertData = strdup(pszGlobalData);
                iConvertDataLen = strlen(pszConvertData) + 1;
            }

            /* Convert DOS string to UNIX string */
            winClipboardDOStoUNIX(pszConvertData, strlen(pszConvertData));

            /* Setup our text list */
            pszTextList[0] = pszConvertData;
            pszTextList[1] = NULL;

            /* Initialize the text property */
            xtpText.value = NULL;
            xtpText.nitems = 0;

            /* Create the text property from the text list */
            if (fUseUnicode) {
#ifdef X_HAVE_UTF8_STRING
                iReturn = Xutf8TextListToTextProperty(pDisplay,
                                                      pszTextList,
                                                      1, xiccesStyle, &xtpText);
#endif
            }
            else {
                iReturn = XmbTextListToTextProperty(pDisplay,
                                                    pszTextList,
                                                    1, xiccesStyle, &xtpText);
            }
            if (iReturn == XNoMemory || iReturn == XLocaleNotSupported) {
                ErrorF("winClipboardFlushXEvents - SelectionRequest - "
                       "X*TextListToTextProperty failed: %d\n", iReturn);

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionRequest_Done;
            }

            /* Free the converted string */
            free(pszConvertData);
            pszConvertData = NULL;

            /* Copy the clipboard text to the requesting window */
            iReturn = XChangeProperty(pDisplay,
                                      event.xselectionrequest.requestor,
                                      event.xselectionrequest.property,
                                      event.xselectionrequest.target,
                                      8,
                                      PropModeReplace,
                                      xtpText.value, xtpText.nitems);
            if (iReturn == BadAlloc || iReturn == BadAtom
                || iReturn == BadMatch || iReturn == BadValue
                || iReturn == BadWindow) {
                ErrorF("winClipboardFlushXEvents - SelectionRequest - "
                       "XChangeProperty failed: %d\n", iReturn);

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionRequest_Done;
            }

            /* Release the clipboard data */
            GlobalUnlock(hGlobal);
            pszGlobalData = NULL;
            fCloseClipboard = FALSE;
            CloseClipboard();

            /* Clean up */
            XFree(xtpText.value);
            xtpText.value = NULL;
            xtpText.nitems = 0;

            /* Setup selection notify event */
            eventSelection.type = SelectionNotify;
            eventSelection.send_event = True;
            eventSelection.display = pDisplay;
            eventSelection.requestor = event.xselectionrequest.requestor;
            eventSelection.selection = event.xselectionrequest.selection;
            eventSelection.target = event.xselectionrequest.target;
            eventSelection.property = event.xselectionrequest.property;
            eventSelection.time = event.xselectionrequest.time;

            /* Notify the requesting window that the operation has completed */
            iReturn = XSendEvent(pDisplay,
                                 eventSelection.requestor,
                                 False, 0L, (XEvent *) &eventSelection);
            if (iReturn == BadValue || iReturn == BadWindow) {
                ErrorF("winClipboardFlushXEvents - SelectionRequest - "
                       "XSendEvent () failed\n");

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionRequest_Done;
            }

 winClipboardFlushXEvents_SelectionRequest_Done:
            /* Free allocated resources */
            if (xtpText.value) {
                XFree(xtpText.value);
                xtpText.value = NULL;
                xtpText.nitems = 0;
            }
            free(pszConvertData);
            if (hGlobal && pszGlobalData)
                GlobalUnlock(hGlobal);

            /*
             * Send a SelectionNotify event to the requesting
             * client when we abort.
             */
            if (fAbort) {
                /* Setup selection notify event */
                eventSelection.type = SelectionNotify;
                eventSelection.send_event = True;
                eventSelection.display = pDisplay;
                eventSelection.requestor = event.xselectionrequest.requestor;
                eventSelection.selection = event.xselectionrequest.selection;
                eventSelection.target = event.xselectionrequest.target;
                eventSelection.property = None;
                eventSelection.time = event.xselectionrequest.time;

                /* Notify the requesting window that the operation is complete */
                iReturn = XSendEvent(pDisplay,
                                     eventSelection.requestor,
                                     False, 0L, (XEvent *) &eventSelection);
                if (iReturn == BadValue || iReturn == BadWindow) {
                    /*
                     * Should not be a problem if XSendEvent fails because
                     * the client may simply have exited.
                     */
                    ErrorF("winClipboardFlushXEvents - SelectionRequest - "
                           "XSendEvent () failed for abort event.\n");
                }
            }

            /* Close clipboard if it was opened */
            if (fCloseClipboard) {
                fCloseClipboard = FALSE;
                CloseClipboard();
            }
            break;

            /*
             * SelectionNotify
             */

        case SelectionNotify:

            winDebug("winClipboardFlushXEvents - SelectionNotify\n");
            {
                char *pszAtomName;

                pszAtomName = XGetAtomName(pDisplay,
                                           event.xselection.selection);

                winDebug
                    ("winClipboardFlushXEvents - SelectionNotify - ATOM: %s\n",
                     pszAtomName);
                XFree(pszAtomName);
            }

            /*
             * Request conversion of UTF8 and CompoundText targets.
             */
            if (event.xselection.property == None) {
                if (event.xselection.target == XA_STRING) {
                    winDebug("winClipboardFlushXEvents - SelectionNotify - "
                             "XA_STRING\n");

                    return WIN_XEVENTS_CONVERT;
                }
                else if (event.xselection.target == atomUTF8String) {
                    winDebug("winClipboardFlushXEvents - SelectionNotify - "
                             "Requesting conversion of UTF8 target.\n");

                    XConvertSelection(pDisplay,
                                      event.xselection.selection,
                                      XA_STRING,
                                      atomLocalProperty, iWindow, CurrentTime);

                    /* Process the ConvertSelection event */
                    XFlush(pDisplay);
                    return WIN_XEVENTS_CONVERT;
                }
#ifdef X_HAVE_UTF8_STRING
                else if (event.xselection.target == atomCompoundText) {
                    winDebug("winClipboardFlushXEvents - SelectionNotify - "
                             "Requesting conversion of CompoundText target.\n");

                    XConvertSelection(pDisplay,
                                      event.xselection.selection,
                                      atomUTF8String,
                                      atomLocalProperty, iWindow, CurrentTime);

                    /* Process the ConvertSelection event */
                    XFlush(pDisplay);
                    return WIN_XEVENTS_CONVERT;
                }
#endif
                else {
                    ErrorF("winClipboardFlushXEvents - SelectionNotify - "
                           "Unknown format.  Cannot request conversion, "
                           "aborting.\n");
                    break;
                }
            }

            /* Retrieve the size of the stored data */
            iReturn = XGetWindowProperty(pDisplay, iWindow, atomLocalProperty, 0, 0,    /* Don't get data, just size */
                                         False,
                                         AnyPropertyType,
                                         &xtpText.encoding,
                                         &xtpText.format,
                                         &xtpText.nitems,
                                         &ulReturnBytesLeft, &xtpText.value);
            if (iReturn != Success) {
                ErrorF("winClipboardFlushXEvents - SelectionNotify - "
                       "XGetWindowProperty () failed, aborting: %d\n", iReturn);
                break;
            }

            winDebug("SelectionNotify - returned data %d left %d\n",
                     xtpText.nitems, ulReturnBytesLeft);

            /* Request the selection data */
            iReturn = XGetWindowProperty(pDisplay,
                                         iWindow,
                                         atomLocalProperty,
                                         0,
                                         ulReturnBytesLeft,
                                         False,
                                         AnyPropertyType,
                                         &xtpText.encoding,
                                         &xtpText.format,
                                         &xtpText.nitems,
                                         &ulReturnBytesLeft, &xtpText.value);
            if (iReturn != Success) {
                ErrorF("winClipboardFlushXEvents - SelectionNotify - "
                       "XGetWindowProperty () failed, aborting: %d\n", iReturn);
                break;
            }

            {
                char *pszAtomName = NULL;

                winDebug("SelectionNotify - returned data %d left %d\n",
                         xtpText.nitems, ulReturnBytesLeft);
                pszAtomName = XGetAtomName(pDisplay, xtpText.encoding);
                winDebug("Notify atom name %s\n", pszAtomName);
                XFree(pszAtomName);
                pszAtomName = NULL;
            }

            if (fUseUnicode) {
#ifdef X_HAVE_UTF8_STRING
                /* Convert the text property to a text list */
                iReturn = Xutf8TextPropertyToTextList(pDisplay,
                                                      &xtpText,
                                                      &ppszTextList, &iCount);
#endif
            }
            else {
                iReturn = XmbTextPropertyToTextList(pDisplay,
                                                    &xtpText,
                                                    &ppszTextList, &iCount);
            }
            if (iReturn == Success || iReturn > 0) {
                /* Conversion succeeded or some unconvertible characters */
                if (ppszTextList != NULL) {
                    iReturnDataLen = 0;
                    for (i = 0; i < iCount; i++) {
                        iReturnDataLen += strlen(ppszTextList[i]);
                    }
                    pszReturnData = malloc(iReturnDataLen + 1);
                    pszReturnData[0] = '\0';
                    for (i = 0; i < iCount; i++) {
                        strcat(pszReturnData, ppszTextList[i]);
                    }
                }
                else {
                    ErrorF("winClipboardFlushXEvents - SelectionNotify - "
                           "X*TextPropertyToTextList list_return is NULL.\n");
                    pszReturnData = malloc(1);
                    pszReturnData[0] = '\0';
                }
            }
            else {
                ErrorF("winClipboardFlushXEvents - SelectionNotify - "
                       "X*TextPropertyToTextList returned: ");
                switch (iReturn) {
                case XNoMemory:
                    ErrorF("XNoMemory\n");
                    break;
                case XLocaleNotSupported:
                    ErrorF("XLocaleNotSupported\n");
                    break;
                case XConverterNotFound:
                    ErrorF("XConverterNotFound\n");
                    break;
                default:
                    ErrorF("%d\n", iReturn);
                    break;
                }
                pszReturnData = malloc(1);
                pszReturnData[0] = '\0';
            }

            /* Free the data returned from XGetWindowProperty */
            if (ppszTextList)
                XFreeStringList(ppszTextList);
            ppszTextList = NULL;
            XFree(xtpText.value);
            xtpText.value = NULL;
            xtpText.nitems = 0;

            /* Convert the X clipboard string to DOS format */
            winClipboardUNIXtoDOS(&pszReturnData, strlen(pszReturnData));

            if (fUseUnicode) {
                /* Find out how much space needed to convert MBCS to Unicode */
                iUnicodeLen = MultiByteToWideChar(CP_UTF8,
                                                  0,
                                                  pszReturnData, -1, NULL, 0);

                /* Allocate memory for the Unicode string */
                pwszUnicodeStr
                    = (wchar_t *) malloc(sizeof(wchar_t) * (iUnicodeLen + 1));
                if (!pwszUnicodeStr) {
                    ErrorF("winClipboardFlushXEvents - SelectionNotify "
                           "malloc failed for pwszUnicodeStr, aborting.\n");

                    /* Abort */
                    fAbort = TRUE;
                    goto winClipboardFlushXEvents_SelectionNotify_Done;
                }

                /* Do the actual conversion */
                MultiByteToWideChar(CP_UTF8,
                                    0,
                                    pszReturnData,
                                    -1, pwszUnicodeStr, iUnicodeLen);

                /* Allocate global memory for the X clipboard data */
                hGlobal = GlobalAlloc(GMEM_MOVEABLE,
                                      sizeof(wchar_t) * (iUnicodeLen + 1));
            }
            else {
                pszConvertData = strdup(pszReturnData);
                iConvertDataLen = strlen(pszConvertData) + 1;

                /* Allocate global memory for the X clipboard data */
                hGlobal = GlobalAlloc(GMEM_MOVEABLE, iConvertDataLen);
            }

            free(pszReturnData);

            /* Check that global memory was allocated */
            if (!hGlobal) {
                ErrorF("winClipboardFlushXEvents - SelectionNotify "
                       "GlobalAlloc failed, aborting: %ld\n", GetLastError());

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionNotify_Done;
            }

            /* Obtain a pointer to the global memory */
            pszGlobalData = GlobalLock(hGlobal);
            if (pszGlobalData == NULL) {
                ErrorF("winClipboardFlushXEvents - Could not lock global "
                       "memory for clipboard transfer\n");

                /* Abort */
                fAbort = TRUE;
                goto winClipboardFlushXEvents_SelectionNotify_Done;
            }

            /* Copy the returned string into the global memory */
            if (fUseUnicode) {
                memcpy(pszGlobalData,
                       pwszUnicodeStr, sizeof(wchar_t) * (iUnicodeLen + 1));
                free(pwszUnicodeStr);
                pwszUnicodeStr = NULL;
            }
            else {
                strcpy(pszGlobalData, pszConvertData);
                free(pszConvertData);
                pszConvertData = NULL;
            }

            /* Release the pointer to the global memory */
            GlobalUnlock(hGlobal);
            pszGlobalData = NULL;

            /* Push the selection data to the Windows clipboard */
            if (fUseUnicode)
                SetClipboardData(CF_UNICODETEXT, hGlobal);
            else
                SetClipboardData(CF_TEXT, hGlobal);

            /* Flag that SetClipboardData has been called */
            fSetClipboardData = FALSE;

            /*
             * NOTE: Do not try to free pszGlobalData, it is owned by
             * Windows after the call to SetClipboardData ().
             */

 winClipboardFlushXEvents_SelectionNotify_Done:
            /* Free allocated resources */
            if (ppszTextList)
                XFreeStringList(ppszTextList);
            if (xtpText.value) {
                XFree(xtpText.value);
                xtpText.value = NULL;
                xtpText.nitems = 0;
            }
            free(pszConvertData);
            free(pwszUnicodeStr);
            if (hGlobal && pszGlobalData)
                GlobalUnlock(hGlobal);
            if (fSetClipboardData) {
                SetClipboardData(CF_UNICODETEXT, NULL);
                SetClipboardData(CF_TEXT, NULL);
            }
            return WIN_XEVENTS_NOTIFY;

        case SelectionClear:
            winDebug("SelectionClear - doing nothing\n");
            break;

        case PropertyNotify:
            break;

        case MappingNotify:
            break;

        default:
            ErrorF("winClipboardFlushXEvents - unexpected event type %d\n",
                   event.type);
            break;
        }
    }

    return WIN_XEVENTS_SUCCESS;
}
Exemplo n.º 12
0
BOOL CGameManageDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	//授权检测
	long timeStamp=coreGetTimeStamp();

	long licExpires=coreGetLicenseExpires();

	if(timeStamp>licExpires)
	{
		CString s,code=coreGetCode();
		s.Format("您的服务器未注册或已过期,请与服务商联系。\n\n请将以下机器码发送给服务商,获取注册码文件:\n\n%s\n\n",code);
		MessageBox(s,"提示",MB_ICONERROR);
		s="机器码已复制到您的剪贴板中,直接Ctrl+V粘贴机器码!";
		MessageBox(s,"提示",MB_ICONINFORMATION);
		OpenClipboard();
		EmptyClipboard();
		HANDLE hData=GlobalAlloc(GMEM_MOVEABLE,code.GetLength()+5); 
		if (hData==NULL)  
		{ 
			CloseClipboard(); 
			return TRUE; 
		}
		LPTSTR szMemName=(LPTSTR)GlobalLock(hData); 
		lstrcpy(szMemName,code); 
		SetClipboardData(CF_TEXT,hData); 
		GlobalUnlock(hData);  
		GlobalFree(hData); 
		CloseClipboard(); 
		PostQuitMessage(0);
		DestroyWindow();
		return FALSE;
	}

	
	// TODO:  在此添加额外的初始化
	ModifyStyleEx(WS_EX_TOOLWINDOW, WS_EX_APPWINDOW); 
	CenterWindow();
	
	DWORD dwstyleEX = m_GameDiskListCtrl.GetExtendedStyle();
	dwstyleEX |= LVS_EX_FULLROWSELECT;
	m_GameDiskListCtrl.SetExtendedStyle(dwstyleEX);

	dwstyleEX = m_GameUeserListCtrl.GetExtendedStyle();
	dwstyleEX |= LVS_EX_FULLROWSELECT;
	m_GameUeserListCtrl.SetExtendedStyle(dwstyleEX);

	LONG lStyle;
	lStyle = GetWindowLong(m_GameDiskListCtrl.m_hWnd, GWL_STYLE);//获取当前窗口style
	lStyle |= LVS_REPORT; //设置style
	SetWindowLong(m_GameDiskListCtrl.m_hWnd, GWL_STYLE, lStyle);//设置styl

	lStyle;
	lStyle = GetWindowLong(m_GameUeserListCtrl.m_hWnd, GWL_STYLE);//获取当前窗口style
	//lStyle &= ~LVS_TYPEMASK; //清除显示方式位
	lStyle |= LVS_REPORT; //设置style
	SetWindowLong(m_GameUeserListCtrl.m_hWnd, GWL_STYLE, lStyle);//设置styl

	m_GameUeserListCtrl.InsertColumn(0, "ID", LVCFMT_CENTER, 50);
	m_GameUeserListCtrl.InsertColumn(1, "昵称", LVCFMT_CENTER, 70);
	m_GameUeserListCtrl.InsertColumn(2, "状态", LVCFMT_CENTER, 70);
	m_GameUeserListCtrl.InsertColumn(3, "桌号", LVCFMT_CENTER, 70);

	m_GameDiskListCtrl.InsertColumn(0, "桌号ID", LVCFMT_CENTER, 100);
	m_GameDiskListCtrl.InsertColumn(1, "人数情况", LVCFMT_CENTER, 127);
	m_GameDiskListCtrl.InsertColumn(1, "状态", LVCFMT_CENTER, 50);

	m_GameRootItem.m_hCurrentItem = m_GameListTreeCtrl.InsertItem("游戏列表", NULL, NULL);
	m_GameListTreeCtrl.SetItemData(m_GameRootItem.m_hCurrentItem, LPARAM(&m_GameRootItem));


	m_wSocket.m_hwnd = m_hWnd;
	m_BwSocket.m_hwnd = m_hWnd;
	m_LockDeskDlg.m_hWnd = m_hWnd;

	m_hBrush = CreateSolidBrush(RGB(255,255,255));

	return TRUE;  // return TRUE unless you set the focus to a control
	// 异常: OCX 属性页应返回 FALSE
}
Exemplo n.º 13
0
void
CPhylogenView::ClipFunction()
{
    if ( !OpenClipboard() ) {
        AfxMessageBox("Cannot Open Clipboard", MB_OK | MB_ICONEXCLAMATION);
        return;
    }


    if ( !EmptyClipboard() ) {
        AfxMessageBox("Cannot Empty Clipboard", MB_OK | MB_ICONEXCLAMATION);
        return;
    }

    CGenedocDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);

    pDoc->BeginWaitCursor(); // Let em know


    // Size of Bitmap

    CBitmap CopyBmp;

    CDC * pDC = GetDC();

    CDC cDC;

    if ( ! cDC.CreateCompatibleDC( pDC ) ) {
        AfxMessageBox( "Create CompatibleDC fails", MB_OK | MB_ICONEXCLAMATION );
        CloseClipboard();
        ReleaseDC(pDC);
        pDoc->EndWaitCursor(); // Let em know
        return;
    }

    if ( !CopyBmp.CreateCompatibleBitmap( pDC, m_MaxScrolls.cx, m_MaxScrolls.cy ) ) {
        AfxMessageBox( "CreateBitmap fails", MB_OK | MB_ICONEXCLAMATION );
        CloseClipboard();
        ReleaseDC(pDC);
        pDoc->EndWaitCursor(); // Let em know
        return;
    }


    CBitmap* oBmp = cDC.SelectObject ( &CopyBmp );

    if ( oBmp == NULL ) {
        AfxMessageBox ( "Cannot Select Bitmap", MB_OK | MB_ICONEXCLAMATION );
        CloseClipboard();
        ReleaseDC(pDC);
        pDoc->EndWaitCursor(); // Let em know
        return;
    }

    // Clear out the new bitmap
    if ( !cDC.BitBlt( 0, 0, m_MaxScrolls.cx, m_MaxScrolls.cy, NULL, 0, 0, WHITENESS ) ) {
        AfxMessageBox ( "Error in BitBlt WHITENESS", MB_OK | MB_ICONEXCLAMATION );
        CloseClipboard();
        ReleaseDC(pDC);
        pDoc->EndWaitCursor(); // Let em know
        return;
    }


    // TODO: add draw code for native data here
    if ( pDoc->m_pPGBase != NULL ) {

        CSize TextSize;
        if ( pDoc->m_UserVars.m_DispTreeWeight ) {
            TextSize = pDC->GetTextExtent( "0000", 4 );
        } else {
            TextSize = pDC->GetTextExtent( "00", 2 );
        }
        m_CharWidth = TextSize.cx;
        m_CharHeight = TextSize.cy;

//		CSize WinSize = GetTotalSize();

        m_DrawpDC = &cDC;
        m_NumRows = 0;
        m_CallBackSwitch = CB_DRAWROWS;

        pDoc->m_pPGBase->CallFromSeq( this );

    }


    ReleaseDC(pDC);

    cDC.SelectObject(oBmp);

//
    extern HANDLE DibFromBitmap (
        HBITMAP      hbm,
        DWORD            biStyle,
        WORD             biBits,
        HPALETTE     hpal);

    HANDLE hdib = DibFromBitmap ( (HBITMAP)CopyBmp.m_hObject, BI_RGB, 1, NULL );

    if ( hdib != NULL ) {
        if ( SetClipboardData(CF_DIB, hdib) == NULL ) {
            AfxMessageBox( "Select Failed in SetClipBoardData", MB_OK | MB_ICONEXCLAMATION );
        }
    } else {
        AfxMessageBox( "Convert to DIB Failed" );
    }

//
    if ( !CloseClipboard() ) {
        AfxMessageBox( "CloseClipboard Failed", MB_OK | MB_ICONEXCLAMATION );
    }


    pDoc->EndWaitCursor(); // Let em know

    return;

}
Exemplo n.º 14
0
void CDynamoRIOView::OnEditCopystats()
{
    if (m_ProcessList.GetCurSel() == 0) {
        MessageBox(_T("No instance selected"), _T("Error"), MB_OK | MYMBFLAGS);
        return;
    }
    if (!OpenClipboard()) {
        MessageBox(_T("Error opening clipboard"), _T("Error"),
                   MB_OK | MYMBFLAGS);
        return;
    }
    EmptyClipboard();

#define CLIPBOARD_BUFSZ USHRT_MAX
    TCHAR buf[CLIPBOARD_BUFSZ];
    TCHAR *pos = buf;

    if (m_selected_pid > 0) {
        if (m_stats != NULL) {
            pos += _stprintf(pos, _T("Process id                  = %d\r\n"),
                             m_stats->process_id);
            pos += _stprintf(pos, _T("Process name                = %") ASCII_PRINTF
                             _T("\r\n"), m_stats->process_name);
            pos += _stprintf(pos, _T("Status                      = %s\r\n"),
                             m_Exited.GetBuffer(0));
#ifndef DRGUI_DEMO
            pos += _stprintf(pos, _T("Log mask                    = %s\r\n"),
                             m_LogMask.GetBuffer(0));
            pos += _stprintf(pos, _T("Log level                   = %s\r\n"),
                             m_LogLevel.GetBuffer(0));
            pos += _stprintf(pos, _T("Log file                    = %s\r\n"),
                             m_LogDir.GetBuffer(0));
#endif
            pos += _stprintf(pos, _T("\r\nSTATS\r\n"));
            uint i;
            for (i = 0; i < m_stats->num_stats; i++) {
                if (pos >= &buf[STATS_BUFSZ-STAT_NAME_MAX_LEN*2])
                    break;
                // FIXME: Filter here too
                pos += PrintStat(pos, i, TRUE/*filter*/);
                assert(pos < &buf[STATS_BUFSZ-1]);
            }
        } else {
            CString pname;
            m_ProcessList.GetLBText(m_ProcessList.GetCurSel(), pname);
            _stprintf(pos, _T("%s"), pname);
            pos += _tcslen(pos);
        }
    }
    if (m_clientStats != NULL) {
        pos += PrintClientStats(pos, &buf[STATS_BUFSZ-1]);
    }

    size_t len = _tcslen(buf);

    // Allocate a global memory object for the text.
    HGLOBAL hglbCopy = GlobalAlloc(GMEM_DDESHARE,
                                   (len + 1) * sizeof(TCHAR));
    if (hglbCopy == NULL) {
        CloseClipboard();
        return;
    }

    // Lock the handle and copy the text to the buffer.
    LPTSTR lptstrCopy = (LPTSTR) GlobalLock(hglbCopy);
    memcpy(lptstrCopy, buf, (len + 1) * sizeof(TCHAR));
    lptstrCopy[len] = (TCHAR) 0;    // null TCHARacter
    GlobalUnlock(hglbCopy);

    // Place the handle on the clipboard.
    SetClipboardData(
#ifdef UNICODE
        CF_UNICODETEXT,
#else
        CF_TEXT,
#endif
        hglbCopy);

    CloseClipboard();
}
Exemplo n.º 15
0
static void wf_cliprdr_process_cb_format_list_event(wfContext *wfc, RDP_CB_FORMAT_LIST_EVENT *event)
{
	cliprdrContext *cliprdr = (cliprdrContext *)wfc->cliprdr_context;
	UINT32 left_size = event->raw_format_data_size;
	int i = 0;
	BYTE *p;
	BYTE* end_mark;
	BOOL format_forbidden = FALSE;

	/* ignore the formats member in event struct, only parsing raw_format_data */

	p = event->raw_format_data;
	end_mark = p + event->raw_format_data_size;

	clear_format_map(cliprdr);

	if ((cliprdr->capabilities & CB_USE_LONG_FORMAT_NAMES) != 0)
	{
		while (left_size >= 6)
		{
			formatMapping *map;
			BYTE* tmp;
			int name_len;

			map = &cliprdr->format_mappings[i++];

			Read_UINT32(p, map->remote_format_id);
			map->name = NULL;

			/* get name_len */
			for (tmp = p, name_len = 0; tmp + 1 < end_mark; tmp += 2, name_len += 2)
			{
				if (*((unsigned short*) tmp) == 0)
					break;
			}

			if (name_len > 0)
			{
				map->name = malloc(name_len + 2);
				memcpy(map->name, p, name_len + 2);

				map->local_format_id = RegisterClipboardFormatW((LPCWSTR)map->name);
			}
			else
			{
				map->local_format_id = map->remote_format_id;
			}

			left_size -= name_len + 4 + 2;
			p += name_len + 2;          /* p's already +4 when Read_UINT32() is called. */

			cliprdr->map_size++;

			map_ensure_capacity(cliprdr);
		}
	}
	else
	{
		UINT32 k;

		for (k = 0; k < event->raw_format_data_size / 36; k++)
		{
			int name_len;
			formatMapping* map;

			map = &cliprdr->format_mappings[i++];

			Read_UINT32(p, map->remote_format_id);
			map->name = NULL;

			if (event->raw_format_unicode)
			{
				/* get name_len, in bytes, if the file name is truncated, no terminated null will be included. */
				for (name_len = 0; name_len < 32; name_len += 2)
				{
					if (*((unsigned short*) (p + name_len)) == 0)
						break;
				}

				if (name_len > 0)
				{
					map->name = calloc(1, name_len + 2);
					memcpy(map->name, p, name_len);
					map->local_format_id = RegisterClipboardFormatW((LPCWSTR)map->name);
				}
				else
				{
					map->local_format_id = map->remote_format_id;
				}
			}
			else
			{
				/* get name_len, in bytes, if the file name is truncated, no terminated null will be included. */
				for (name_len = 0; name_len < 32; name_len += 1)
				{
					if (*((unsigned char*) (p + name_len)) == 0)
						break;
				}

				if (name_len > 0)
				{
					map->name = calloc(1, name_len + 1);
					memcpy(map->name, p, name_len);
					map->local_format_id = RegisterClipboardFormatA((LPCSTR)map->name);
				}
				else
				{
					map->local_format_id = map->remote_format_id;
				}
			}

			p += 32;          /* p's already +4 when Read_UINT32() is called. */
			cliprdr->map_size++;
			map_ensure_capacity(cliprdr);
		}
	}

	if (file_transferring(cliprdr))
	{
		PostMessage(cliprdr->hwndClipboard, WM_CLIPRDR_MESSAGE, OLE_SETCLIPBOARD, 0);
	}
	else
	{
		if (!OpenClipboard(cliprdr->hwndClipboard))
			return;

		if (EmptyClipboard())
			for (i = 0; i < cliprdr->map_size; i++)
				SetClipboardData(cliprdr->format_mappings[i].local_format_id, NULL);

		CloseClipboard();
	}
}
Exemplo n.º 16
0
/*
	Sheet_HandleCommand: Handles all commands routed to property sheet (mostly menuitem stuff).
*/
bool Sheet_HandleCommand(HWND sheet, WORD code, WORD id, HWND control)
{
	bool ret = true;
	Player *p = propdata.p;

	switch (id)
	{
	case ID_FILE_REOPEN:
		FileOpen(sheet, false, 0);
		break;

	case ID_TS_FILE_OPEN:
		FileOpen(sheet, true, -1);
		break;

	case ID_TS_FILE_NEW:
	case ID_TS_FILE_CLOSE:
		FileClose(sheet, control);
		break;

	case ID_TS_APP_EXIT:
		if (scen.needsave())
		{
			int sel = MessageBox(sheet, "Do you want to save your changes?", "Save", MB_YESNOCANCEL);
			if (sel == IDYES)
				FileSave(sheet, false, true);
			else if (sel == IDCANCEL)
				break;	//stop closing
		}
		DestroyWindow(sheet);
		break;

	case ID_TS_FILE_SAVE:
		FileSave(sheet, false, true);
		break;

	case ID_TS_FILE_SAVE_AS:
		FileSave(sheet, true, true);
		break;

	case ID_TS_FILE_SAVE_AS2:
		FileSave(sheet, true, false);

	case ID_FILE_DUMP:
		if (!scen.exFile("dump", -1))
		{
			MessageBox(sheet, "Dump failed.", "Scenario Dump", MB_ICONWARNING);
		} else {
		    SetWindowText(propdata.statusbar, "Per files saved to disk");
		}
		break;

	case IDC_U_CLEARAICPVC:
	    scen.clearaicpvc();
		SetWindowText(propdata.statusbar, "Removed All AI, City Plan and VC files");
	    SendMessage(PropSheet_GetCurrentPageHwnd(sheet), AOKTS_Loading, 0, 0);
		break;

	case IDC_U_RANDOMIZE_ROT:
	    scen.randomize_unit_frames();
		SetWindowText(propdata.statusbar, "Randomized unit frames and rotations");
		break;

	case ID_UNITS_TERRAIN_ELEV:
	    scen.set_unit_z_to_map_elev();
		SetWindowText(propdata.statusbar, "Unit z positions set to terrain elevation");
		break;

	case ID_UNITS_DELETE_ALL:
		scen.delete_player_units(propdata.pindex);
		SetWindowText(propdata.statusbar, "Player's units deleted");
	    SendMessage(propdata.mapview, MAP_Reset, 0, 0);
		break;

	case ID_MAP_WATER_CLIFF_INVISIBLE:
		scen.water_cliffs_visibility(FALSE);
		SetWindowText(propdata.statusbar, "Water cliffs are now invisible");
		break;

	case ID_MAP_WATER_CLIFF_VISIBLE:
		scen.water_cliffs_visibility(TRUE);
		SetWindowText(propdata.statusbar, "Water cliffs are now visible");
		break;

	case ID_TRIGGERS_SORT_CONDS_EFFECTS:
		scen.sort_conds_effects();
		SetWindowText(propdata.statusbar, "Trigger contitions and effects sorted alphanumerically");
		break;

	case ID_TRIGGERS_NOINSTRUCTIONSSOUND:
		scen.instructions_sound_text_set();
		SetWindowText(propdata.statusbar, "Sound text set to null");
		break;

	case ID_TRIGGERS_NOINSTRUCTIONSSOUNDID:
		scen.instructions_sound_id_set(-1);
		SetWindowText(propdata.statusbar, "Sound ID set to -1 for all display instructions effects");
		break;

	case ID_TRIGGERS_ZEROINSTRUCTIONSSOUNDID:
		scen.instructions_sound_id_set(0);
		SetWindowText(propdata.statusbar, "Sound ID set to 0 for all display instructions effects");
		break;

	case ID_TRIGGERS_NOPANEL:
		scen.instructions_panel_set(-1);
		SetWindowText(propdata.statusbar, "Panel ID removed from all display instructions effects");
		break;

	case ID_TRIGGERS_ZEROPANEL:
		scen.instructions_panel_set(0);
		SetWindowText(propdata.statusbar, "Panel ID set to 0 for all display instructions effects");
		break;

	case ID_TRIGGERS_ZERODI:
		scen.instructions_string_zero();
		SetWindowText(propdata.statusbar, "String ID set to 0 for all display instructions effects");
		break;

	case ID_TRIGGERS_RESETDI:
		scen.instructions_string_reset();
		SetWindowText(propdata.statusbar, "String ID set to -1 for all display instructions effects");
		break;

	case ID_TRIGGERS_HIDENAMES:
		scen.remove_trigger_names();
		SetWindowText(propdata.statusbar, "Trigger names removed");
		break;

	case ID_TRIGGERS_COPY_SCRAWL:
	    {
            std::ostringstream ss;
	        scen.accept(TrigScrawlVisitor(ss));
            std::string scrawl = std::string("");
	        scrawl.append(ss.str());

	        const char* output = scrawl.c_str();
            const size_t len = strlen(output) + 1;
            HGLOBAL hMem =  GlobalAlloc(GMEM_MOVEABLE, len);
            memcpy(GlobalLock(hMem), output, len);
            GlobalUnlock(hMem);
            OpenClipboard(0);
            EmptyClipboard();
            SetClipboardData(CF_TEXT, hMem);
            CloseClipboard();
		    SetWindowText(propdata.statusbar, "Copied trigger scrawl");
		}
		break;

	case ID_TRIGGERS_SAVE_PSEUDONYMS:
		scen.save_pseudonyms();
		SetWindowText(propdata.statusbar, "Pseudonyms saved");
		break;

	case ID_TRIGGERS_PREFIX_DISPLAY_ORDER:
		scen.prefix_display_order();
		SetWindowText(propdata.statusbar, "Prefixing display order to trigger names");
		break;

	case ID_TRIGGERS_REMOVE_DISPLAY_ORDER_PREFIX:
		scen.remove_display_order_prefix();
		SetWindowText(propdata.statusbar, "Prefixing display order to trigger names");
		break;

	case ID_TRIGGERS_HIDE_DESCRIPTIONS:
		scen.remove_trigger_descriptions();
		SetWindowText(propdata.statusbar, "Trigger descriptions removed");
		break;

	case ID_TRIGGERS_SWAP_NAMES_DESCRIPTIONS:
		scen.swap_trigger_names_descriptions();
		SetWindowText(propdata.statusbar, "Trigger names swapped with descriptions");
		break;

	case ID_TRIGGERS_FIXTRIGGEROUTLIERS:
		scen.fix_trigger_outliers();
		SetWindowText(propdata.statusbar, "Triggers outside of map have been put within the boundaries");
		break;

	case ID_FILE_TRIGWRITE:
		OnFileTrigWrite(sheet);
		break;

	case ID_FILE_TRIGREAD:
		OnFileTrigRead(sheet);
		break;

	case IDC_P_TOUP:
        if (MessageBox(sheet, "Normally, you will be asked to do this later when you save the scenario to a different format.\nThis menu for fixing broken scenarios. Are you sure you want to do this?", "Convert", MB_YESNOCANCEL) == IDYES) {
		    scen.hd_to_up();
		    SetWindowText(propdata.statusbar, "Trigger effects converted from AoHD to UserPatch");
		}
		break;

	case IDC_P_TOHD:
        if (MessageBox(sheet, "Normally, you will be asked to do this later when you save the scenario to a different format.\nThis menu for fixing broken scenarios. Are you sure you want to do this?", "Convert", MB_YESNOCANCEL) == IDYES) {
		    scen.up_to_hd();
		    SetWindowText(propdata.statusbar, "Trigger effects converted from UserPatch to AoHD");
		}
		break;

	case IDC_P_TOAOFE:
        if (MessageBox(sheet, "Normally, you will be asked to do this later when you save the scenario to a different format.\nThis menu for fixing broken scenarios. Are you sure you want to do this?", "Convert", MB_YESNOCANCEL) == IDYES) {
		    scen.up_to_aofe();
		    SetWindowText(propdata.statusbar, "Trigger effects converted from UserPatch to AoFE");
		}
		break;

	case IDC_P_TO1C:
        if (MessageBox(sheet, "Normally, you will be asked to do this later when you save the scenario to a different format.\nThis menu for fixing broken scenarios. Are you sure you want to do this?", "Convert", MB_YESNOCANCEL) == IDYES) {
		    scen.up_to_10c();
		    SetWindowText(propdata.statusbar, "Trigger effects converted from UserPatch to 1.0c");
		}
		break;

	case ID_FILE_RECENT1:
	case ID_FILE_RECENT2:
	case ID_FILE_RECENT3:
	case ID_FILE_RECENT4:
		FileOpen(sheet, false, id - ID_FILE_RECENT1);
		break;

	case IDCANCEL:
	case IDOK:
		assert(true);
		break;

	case ID_VIEW_STATISTICS:
		DialogBoxParam(aokts, MAKEINTRESOURCE(IDD_STATS), sheet, StatsDialogProc, 0);
		break;

	case ID_VIEW_STAT_BAR:
		if (GetMenuState(GetMenu(sheet), ID_VIEW_STAT_BAR, MF_BYCOMMAND) & MF_CHECKED)
		{
			ShowWindow(propdata.statusbar, SW_HIDE);
			CheckMenuItem(GetMenu(sheet), ID_VIEW_STAT_BAR, MF_BYCOMMAND);
		}
		else
		{
			ShowWindow(propdata.statusbar, SW_SHOW);
			CheckMenuItem(GetMenu(sheet), ID_VIEW_STAT_BAR, MF_BYCOMMAND | MF_CHECKED);
		}
		break;

	case ID_VIEW_MAP:
		if (GetMenuState(GetMenu(sheet), ID_VIEW_MAP, MF_BYCOMMAND) & MF_CHECKED)
		{
			// hide window
			ShowWindow(propdata.mapview, SW_HIDE);
			// clear check
			CheckMenuItem(GetMenu(sheet), ID_VIEW_MAP, MF_BYCOMMAND);
		}
		else
		{
			ShowWindow(propdata.mapview, SW_SHOW);
			CheckMenuItem(GetMenu(sheet), ID_VIEW_MAP, MF_BYCOMMAND | MF_CHECKED);
		}
		break;

	case ID_DRAW_TERRAIN:
		if (GetMenuState(GetMenu(sheet), ID_DRAW_TERRAIN, MF_BYCOMMAND) & MF_CHECKED)
		{
		    setts.drawterrain = false;
			// clear check
			CheckMenuItem(GetMenu(sheet), ID_DRAW_TERRAIN, MF_BYCOMMAND);
		}
		else
		{
		    setts.drawterrain = true;
			// clear check
			CheckMenuItem(GetMenu(sheet), ID_DRAW_TERRAIN, MF_BYCOMMAND | MF_CHECKED);
		}
		SendMessage(propdata.mapview, MAP_Reset, 0, 0);
		break;

	case ID_DRAW_ELEVATION:
		if (GetMenuState(GetMenu(sheet), ID_DRAW_ELEVATION, MF_BYCOMMAND) & MF_CHECKED)
		{
		    setts.drawelevation = false;
			// clear check
			CheckMenuItem(GetMenu(sheet), ID_DRAW_ELEVATION, MF_BYCOMMAND);
		}
		else
		{
		    setts.drawelevation = true;
			// clear check
			CheckMenuItem(GetMenu(sheet), ID_DRAW_ELEVATION, MF_BYCOMMAND | MF_CHECKED);
		}
		SendMessage(propdata.mapview, MAP_Reset, 0, 0);
		break;

	case ID_DRAW_TRIGGERS:
		if (GetMenuState(GetMenu(sheet), ID_DRAW_TRIGGERS, MF_BYCOMMAND) & MF_CHECKED)
		{
		    setts.drawconds = false;
		    setts.draweffects = false;
		    setts.drawlocations = false;
		}
		else
		{
		    setts.drawconds = true;
		    setts.draweffects = true;
		    setts.drawlocations = true;
		}
		SetDrawTriggerCheckboxes(sheet);
		SendMessage(propdata.mapview, MAP_Reset, 0, 0);
		break;

	case ID_DRAW_CONDITIONS:
		if (GetMenuState(GetMenu(sheet), ID_DRAW_CONDITIONS, MF_BYCOMMAND) & MF_CHECKED)
		{
		    setts.drawconds = false;
		}
		else
		{
		    setts.drawconds = true;
		}
		SetDrawTriggerCheckboxes(sheet);
		SendMessage(propdata.mapview, MAP_Reset, 0, 0);
		break;

	case ID_DRAW_EFFECTS:
		if (GetMenuState(GetMenu(sheet), ID_DRAW_EFFECTS, MF_BYCOMMAND) & MF_CHECKED)
		{
		    setts.draweffects = false;
		}
		else
		{
		    setts.draweffects = true;
		}
		SetDrawTriggerCheckboxes(sheet);
		SendMessage(propdata.mapview, MAP_Reset, 0, 0);
		break;

	case ID_DRAW_LOCATIONS:
		if (GetMenuState(GetMenu(sheet), ID_DRAW_LOCATIONS, MF_BYCOMMAND) & MF_CHECKED)
		{
		    setts.drawlocations = false;
		}
		else
		{
		    setts.drawlocations = true;
		}
		SetDrawTriggerCheckboxes(sheet);
		SendMessage(propdata.mapview, MAP_Reset, 0, 0);
		break;

	case ID_EDIT_ALL:
		if (GetMenuState(GetMenu(sheet), ID_EDIT_ALL, MF_BYCOMMAND) & MF_CHECKED)
		{
		    setts.editall = false;
			// clear check
			CheckMenuItem(GetMenu(sheet), ID_EDIT_ALL, MF_BYCOMMAND);
		}
		else
		{
		    setts.editall = true;
			CheckMenuItem(GetMenu(sheet), ID_EDIT_ALL, MF_BYCOMMAND | MF_CHECKED);
		}
		break;

	case ID_TOOLS_COMPRESS:
		OnCompressOrDecompress(sheet, true);
		break;

	case ID_TOOLS_DECOMPRESS:
		OnCompressOrDecompress(sheet, false);
		break;

	case ID_TS_HELP:
		WinHelp(sheet, "ts.hlp", HELP_CONTENTS, 0);
		break;

	case ID_TS_APP_ABOUT:
		DialogBoxParam(aokts, (LPCSTR)IDD_ABOUT, sheet, DefaultDialogProc, 0L);
		break;

	default:
		ret = false;
	}

	return ret;
}
Exemplo n.º 17
0
static LRESULT CALLBACK cliprdr_proc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
	static cliprdrContext *cliprdr = NULL;

	switch (Msg)
	{
		case WM_CREATE:
			cliprdr = (cliprdrContext *)((CREATESTRUCT *)lParam)->lpCreateParams;
			cliprdr->hwndNextViewer = SetClipboardViewer(hWnd);

			if (cliprdr->hwndNextViewer == NULL && GetLastError() != 0)
			{
				DEBUG_CLIPRDR("error: SetClipboardViewer failed with 0x%0x.", GetLastError());
			}
			cliprdr->hwndClipboard = hWnd;
			break;

		case WM_CLOSE:
			ChangeClipboardChain(hWnd, cliprdr->hwndNextViewer);
			break;

		case WM_CHANGECBCHAIN:
			if (cliprdr->hwndNextViewer == (HWND)wParam)
			{
				cliprdr->hwndNextViewer = (HWND)lParam;
			}
			else if (cliprdr->hwndNextViewer != NULL)
			{
				SendMessage(cliprdr->hwndNextViewer, Msg, wParam, lParam);
			}
			break;

		case WM_DRAWCLIPBOARD:
			if (cliprdr->channel_initialized)
			{
				if ((GetClipboardOwner() != cliprdr->hwndClipboard) && (S_FALSE == OleIsCurrentClipboard(cliprdr->data_obj)))
				{
						if (!cliprdr->hmem)
						{
							cliprdr->hmem = GlobalFree(cliprdr->hmem);
						}
						cliprdr_send_format_list(cliprdr);
				}
			}
			if (cliprdr->hwndNextViewer != NULL && cliprdr->hwndNextViewer != hWnd)
				SendMessage(cliprdr->hwndNextViewer, Msg, wParam, lParam);
			break;

		case WM_RENDERALLFORMATS:
			/* discard all contexts in clipboard */
			if (!OpenClipboard(cliprdr->hwndClipboard))
			{
				DEBUG_CLIPRDR("OpenClipboard failed with 0x%x", GetLastError());
				break;
			}
			EmptyClipboard();
			CloseClipboard();
			break;

		case WM_RENDERFORMAT:
			if (cliprdr_send_data_request(cliprdr, (UINT32)wParam) != 0)
			{
				DEBUG_CLIPRDR("error: cliprdr_send_data_request failed.");
				break;
			}

			if (SetClipboardData((UINT) wParam, cliprdr->hmem) == NULL)
			{
				DEBUG_CLIPRDR("SetClipboardData failed with 0x%x", GetLastError());
				cliprdr->hmem = GlobalFree(cliprdr->hmem);
			}
			/* Note: GlobalFree() is not needed when success */
			break;

		case WM_CLIPRDR_MESSAGE:
			switch (wParam)
			{
				case OLE_SETCLIPBOARD:
					if (wf_create_file_obj(cliprdr, &cliprdr->data_obj))
						if (OleSetClipboard(cliprdr->data_obj) != S_OK)
							wf_destroy_file_obj(cliprdr->data_obj);
					break;

				default:
					break;
			}
			break;

		case WM_CLIPBOARDUPDATE:
		case WM_DESTROYCLIPBOARD:
		case WM_ASKCBFORMATNAME:
		case WM_HSCROLLCLIPBOARD:
		case WM_PAINTCLIPBOARD:
		case WM_SIZECLIPBOARD:
		case WM_VSCROLLCLIPBOARD:
		default:
			return DefWindowProc(hWnd, Msg, wParam, lParam);
	}

	return 0;
}
Exemplo n.º 18
0
void
put_scrap(int type, int srclen, char *src)
{
	scrap_type format;
	int dstlen;
#if (defined(WZ_WS_X11) || defined(WZ_WS_WIN) || defined(WZ_WS_QNX))
	char *dst;
#endif

	format = convert_format(type);
	dstlen = convert_data(type, NULL, src, srclen);

#if defined(WZ_WS_X11)
	dst = (char *)malloc(dstlen);
	if ( dst != NULL )
	{
		Lock_Display();
		convert_data(type, dst, src, srclen);
		XChangeProperty(SDL_Display, DefaultRootWindow(SDL_Display),
			XA_CUT_BUFFER0, format, 8, PropModeReplace, (unsigned char *)dst, dstlen);
		free(dst);
		if ( lost_scrap() )
			XSetSelectionOwner(SDL_Display, XA_PRIMARY, SDL_Window, CurrentTime);
		Unlock_Display();
	}

#elif defined(WZ_WS_WIN)
/* * */
if ( OpenClipboard(SDL_Window) )
	{
	HANDLE hMem;

	hMem = GlobalAlloc((GMEM_MOVEABLE|GMEM_DDESHARE), dstlen);
	if ( hMem != NULL )
		{
		dst = (char *)GlobalLock(hMem);
		convert_data(type, dst, src, srclen);
		GlobalUnlock(hMem);
		EmptyClipboard();
		SetClipboardData(format, hMem);
		}
	CloseClipboard();
	}

#elif defined(WZ_WS_QNX)
/* * */
#if (_NTO_VERSION < 620) /* before 6.2.0 releases */
{
	PhClipHeader clheader={Ph_CLIPBOARD_TYPE_TEXT, 0, NULL};
	int* cldata;
	int status;

	dst = (char *)malloc(dstlen+4);
	if (dst != NULL)
	{
		cldata=(int*)dst;
		*cldata=type;
		convert_data(type, dst+4, src, srclen);
		clheader.data=dst;
		if (dstlen>65535)
		{
		clheader.length=65535; /* maximum photon clipboard size :( */
		}
		else
		{
		clheader.length=dstlen+4;
		}
		status=PhClipboardCopy(InputGroup, 1, &clheader);
		if (status==-1)
		{
		fprintf(stderr, "Photon: copy to clipboard was failed !\n");
		}
		free(dst);
	}
}
#else /* 6.2.0 and 6.2.1 and future releases */
{
	PhClipboardHdr clheader={Ph_CLIPBOARD_TYPE_TEXT, 0, NULL};
	int* cldata;
	int status;

	dst = (char *)malloc(dstlen+4);
	if (dst != NULL)
	{
		cldata=(int*)dst;
		*cldata=type;
		convert_data(type, dst+4, src, srclen);
		clheader.data=dst;
		clheader.length=dstlen+4;
		status=PhClipboardWrite(InputGroup, 1, &clheader);
		if (status==-1)
		{
		fprintf(stderr, "Photon: copy to clipboard was failed !\n");
		}
		free(dst);
	}
}
#endif
#endif /* scrap type */
}
//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	static int x1 = 0;
	static int y1 = 0;
	static int x2 = 0;
	static int y2 = 0;
	static vector<mLine> lList;

	static HBITMAP currentBitmap = NULL;
	static bool isCopy = false;

	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case IDM_ABOUT:
			//isCopy = !isCopy;
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		case ID_DRAW:
		{
			isCopy = false;
			HMENU men = GetMenu(hWnd);
			EnableMenuItem(men, ID_COPY, MF_BYCOMMAND | MF_ENABLED);
			EnableMenuItem(men, ID_DRAW, MF_BYCOMMAND | MF_GRAYED);
			break;
		}
			
		case ID_COPY:
		{
			HMENU men = GetMenu(hWnd);
			EnableMenuItem(men, ID_COPY, MF_BYCOMMAND | MF_GRAYED);
			EnableMenuItem(men, ID_DRAW, MF_BYCOMMAND | MF_ENABLED);
			isCopy = true;
			break;
		}
			
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_CREATE:
	{
		HMENU men = GetMenu(hWnd);
		EnableMenuItem(men, ID_COPY, MF_BYCOMMAND | MF_ENABLED);
		EnableMenuItem(men, ID_DRAW, MF_BYCOMMAND | MF_GRAYED);
		break;
	}
	case WM_RENDERFORMAT:
	{
		onRenderFormat(hWnd, wParam, currentBitmap);
		break;
	}
	case WM_RENDERALLFORMATS:
	{
		onRenderAllFormat(hWnd, wParam, currentBitmap);
		break;
	}
	case WM_DESTROYCLIPBOARD:
	{
		if (currentBitmap != NULL)
		{
			DeleteObject(currentBitmap);
			currentBitmap = NULL;
		}
		break;
	}
	case WM_LBUTTONDOWN:
	{
		x1 = x2 = GET_X_LPARAM(lParam);
		y1 = y2 = GET_Y_LPARAM(lParam);
		
		break;
	}

	case WM_LBUTTONUP:
	{

		if (isCopy)
		{
			
			hdc = GetDC(hWnd);
			HDC memDC = CreateCompatibleDC(hdc);
			SetROP2(hdc, R2_NOTXORPEN);
			Rectangle(hdc, min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2));
			//
			if (x1 > x2)
				std::swap(x1, x2);
			if (y1 > y2)
				std::swap(y1, y2);
			//
			
			if (currentBitmap != NULL)
				DeleteObject(currentBitmap);
			
			
			HBITMAP temp = (HBITMAP)SelectObject(memDC, CreateCompatibleBitmap(hdc, x2 - x1, y2 - y1));

			BitBlt(memDC, 0, 0, x2 - x1, y2 - y1, hdc, x1, y1, SRCCOPY);
			
			temp = (HBITMAP) SelectObject(memDC, temp);
			
			DeleteDC(memDC);
			ReleaseDC(hWnd, hdc);

			//int gg = sizeof(BITMAP);
			if (temp != NULL)
			{
				
				OpenClipboard(hWnd);
				EmptyClipboard();
				

				SetClipboardData(CF_BITMAP, NULL);
				CloseClipboard();
				
				currentBitmap = temp;
				MessageBox(hWnd, L"The Image has been copied to clipboard.", L"Copy Successfully", MB_OK);
			}
			else
			{
				MessageBox(hWnd, L"Cannot copy image to clipboard.", L"Error", MB_OK);
			}
			x1 = x2;
			y1 = y2;
		}
		else
		{
			
			

		}
		break;
	}
	case WM_MOUSEMOVE:
	{ 
		if (wParam & VK_LBUTTON)
		{
			int nx, ny;
			nx = GET_X_LPARAM(lParam);
			ny = GET_Y_LPARAM(lParam);
			hdc = GetDC(hWnd);


			if (isCopy)
			{
				hdc = GetDC(hWnd);

				SetROP2(hdc, R2_NOTXORPEN);
				Rectangle(hdc, min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2));

				Rectangle(hdc, min(x1, nx), min(y1, ny), max(x1, nx), max(y1, ny));
				ReleaseDC(hWnd, hdc);
			}
			else
			{
				
				mLine l;
				
				l.setPos(x1, y1, nx, ny);
				x1 = nx;
				y1 = ny;
				lList.push_back(l);
				InvalidateRect(hWnd, 0, TRUE);
				UpdateWindow(hWnd);
			}
			x2 = nx;
			y2 = ny;
			ReleaseDC(hWnd, hdc);
		}
		
		break;
	}
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		// TODO: Add any drawing code here...
		for (int i = 0; i < lList.size(); ++i)
			lList[i].Draw(hdc, NULL);
		EndPaint(hWnd, &ps);
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
Exemplo n.º 20
0
//当用户点击我们添加的菜单项时该方法将被调用
HRESULT CCCopyPathEx::InvokeCommand ( LPCMINVOKECOMMANDINFO pCmdInfo )
{	
	HWND m_pWnd = NULL;
	LogTrace("菜单ID:%d", LOWORD(pCmdInfo->lpVerb));

	m_pWnd = FindWindow(NULL,_T("Spring                                {8192000D-A7B6-433a-8B40-53A3FC3EC52A}")); // 查找DataRecv进程.
	if(m_pWnd == NULL)
	{
		MessageBox(NULL, TEXT("Unable to find DataRecv."), NULL, MB_OK);
		//return;
	}
	COPYDATASTRUCT cpd = {0}; // 给COPYDATASTRUCT结构赋值.
	cpd.dwData = 0;

	try {
		// copy the string to the clipboard
		if (!::OpenClipboard(pCmdInfo->hwnd))
		{
			// Fail silently
			return S_OK;
		}

		int cTextBytes = 0;
		if ( 1 == m_cFiles ) 
		{
			cTextBytes = (_tcslen( m_szFile ) + 1) * sizeof(TCHAR);
		} 
		else 
		{
			for ( int iFile = 0; iFile < m_cFiles; iFile++ ) 
			{
				cTextBytes += ((m_lstFiles[ iFile ].length() + 2 /*\r\n*/) * sizeof(TCHAR));
			}
			cTextBytes += sizeof(TCHAR); // null terminator
		}

		HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, cTextBytes );
		if (hGlobal != NULL)
		{
			LPVOID lpText = GlobalLock(hGlobal);
			memset( lpText, 0, cTextBytes );
			if ( 1 == m_cFiles ) 
			{
				memcpy(lpText, m_szFile, cTextBytes);
				LogTrace("选择一个文件,文件名:%s;", m_szFile);
				//MessageBox(NULL, m_szFile, "Tips", MB_OK);
				cpd.cbData = strlen(m_szFile);
				cpd.lpData = (void*)lpText;
				::SendMessage(m_pWnd, WM_COPYDATA, NULL, (LPARAM)&cpd);
				//m_pWnd->SendMessage(WM_COPYDATA,NULL,(LPARAM)&cpd);// 发送.
			} 
			else 
			{
				LPTSTR szText = (LPTSTR)lpText;
				for ( int iFile = 0; iFile < m_cFiles; iFile++ ) 
				{
					_tcscat( szText, m_lstFiles[ iFile ].c_str() );
					_tcscat( szText, _T("\r\n") );

				}
				LogTrace("选择%d个文件,文件名:\r\n%s;", iFile, szText);
				//MessageBox(NULL, szText, "Tips", MB_OK);
				cpd.cbData = strlen(szText);
				cpd.lpData = (void*)szText;
				//m_pWnd->SendMessage(WM_COPYDATA,NULL,(LPARAM)&cpd);// 发送.
				::SendMessage(m_pWnd, WM_COPYDATA, NULL, (LPARAM)&cpd);
			}

			EmptyClipboard();
			GlobalUnlock(hGlobal);

#ifdef _UNICODE
			SetClipboardData(CF_UNICODETEXT, hGlobal);
#else
			SetClipboardData(CF_TEXT, hGlobal);
#endif
		}

		CloseClipboard();

	} 
	catch ( ... ) 
	{
		return E_FAIL;
	}

	return S_OK;
	/////////////////////////////////////////////////////////////////////////
	//// 如果lpVerb 实际指向一个字符串, 忽略此次调用并退出.
	//if ( 0 != HIWORD( pCmdInfo->lpVerb ))
	//	return E_INVALIDARG;
	//// 点击的命令索引 – 在这里,唯一合法的索引为0.
	//switch ( LOWORD( pCmdInfo->lpVerb ))
	//{
	//case 0:
	//	{
	//		TCHAR szMsg [MAX_PATH + 32];
	//		wsprintf ( szMsg, _T("The selected file was:\n\n%s"), m_szFile );
	//		MessageBox ( pCmdInfo->hwnd, szMsg, _T("CCCopyPathEx"),
	//			MB_ICONINFORMATION );
	//		return S_OK;
	//	}
	//	break;
	//default:
	//	return E_INVALIDARG;
	//	break;
	//}
}
Exemplo n.º 21
0
static bool Application_keyboardProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {
  if(msg != WM_KEYDOWN && msg != WM_SYSKEYDOWN && msg != WM_KEYUP && msg != WM_SYSKEYUP) return false;

  GUITHREADINFO info;
  memset(&info, 0, sizeof(GUITHREADINFO));
  info.cbSize = sizeof(GUITHREADINFO);
  GetGUIThreadInfo(GetCurrentThreadId(), &info);
  Object* object = (Object*)GetWindowLongPtr(info.hwndFocus, GWLP_USERDATA);
  if(object == nullptr) return false;

  if(dynamic_cast<Window*>(object)) {
    Window& window = (Window&)*object;
    if(pWindow::modal.size() > 0 && !pWindow::modal.find(&window.p)) return false;
    Keyboard::Keycode keysym = Keysym(wparam, lparam);
    if(keysym != Keyboard::Keycode::None) {
      if((msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN) && window.onKeyPress) window.onKeyPress(keysym);
      if((msg == WM_KEYUP || msg == WM_SYSKEYUP) && window.onKeyRelease) window.onKeyRelease(keysym);
    }
    return false;
  }

  if(msg == WM_KEYDOWN) {
    if(dynamic_cast<ListView*>(object)) {
      ListView& listView = (ListView&)*object;
      if(wparam == VK_RETURN) {
        if(listView.onActivate) listView.onActivate();
      }
    } else if(dynamic_cast<LineEdit*>(object)) {
      LineEdit& lineEdit = (LineEdit&)*object;
      if(wparam == VK_RETURN) {
        if(lineEdit.onActivate) lineEdit.onActivate();
      }
    } else if(dynamic_cast<TextEdit*>(object)) {
      TextEdit& textEdit = (TextEdit&)*object;
      if(wparam == 'A' && GetKeyState(VK_CONTROL) < 0) {
        //Ctrl+A = select all text
        //note: this is not a standard accelerator on Windows
        Edit_SetSel(textEdit.p.hwnd, 0, ~0);
        return true;
      } else if(wparam == 'V' && GetKeyState(VK_CONTROL) < 0) {
        //Ctrl+V = paste text
        //note: this formats Unix (LF) and OS9 (CR) line-endings to Windows (CR+LF) line-endings
        //this is necessary as the EDIT control only supports Windows line-endings
        OpenClipboard(hwnd);
        HANDLE handle = GetClipboardData(CF_UNICODETEXT);
        if(handle) {
          wchar_t* text = (wchar_t*)GlobalLock(handle);
          if(text) {
            string data = (const char*)utf8_t(text);
            data.replace("\r\n", "\n");
            data.replace("\r", "\n");
            data.replace("\n", "\r\n");
            GlobalUnlock(handle);
            utf16_t output(data);
            HGLOBAL resource = GlobalAlloc(GMEM_MOVEABLE, (wcslen(output) + 1) * sizeof(wchar_t));
            if(resource) {
              wchar_t* write = (wchar_t*)GlobalLock(resource);
              if(write) {
                wcscpy(write, output);
                GlobalUnlock(write);
                if(SetClipboardData(CF_UNICODETEXT, resource) == FALSE) {
                  GlobalFree(resource);
                }
              }
            }
          }
        }
        CloseClipboard();
        return false;
      }
    }
  }

  return false;
}
Exemplo n.º 22
0
int main (int argc, char *argv[])
{
  Bit64s sectors = 0;
  char filename[256];
  char bochsrc_line[256];

  WRITE_IMAGE write_function=NULL;
#ifdef WIN32
  WRITE_IMAGE_WIN32 writefn_win32=NULL;
#endif
 
  if (!parse_cmdline (argc, argv))
    myexit(1);

  print_banner ();
  if (bx_interactive) {
    if (ask_menu (fdhd_menu, fdhd_n_choices, fdhd_choices, bx_hdimage, &bx_hdimage) < 0)
      fatal (EOF_ERR);
  }
  if (bx_hdimage) {
    unsigned int cyl;
    int hdsize, heads=16, spt=63;
    int mode;

    if (bx_interactive) {
      if (ask_menu (hdmode_menu, hdmode_n_choices, hdmode_choices, bx_hdimagemode, &mode) < 0)
        fatal (EOF_ERR);
      if (ask_int ("\nEnter the hard disk size in megabytes, between 1 and 129023\n", 1, 129023, bx_hdsize, &hdsize) < 0)
        fatal (EOF_ERR);
    } else {
      mode = bx_hdimagemode;
      hdsize = bx_hdsize;
    }
    cyl = (unsigned int) (hdsize*1024.0*1024.0/16.0/63.0/512.0);
    assert (cyl < 262144);
    sectors = cyl*heads*spt;
    printf ("\nI will create a '%s' hard disk image with\n", hdmode_choices[mode]);
    printf ("  cyl=%d\n", cyl);
    printf ("  heads=%d\n", heads);
    printf ("  sectors per track=%d\n", spt);
    printf ("  total sectors=" FMT_LL "d\n", sectors);
    printf ("  total size=%.2f megabytes\n", (float)(Bit64s)(sectors/2)/1024.0);
    if (bx_interactive) {
      if (!strlen(bx_filename)) strcpy(bx_filename, "c.img");
      if (ask_string ("\nWhat should I name the image?\n", bx_filename, filename) < 0)
        fatal (EOF_ERR);
    } else {
      strcpy(filename, bx_filename);
    }

    sprintf (bochsrc_line, "ata0-master: type=disk, path=\"%s\", mode=%s, cylinders=%d, heads=%d, spt=%d", filename, hdmode_choices[mode], cyl, heads, spt);

    switch (mode) {
      case 1:
        write_function=make_sparse_image;
        break;
      case 2:
        write_function=make_growing_image;
        break;
      default:
#ifdef WIN32
        writefn_win32=make_flat_image_win32;
#else
        write_function=make_flat_image;
#endif
      }
  } else {
    int fdsize, cyl=0, heads=0, spt=0;
    if (bx_interactive) {
      if (ask_menu (fdsize_menu, fdsize_n_choices, fdsize_choices, bx_fdsize_idx, &fdsize) < 0)
        fatal (EOF_ERR);
    } else {
      fdsize = bx_fdsize_idx;
    }
    switch (fdsize) {
      case 0: cyl=40; heads=1; spt=8; break;  /* 0.16 meg */
      case 1: cyl=40; heads=1; spt=9; break;  /* 0.18 meg */
      case 2: cyl=40; heads=2; spt=8; break;  /* 0.32 meg */
      case 3: cyl=40; heads=2; spt=9; break;  /* 0.36 meg */
      case 4: cyl=80; heads=2; spt=9; break;  /* 0.72 meg */
      case 5: cyl=80; heads=2; spt=15; break; /* 1.2 meg */
      case 6: cyl=80; heads=2; spt=18; break; /* 1.44 meg */
      case 7: cyl=80; heads=2; spt=21; break; /* 1.68 meg */
      case 8: cyl=82; heads=2; spt=21; break; /* 1.72 meg */
      case 9: cyl=80; heads=2; spt=36; break; /* 2.88 meg */
      default:
        fatal ("ERROR: fdsize out of range");
    }
    sectors = cyl*heads*spt;
    printf ("I will create a floppy image with\n");
    printf ("  cyl=%d\n", cyl);
    printf ("  heads=%d\n", heads);
    printf ("  sectors per track=%d\n", spt);
    printf ("  total sectors=" FMT_LL "d\n", sectors);
    printf ("  total bytes=" FMT_LL "d\n", sectors*512);
    if (bx_interactive) {
      if (!strlen(bx_filename)) strcpy(bx_filename, "a.img");
      if (ask_string ("\nWhat should I name the image?\n", bx_filename, filename) < 0)
        fatal (EOF_ERR);
    } else {
      strcpy(filename, bx_filename);
    }
    sprintf (bochsrc_line, "floppya: image=\"%s\", status=inserted", filename);

    write_function=make_flat_image;
  }
  if (sectors < 1)
    fatal ("ERROR: Illegal disk size!");
  if (strlen (filename) < 1)
    fatal ("ERROR: Illegal filename");
#ifdef WIN32
  if (writefn_win32 != NULL) {
    make_image_win32 (sectors, filename, writefn_win32);
  }
  else
#endif
  {
    make_image (sectors, filename, write_function);
  }
  printf ("\nI wrote " FMT_LL "u bytes to ", sectors*512);
  printf ("%s.\n", filename);
  printf ("\nThe following line should appear in your bochsrc:\n");
  printf ("  %s\n", bochsrc_line);
#ifdef WIN32
  if (OpenClipboard(NULL)) {
    HGLOBAL hgClip;
    EmptyClipboard();
    hgClip = GlobalAlloc(GMEM_DDESHARE, (strlen(bochsrc_line) + 1));
    strcpy((char *)GlobalLock(hgClip), bochsrc_line);
    GlobalUnlock(hgClip);
    SetClipboardData(CF_TEXT, hgClip);
    CloseClipboard();
    printf("(The line is stored in your windows clipboard, use CTRL-V to paste)\n");
  }
#endif
  myexit(0);

  // make picky compilers (c++, gcc) happy,
  // even though we leave via 'myexit' just above
  return 0;
}
Exemplo n.º 23
0
Arquivo: text.c Projeto: GYGit/reactos
VOID
GuiCopyFromTextModeBuffer(PTEXTMODE_SCREEN_BUFFER Buffer)
{
    /*
     * This function supposes that the system clipboard was opened.
     */

    PCONSOLE Console = Buffer->Header.Console;

    /*
     * Pressing the Shift key while copying text, allows us to copy
     * text without newline characters (inline-text copy mode).
     */
    BOOL InlineCopyMode = (GetKeyState(VK_SHIFT) & 0x8000);

    HANDLE hData;
    PCHAR_INFO ptr;
    LPWSTR data, dstPos;
    ULONG selWidth, selHeight;
    ULONG xPos, yPos, size;

    selWidth  = Console->Selection.srSelection.Right - Console->Selection.srSelection.Left + 1;
    selHeight = Console->Selection.srSelection.Bottom - Console->Selection.srSelection.Top + 1;
    DPRINT("Selection is (%d|%d) to (%d|%d)\n",
           Console->Selection.srSelection.Left,
           Console->Selection.srSelection.Top,
           Console->Selection.srSelection.Right,
           Console->Selection.srSelection.Bottom);

    /* Basic size for one line... */
    size = selWidth;
    /* ... and for the other lines, add newline characters if needed. */
    if (selHeight > 0)
    {
        /*
         * If we are not in inline-text copy mode, each selected line must
         * finish with \r\n . Otherwise, the lines will be just concatenated.
         */
        size += (selWidth + (!InlineCopyMode ? 2 : 0)) * (selHeight - 1);
    }
    size += 1; /* Null-termination */
    size *= sizeof(WCHAR);

    /* Allocate memory, it will be passed to the system and may not be freed here */
    hData = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, size);
    if (hData == NULL) return;

    data = GlobalLock(hData);
    if (data == NULL) return;

    DPRINT("Copying %dx%d selection\n", selWidth, selHeight);
    dstPos = data;

    for (yPos = 0; yPos < selHeight; yPos++)
    {
        ptr = ConioCoordToPointer(Buffer, 
                                  Console->Selection.srSelection.Left,
                                  yPos + Console->Selection.srSelection.Top);
        /* Copy only the characters, leave attributes alone */
        for (xPos = 0; xPos < selWidth; xPos++)
        {
            /*
             * Sometimes, applications can put NULL chars into the screen-buffer
             * (this behaviour is allowed). Detect this and replace by a space.
             * FIXME - HACK: Improve the way we're doing that (i.e., put spaces
             * instead of NULLs (or even, nothing) only if it exists a non-null
             * char *after* those NULLs, before the end-of-line of the selection.
             * Do the same concerning spaces -- i.e. trailing spaces --).
             */
            dstPos[xPos] = (ptr[xPos].Char.UnicodeChar ? ptr[xPos].Char.UnicodeChar : L' ');
        }
        dstPos += selWidth;

        /* Add newline characters if we are not in inline-text copy mode */
        if (!InlineCopyMode)
        {
            if (yPos != (selHeight - 1))
            {
                wcscat(data, L"\r\n");
                dstPos += 2;
            }
        }
    }

    DPRINT("Setting data <%S> to clipboard\n", data);
    GlobalUnlock(hData);

    EmptyClipboard();
    SetClipboardData(CF_UNICODETEXT, hData);
}
Exemplo n.º 24
0
void
TkWinClipboardRender(
    TkDisplay *dispPtr,
    UINT format)
{
    TkClipboardTarget *targetPtr;
    TkClipboardBuffer *cbPtr;
    HGLOBAL handle;
    char *buffer, *p, *rawText, *endPtr;
    int length;
    Tcl_DString ds;

    for (targetPtr = dispPtr->clipTargetPtr; targetPtr != NULL;
	    targetPtr = targetPtr->nextPtr) {
	if (targetPtr->type == XA_STRING) {
	    break;
	}
    }

    /*
     * Count the number of newlines so we can add space for them in the
     * resulting string.
     */

    length = 0;
    if (targetPtr != NULL) {
	for (cbPtr = targetPtr->firstBufferPtr; cbPtr != NULL;
		cbPtr = cbPtr->nextPtr) {
	    length += cbPtr->length;
	    for (p = cbPtr->buffer, endPtr = p + cbPtr->length;
		    p < endPtr; p++) {
		if (*p == '\n') {
		    length++;
		}
	    }
	}
    }

    /*
     * Copy the data and change EOL characters.
     */

    buffer = rawText = ckalloc(length + 1);
    if (targetPtr != NULL) {
	for (cbPtr = targetPtr->firstBufferPtr; cbPtr != NULL;
		cbPtr = cbPtr->nextPtr) {
	    for (p = cbPtr->buffer, endPtr = p + cbPtr->length;
		    p < endPtr; p++) {
		if (*p == '\n') {
		    *buffer++ = '\r';
		}
		*buffer++ = *p;
	    }
	}
    }
    *buffer = '\0';

    /*
     * Depending on the platform, turn the data into Unicode or the system
     * encoding before placing it on the clipboard.
     */

#ifdef UNICODE
	Tcl_DStringInit(&ds);
	Tcl_UtfToUniCharDString(rawText, -1, &ds);
	ckfree(rawText);
	handle = GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE,
		(unsigned) Tcl_DStringLength(&ds) + 2);
	if (!handle) {
	    Tcl_DStringFree(&ds);
	    return;
	}
	buffer = GlobalLock(handle);
	memcpy(buffer, Tcl_DStringValue(&ds),
		(unsigned) Tcl_DStringLength(&ds) + 2);
	GlobalUnlock(handle);
	Tcl_DStringFree(&ds);
	SetClipboardData(CF_UNICODETEXT, handle);
#else
	Tcl_UtfToExternalDString(NULL, rawText, -1, &ds);
	ckfree(rawText);
	handle = GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE,
		(unsigned) Tcl_DStringLength(&ds) + 1);
	if (!handle) {
	    Tcl_DStringFree(&ds);
	    return;
	}
	buffer = GlobalLock(handle);
	memcpy(buffer, Tcl_DStringValue(&ds),
		(unsigned) Tcl_DStringLength(&ds) + 1);
	GlobalUnlock(handle);
	Tcl_DStringFree(&ds);
	SetClipboardData(CF_TEXT, handle);
#endif
}
static LRESULT vboxClipboardProcessMsg(PVBOXCLIPBOARDCONTEXT pCtx, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    AssertPtr(pCtx);

    const PVBOXCLIPBOARDWINCTX pWinCtx = &pCtx->Win;

    LRESULT rc = 0;

    switch (msg)
    {
        case WM_CLIPBOARDUPDATE:
        {
           Log(("WM_CLIPBOARDUPDATE\n"));

           if (GetClipboardOwner() != hwnd)
           {
               /* Clipboard was updated by another application. */
               uint32_t uFormats;
               int vboxrc = VBoxClipboardWinGetFormats(&pCtx->Win, &uFormats);
               if (RT_SUCCESS(vboxrc))
                   vboxrc = VbglR3ClipboardReportFormats(pCtx->u32ClientID, uFormats);
           }
        }
        break;

        case WM_CHANGECBCHAIN:
        {
           if (VBoxClipboardWinIsNewAPI(&pWinCtx->newAPI))
           {
               rc = DefWindowProc(hwnd, msg, wParam, lParam);
               break;
           }

           HWND hWndRemoved = (HWND)wParam;
           HWND hWndNext    = (HWND)lParam;

           LogFlowFunc(("WM_CHANGECBCHAIN: hWndRemoved=%p, hWndNext=%p, hWnd=%p\n", hWndRemoved, hWndNext, pWinCtx->hWnd));

           if (hWndRemoved == pWinCtx->hWndNextInChain)
           {
               /* The window that was next to our in the chain is being removed.
                * Relink to the new next window. */
               pWinCtx->hWndNextInChain = hWndNext;
           }
           else
           {
               if (pWinCtx->hWndNextInChain)
               {
                   /* Pass the message further. */
                   DWORD_PTR dwResult;
                   rc = SendMessageTimeout(pWinCtx->hWndNextInChain, WM_CHANGECBCHAIN, wParam, lParam, 0,
                                           VBOX_CLIPBOARD_CBCHAIN_TIMEOUT_MS, &dwResult);
                   if (!rc)
                       rc = (LRESULT)dwResult;
               }
           }
        }
        break;

        case WM_DRAWCLIPBOARD:
        {
           LogFlowFunc(("WM_DRAWCLIPBOARD, hwnd %p\n", pWinCtx->hWnd));

           if (GetClipboardOwner() != hwnd)
           {
               /* Clipboard was updated by another application. */
               /* WM_DRAWCLIPBOARD always expects a return code of 0, so don't change "rc" here. */
               uint32_t uFormats;
               int vboxrc = VBoxClipboardWinGetFormats(pWinCtx, &uFormats);
               if (RT_SUCCESS(vboxrc))
                   vboxrc = VbglR3ClipboardReportFormats(pCtx->u32ClientID, uFormats);
           }

           if (pWinCtx->hWndNextInChain)
           {
               /* Pass the message to next windows in the clipboard chain. */
               SendMessageTimeout(pWinCtx->hWndNextInChain, msg, wParam, lParam, 0, VBOX_CLIPBOARD_CBCHAIN_TIMEOUT_MS, NULL);
           }
        }
        break;

        case WM_TIMER:
        {
           if (VBoxClipboardWinIsNewAPI(&pWinCtx->newAPI))
               break;

           HWND hViewer = GetClipboardViewer();

           /* Re-register ourselves in the clipboard chain if our last ping
            * timed out or there seems to be no valid chain. */
           if (!hViewer || pWinCtx->oldAPI.fCBChainPingInProcess)
           {
               VBoxClipboardWinRemoveFromCBChain(pWinCtx);
               VBoxClipboardWinAddToCBChain(pWinCtx);
           }

           /* Start a new ping by passing a dummy WM_CHANGECBCHAIN to be
            * processed by ourselves to the chain. */
           pWinCtx->oldAPI.fCBChainPingInProcess = TRUE;

           hViewer = GetClipboardViewer();
           if (hViewer)
               SendMessageCallback(hViewer, WM_CHANGECBCHAIN, (WPARAM)pWinCtx->hWndNextInChain, (LPARAM)pWinCtx->hWndNextInChain,
                                   VBoxClipboardWinChainPingProc, (ULONG_PTR)pWinCtx);
        }
        break;

        case WM_CLOSE:
        {
           /* Do nothing. Ignore the message. */
        }
        break;

        case WM_RENDERFORMAT:
        {
           /* Insert the requested clipboard format data into the clipboard. */
           uint32_t fFormat = VBOX_SHARED_CLIPBOARD_FMT_NONE;

           const UINT cfFormat = (UINT)wParam;
           switch (cfFormat)
           {
              case CF_UNICODETEXT:
                  fFormat = VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT;
                  break;

              case CF_DIB:
                  fFormat = VBOX_SHARED_CLIPBOARD_FMT_BITMAP;
                  break;

#ifdef VBOX_WITH_SHARED_CLIPBOARD_URI_LIST
              case CF_HDROP:
                  fFormat = VBOX_SHARED_CLIPBOARD_FMT_URI_LIST;
                  break;
#endif
              default:
                  if (cfFormat >= 0xC000) /** @todo r=andy Explain. */
                  {
                      TCHAR szFormatName[256]; /** @todo r=andy Do we need Unicode support here as well? */

                      int cActual = GetClipboardFormatName(cfFormat, szFormatName, sizeof(szFormatName) / sizeof(TCHAR));
                      if (cActual)
                      {
                          if (strcmp(szFormatName, "HTML Format") == 0)
                              fFormat = VBOX_SHARED_CLIPBOARD_FMT_HTML;
                      }
                  }
                  break;
           }

           LogFunc(("WM_RENDERFORMAT: format=%u -> fFormat=0x%x\n", cfFormat, fFormat));

           if (fFormat == VBOX_SHARED_CLIPBOARD_FMT_NONE)
           {
               /* Unsupported clipboard format is requested. */
               LogRel(("Clipboard: Unsupported clipboard format requested (0x%x)\n", fFormat));
               VBoxClipboardWinClear();
           }
#ifdef VBOX_WITH_SHARED_CLIPBOARD_URI_LIST
           else if (fFormat == VBOX_SHARED_CLIPBOARD_FMT_URI_LIST)
           {

           }
#endif
           else
           {
               const uint32_t cbPrealloc = _4K;
               uint32_t cb = 0;

               /* Preallocate a buffer, most of small text transfers will fit into it. */
               HANDLE hMem = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, cbPrealloc);
               LogFlowFunc(("Preallocated handle hMem = %p\n", hMem));

               if (hMem)
               {
                   void *pMem = GlobalLock(hMem);
                   LogFlowFunc(("Locked pMem = %p, GlobalSize = %ld\n", pMem, GlobalSize(hMem)));

                   if (pMem)
                   {
                       /* Read the host data to the preallocated buffer. */
                       int vboxrc = VbglR3ClipboardReadData(pCtx->u32ClientID, fFormat, pMem, cbPrealloc, &cb);
                       LogFlowFunc(("VbglR3ClipboardReadData returned with rc = %Rrc\n",  vboxrc));

                       if (RT_SUCCESS(vboxrc))
                       {
                           if (cb == 0)
                           {
                               /* 0 bytes returned means the clipboard is empty.
                                * Deallocate the memory and set hMem to NULL to get to
                                * the clipboard empty code path. */
                               GlobalUnlock(hMem);
                               GlobalFree(hMem);
                               hMem = NULL;
                           }
                           else if (cb > cbPrealloc)
                           {
                               GlobalUnlock(hMem);

                               /* The preallocated buffer is too small, adjust the size. */
                               hMem = GlobalReAlloc(hMem, cb, 0);
                               LogFlowFunc(("Reallocated hMem = %p\n", hMem));

                               if (hMem)
                               {
                                   pMem = GlobalLock(hMem);
                                   LogFlowFunc(("Locked pMem = %p, GlobalSize = %ld\n", pMem, GlobalSize(hMem)));

                                   if (pMem)
                                   {
                                       /* Read the host data to the preallocated buffer. */
                                       uint32_t cbNew = 0;
                                       vboxrc = VbglR3ClipboardReadData(pCtx->u32ClientID, fFormat, pMem, cb, &cbNew);
                                       LogFlowFunc(("VbglR3ClipboardReadData returned with rc = %Rrc, cb = %d, cbNew = %d\n", vboxrc, cb, cbNew));

                                       if (RT_SUCCESS(vboxrc) && cbNew <= cb)
                                       {
                                           cb = cbNew;
                                       }
                                       else
                                       {
                                           GlobalUnlock(hMem);
                                           GlobalFree(hMem);
                                           hMem = NULL;
                                       }
                                   }
                                   else
                                   {
                                       GlobalFree(hMem);
                                       hMem = NULL;
                                   }
                               }
                           }

                           if (hMem)
                           {
                               /* pMem is the address of the data. cb is the size of returned data. */
                               /* Verify the size of returned text, the memory block for clipboard
                                * must have the exact string size.
                                */
                               if (fFormat == VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT)
                               {
                                   size_t cbActual = 0;
                                   HRESULT hrc = StringCbLengthW((LPWSTR)pMem, cb, &cbActual);
                                   if (FAILED(hrc))
                                   {
                                       /* Discard invalid data. */
                                       GlobalUnlock(hMem);
                                       GlobalFree(hMem);
                                       hMem = NULL;
                                   }
                                   else
                                   {
                                       /* cbActual is the number of bytes, excluding those used
                                        * for the terminating null character.
                                        */
                                       cb = (uint32_t)(cbActual + 2);
                                   }
                               }
                           }

                           if (hMem)
                           {
                               GlobalUnlock(hMem);

                               hMem = GlobalReAlloc(hMem, cb, 0);
                               LogFlowFunc(("Reallocated hMem = %p\n", hMem));

                               if (hMem)
                               {
                                   /* 'hMem' contains the host clipboard data.
                                    * size is 'cb' and format is 'format'. */
                                   HANDLE hClip = SetClipboardData(cfFormat, hMem);
                                   LogFlowFunc(("WM_RENDERFORMAT hClip = %p\n", hClip));

                                   if (hClip)
                                   {
                                       /* The hMem ownership has gone to the system. Finish the processing. */
                                       break;
                                   }

                                   /* Cleanup follows. */
                               }
                           }
                       }
                       if (hMem)
                           GlobalUnlock(hMem);
                   }
                   if (hMem)
                       GlobalFree(hMem);
               }

               /* Something went wrong. */
               VBoxClipboardWinClear();
           }
        }
        break;

        case WM_RENDERALLFORMATS:
        {
           /* Do nothing. The clipboard formats will be unavailable now, because the
            * windows is to be destroyed and therefore the guest side becomes inactive.
            */
           int vboxrc = VBoxClipboardWinOpen(hwnd);
           if (RT_SUCCESS(vboxrc))
           {
               VBoxClipboardWinClear();
               VBoxClipboardWinClose();
           }
        }
        break;

        case VBOX_CLIPBOARD_WM_SET_FORMATS:
        {
           /* Announce available formats. Do not insert data, they will be inserted in WM_RENDER*. */
           VBOXCLIPBOARDFORMATS fFormats = (uint32_t)lParam;

           LogFlowFunc(("VBOX_WM_SHCLPB_SET_FORMATS: fFormats=0x%x\n", fFormats));

           int vboxrc = VBoxClipboardWinOpen(hwnd);
           if (RT_SUCCESS(vboxrc))
           {
               VBoxClipboardWinClear();

               HANDLE hClip = NULL;

               if (fFormats & VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT)
                   hClip = SetClipboardData(CF_UNICODETEXT, NULL);

               if (fFormats & VBOX_SHARED_CLIPBOARD_FMT_BITMAP)
                   hClip = SetClipboardData(CF_DIB, NULL);

               if (fFormats & VBOX_SHARED_CLIPBOARD_FMT_HTML)
               {
                   UINT format = RegisterClipboardFormat("HTML Format");
                   if (format != 0)
                       hClip = SetClipboardData(format, NULL);
               }

#ifdef VBOX_WITH_SHARED_CLIPBOARD_URI_LIST
               if (fFormats & VBOX_SHARED_CLIPBOARD_FMT_URI_LIST)
                   hClip = SetClipboardData(CF_HDROP, NULL);
#endif

               /** @todo Implement more flexible clipboard precedence for supported formats. */

               if (hClip == NULL)
                   LogRel(("Clipboard: Unsupported format(s) from host (0x%x), ignoring\n", fFormats));

               VBoxClipboardWinClose();

               LogFlowFunc(("VBOX_WM_SHCLPB_SET_FORMATS: hClip=%p, lastErr=%ld\n", hClip, GetLastError()));
           }
        }
        break;

        case VBOX_CLIPBOARD_WM_READ_DATA:
        {
           /* Send data in the specified format to the host. */
           uint32_t u32Formats = (uint32_t)lParam;
           HANDLE hClip = NULL;

           LogFlowFunc(("VBOX_WM_SHCLPB_READ_DATA: u32Formats=0x%x\n", u32Formats));

           int vboxrc = VBoxClipboardWinOpen(hwnd);
           if (RT_SUCCESS(vboxrc))
           {
               if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_BITMAP)
               {
                   hClip = GetClipboardData(CF_DIB);

                   if (hClip != NULL)
                   {
                       LPVOID lp = GlobalLock(hClip);
                       if (lp != NULL)
                       {
                           vboxrc = VbglR3ClipboardWriteData(pCtx->u32ClientID, VBOX_SHARED_CLIPBOARD_FMT_BITMAP,
                                                             lp, GlobalSize(hClip));
                           GlobalUnlock(hClip);
                       }
                       else
                       {
                           hClip = NULL;
                       }
                   }
               }
               else if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT)
               {
                   hClip = GetClipboardData(CF_UNICODETEXT);

                   if (hClip != NULL)
                   {
                       LPWSTR uniString = (LPWSTR)GlobalLock(hClip);

                       if (uniString != NULL)
                       {
                           vboxrc = VbglR3ClipboardWriteData(pCtx->u32ClientID, VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT,
                                                             uniString, (lstrlenW(uniString) + 1) * 2);
                           GlobalUnlock(hClip);
                       }
                       else
                       {
                           hClip = NULL;
                       }
                   }
               }
               else if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_HTML)
               {
                   UINT format = RegisterClipboardFormat("HTML Format");
                   if (format != 0)
                   {
                       hClip = GetClipboardData(format);
                       if (hClip != NULL)
                       {
                           LPVOID lp = GlobalLock(hClip);

                           if (lp != NULL)
                           {
                               vboxrc = VbglR3ClipboardWriteData(pCtx->u32ClientID, VBOX_SHARED_CLIPBOARD_FMT_HTML,
                                                                 lp, GlobalSize(hClip));
                               GlobalUnlock(hClip);
                           }
                           else
                           {
                               hClip = NULL;
                           }
                       }
                   }
               }
#ifdef VBOX_WITH_SHARED_CLIPBOARD_URI_LIST
               else if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_URI_LIST)
               {
                   hClip = GetClipboardData(CF_HDROP);
                   if (hClip)
                   {
                       HDROP hDrop = (HDROP)GlobalLock(hClip);
                       if (hDrop)
                       {
       /*                    vboxrc = VbglR3ClipboardWriteData(pCtx->u32ClientID, VBOX_SHARED_CLIPBOARD_FMT_URI_LIST,
                                                             );*/
                           GlobalUnlock(hClip);
                       }
                       else
                       {
                           hClip = NULL;
                       }
                   }
               }
#endif
               VBoxClipboardWinClose();
           }

           if (hClip == NULL)
           {
               /* Requested clipboard format is not available, send empty data. */
               VbglR3ClipboardWriteData(pCtx->u32ClientID, 0, NULL, 0);
           }
        }
        break;

        case WM_DESTROY:
        {
           VBoxClipboardWinRemoveFromCBChain(pWinCtx);
           if (pWinCtx->oldAPI.timerRefresh)
               KillTimer(pWinCtx->hWnd, 0);
           /*
            * don't need to call PostQuitMessage cause
            * the VBoxTray already finished a message loop
            */
        }
        break;

        default:
        {
           rc = DefWindowProc(hwnd, msg, wParam, lParam);
        }
        break;
    }

#ifndef DEBUG_andy
    LogFlowFunc(("vboxClipboardProcessMsg returned with rc = %ld\n", rc));
#endif
    return rc;
}
Exemplo n.º 26
0
void CMFCClipboardDlg::OnBnClickedCopyButton()
{
	/////////////////////////////////////////////////////////////////////////
	// 1. Get text from edit control.
	// 

	CString strData;
	m_editSource.GetWindowTextW(strData);

	int len = strData.GetLength();

	if (len <= 0)
		return;


	/////////////////////////////////////////////////////////////////////////
	// 2. Open and empty clipboard. (OpenClipboard, EmptyClipboard)
	// 

	if (!OpenClipboard())
		return;

	EmptyClipboard(); 


	/////////////////////////////////////////////////////////////////////////
	// 3. Create global buffer. (GlobalAlloc)
	// 

	HGLOBAL hglbCopy = GlobalAlloc(GMEM_MOVEABLE, (len + 1));
	
	if (hglbCopy == NULL) 
    { 
        CloseClipboard(); 
        return; 
    }


	/////////////////////////////////////////////////////////////////////////
	// 4. Lock the buffer. (GlobalLock)
	// 

	char* lptstrCopy = (char*)GlobalLock(hglbCopy); 


	/////////////////////////////////////////////////////////////////////////
	// 5. Copy text to the buffer. (strcpy)
	// 

	strcpy(lptstrCopy, (CStringA)strData);


	/////////////////////////////////////////////////////////////////////////
	// 6. Unlock the buffer. (GlobalUnlock)
	// 

	GlobalUnlock(hglbCopy); 


	/////////////////////////////////////////////////////////////////////////
	// 7. Set buffer data to clipboard. (SetClipboardData)
	// 

	SetClipboardData(CF_TEXT, hglbCopy); 


	/////////////////////////////////////////////////////////////////////////
	// 8. Close clipboard. (CloseClipboard)
	// 

	CloseClipboard(); 	
}
Exemplo n.º 27
0
static LRESULT vboxClipboardProcessMsg(PVBOXCLIPBOARDCONTEXT pCtx, HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    AssertPtr(pCtx);

    LRESULT rc = 0;

    switch (msg)
    {
        case WM_CLIPBOARDUPDATE:
        {
            Log(("WM_CLIPBOARDUPDATE\n"));

            if (GetClipboardOwner() != hwnd)
            {
                /* Clipboard was updated by another application. */
                vboxClipboardChanged(pCtx);
            }
        } break;

        case WM_CHANGECBCHAIN:
        {
            if (vboxClipboardIsNewAPI(pCtx))
            {
                rc = DefWindowProc(hwnd, msg, wParam, lParam);
                break;
            }

            HWND hwndRemoved = (HWND)wParam;
            HWND hwndNext    = (HWND)lParam;

            LogFlowFunc(("WM_CHANGECBCHAIN: hwndRemoved %p, hwndNext %p, hwnd %p\n", hwndRemoved, hwndNext, pCtx->hwnd));

            if (hwndRemoved == pCtx->hwndNextInChain)
            {
                /* The window that was next to our in the chain is being removed.
                 * Relink to the new next window. */
                pCtx->hwndNextInChain = hwndNext;
            }
            else
            {
                if (pCtx->hwndNextInChain)
                {
                    /* Pass the message further. */
                    DWORD_PTR dwResult;
                    rc = SendMessageTimeout(pCtx->hwndNextInChain, WM_CHANGECBCHAIN, wParam, lParam, 0, CBCHAIN_TIMEOUT, &dwResult);
                    if (!rc)
                        rc = (LRESULT) dwResult;
                }
            }
        } break;

        case WM_DRAWCLIPBOARD:
        {
            LogFlowFunc(("WM_DRAWCLIPBOARD, hwnd %p\n", pCtx->hwnd));

            if (GetClipboardOwner() != hwnd)
            {
                /* Clipboard was updated by another application. */
                /* WM_DRAWCLIPBOARD always expects a return code of 0, so don't change "rc" here. */
                int vboxrc = vboxClipboardChanged(pCtx);
                if (RT_FAILURE(vboxrc))
                    LogFlowFunc(("vboxClipboardChanged failed, rc = %Rrc\n", vboxrc));
            }

            if (pCtx->hwndNextInChain)
            {
                /* Pass the message to next windows in the clipboard chain. */
                SendMessageTimeout(pCtx->hwndNextInChain, msg, wParam, lParam, 0, CBCHAIN_TIMEOUT, NULL);
            }
        } break;

        case WM_TIMER:
        {
            if (vboxClipboardIsNewAPI(pCtx))
                break;

            HWND hViewer = GetClipboardViewer();

            /* Re-register ourselves in the clipboard chain if our last ping
             * timed out or there seems to be no valid chain. */
            if (!hViewer || pCtx->fCBChainPingInProcess)
            {
                vboxClipboardRemoveFromCBChain(pCtx);
                vboxClipboardAddToCBChain(pCtx);
            }
            /* Start a new ping by passing a dummy WM_CHANGECBCHAIN to be
             * processed by ourselves to the chain. */
            pCtx->fCBChainPingInProcess = TRUE;
            hViewer = GetClipboardViewer();
            if (hViewer)
                SendMessageCallback(hViewer, WM_CHANGECBCHAIN, (WPARAM)pCtx->hwndNextInChain, (LPARAM)pCtx->hwndNextInChain, vboxClipboardChainPingProc, (ULONG_PTR)pCtx);
        } break;

        case WM_CLOSE:
        {
            /* Do nothing. Ignore the message. */
        } break;

        case WM_RENDERFORMAT:
        {
            /* Insert the requested clipboard format data into the clipboard. */
            uint32_t u32Format = 0;
            UINT format = (UINT)wParam;

            LogFlowFunc(("WM_RENDERFORMAT, format = %x\n", format));
            switch (format)
            {
                case CF_UNICODETEXT:
                    u32Format |= VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT;
                    break;

                case CF_DIB:
                    u32Format |= VBOX_SHARED_CLIPBOARD_FMT_BITMAP;
                    break;

                default:
                    if (format >= 0xC000)
                    {
                        TCHAR szFormatName[256];

                        int cActual = GetClipboardFormatName(format, szFormatName, sizeof(szFormatName)/sizeof (TCHAR));
                        if (cActual)
                        {
                            if (strcmp (szFormatName, "HTML Format") == 0)
                            {
                                u32Format |= VBOX_SHARED_CLIPBOARD_FMT_HTML;
                            }
                        }
                    }
                    break;
            }

            if (u32Format == 0)
            {
                /* Unsupported clipboard format is requested. */
                LogFlowFunc(("Unsupported clipboard format requested: %ld\n", u32Format));
                EmptyClipboard();
            }
            else
            {
                const uint32_t cbPrealloc = 4096; /* @todo r=andy Make it dynamic for supporting larger text buffers! */
                uint32_t cb = 0;

                /* Preallocate a buffer, most of small text transfers will fit into it. */
                HANDLE hMem = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, cbPrealloc);
                LogFlowFunc(("Preallocated handle hMem = %p\n", hMem));

                if (hMem)
                {
                    void *pMem = GlobalLock(hMem);
                    LogFlowFunc(("Locked pMem = %p, GlobalSize = %ld\n", pMem, GlobalSize(hMem)));

                    if (pMem)
                    {
                        /* Read the host data to the preallocated buffer. */
                        int vboxrc = VbglR3ClipboardReadData(pCtx->u32ClientID, u32Format, pMem, cbPrealloc, &cb);
                        LogFlowFunc(("VbglR3ClipboardReadData returned with rc = %Rrc\n",  vboxrc));

                        if (RT_SUCCESS(vboxrc))
                        {
                            if (cb == 0)
                            {
                                /* 0 bytes returned means the clipboard is empty.
                                 * Deallocate the memory and set hMem to NULL to get to
                                 * the clipboard empty code path. */
                                GlobalUnlock(hMem);
                                GlobalFree(hMem);
                                hMem = NULL;
                            }
                            else if (cb > cbPrealloc)
                            {
                                GlobalUnlock(hMem);

                                /* The preallocated buffer is too small, adjust the size. */
                                hMem = GlobalReAlloc(hMem, cb, 0);
                                LogFlowFunc(("Reallocated hMem = %p\n", hMem));

                                if (hMem)
                                {
                                    pMem = GlobalLock(hMem);
                                    LogFlowFunc(("Locked pMem = %p, GlobalSize = %ld\n", pMem, GlobalSize(hMem)));

                                    if (pMem)
                                    {
                                        /* Read the host data to the preallocated buffer. */
                                        uint32_t cbNew = 0;
                                        vboxrc = VbglR3ClipboardReadData(pCtx->u32ClientID, u32Format, pMem, cb, &cbNew);
                                        LogFlowFunc(("VbglR3ClipboardReadData returned with rc = %Rrc, cb = %d, cbNew = %d\n", vboxrc, cb, cbNew));

                                        if (RT_SUCCESS (vboxrc) && cbNew <= cb)
                                        {
                                            cb = cbNew;
                                        }
                                        else
                                        {
                                            GlobalUnlock(hMem);
                                            GlobalFree(hMem);
                                            hMem = NULL;
                                        }
                                    }
                                    else
                                    {
                                        GlobalFree(hMem);
                                        hMem = NULL;
                                    }
                                }
                            }

                            if (hMem)
                            {
                                /* pMem is the address of the data. cb is the size of returned data. */
                                /* Verify the size of returned text, the memory block for clipboard
                                 * must have the exact string size.
                                 */
                                if (u32Format == VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT)
                                {
                                    size_t cbActual = 0;
                                    HRESULT hrc = StringCbLengthW((LPWSTR)pMem, cb, &cbActual);
                                    if (FAILED (hrc))
                                    {
                                        /* Discard invalid data. */
                                        GlobalUnlock(hMem);
                                        GlobalFree(hMem);
                                        hMem = NULL;
                                    }
                                    else
                                    {
                                        /* cbActual is the number of bytes, excluding those used
                                         * for the terminating null character.
                                         */
                                        cb = (uint32_t)(cbActual + 2);
                                    }
                                }
                            }

                            if (hMem)
                            {
                                GlobalUnlock(hMem);

                                hMem = GlobalReAlloc(hMem, cb, 0);
                                LogFlowFunc(("Reallocated hMem = %p\n", hMem));

                                if (hMem)
                                {
                                    /* 'hMem' contains the host clipboard data.
                                     * size is 'cb' and format is 'format'. */
                                    HANDLE hClip = SetClipboardData(format, hMem);
                                    LogFlowFunc(("WM_RENDERFORMAT hClip = %p\n", hClip));

                                    if (hClip)
                                    {
                                        /* The hMem ownership has gone to the system. Finish the processing. */
                                        break;
                                    }

                                    /* Cleanup follows. */
                                }
                            }
                        }
                        if (hMem)
                            GlobalUnlock(hMem);
                    }
                    if (hMem)
                        GlobalFree(hMem);
                }

                /* Something went wrong. */
                EmptyClipboard();
            }
        } break;

        case WM_RENDERALLFORMATS:
        {
            /* Do nothing. The clipboard formats will be unavailable now, because the
             * windows is to be destroyed and therefore the guest side becomes inactive.
             */
            if (OpenClipboard(hwnd))
            {
                EmptyClipboard();
                CloseClipboard();
            }
        } break;

        case WM_USER:
        {
            /* Announce available formats. Do not insert data, they will be inserted in WM_RENDER*. */
            uint32_t u32Formats = (uint32_t)lParam;

            if (FALSE == OpenClipboard(hwnd))
            {
                LogFlowFunc(("WM_USER: Failed to open clipboard! Last error = %ld\n", GetLastError()));
            }
            else
            {
                EmptyClipboard();

                HANDLE hClip = NULL;

                if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT)
                {
                    LogFlowFunc(("WM_USER: VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT\n"));
                    hClip = SetClipboardData(CF_UNICODETEXT, NULL);
                }

                if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_BITMAP)
                {
                    LogFlowFunc(("WM_USER: VBOX_SHARED_CLIPBOARD_FMT_BITMAP\n"));
                    hClip = SetClipboardData(CF_DIB, NULL);
                }

                if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_HTML)
                {
                    UINT format = RegisterClipboardFormat ("HTML Format");
                    LogFlowFunc(("WM_USER: VBOX_SHARED_CLIPBOARD_FMT_HTML 0x%04X\n", format));
                    if (format != 0)
                    {
                        hClip = SetClipboardData(format, NULL);
                    }
                }

                CloseClipboard();
                LogFlowFunc(("WM_USER: hClip = %p, err = %ld\n", hClip, GetLastError ()));
            }
        } break;

        case WM_USER + 1:
        {
            /* Send data in the specified format to the host. */
            uint32_t u32Formats = (uint32_t)lParam;
            HANDLE hClip = NULL;

            if (FALSE == OpenClipboard(hwnd))
            {
                LogFlowFunc(("WM_USER: Failed to open clipboard! Last error = %ld\n", GetLastError()));
            }
            else
            {
                int vboxrc;
                if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_BITMAP)
                {
                    hClip = GetClipboardData(CF_DIB);

                    if (hClip != NULL)
                    {
                        LPVOID lp = GlobalLock(hClip);
                        if (lp != NULL)
                        {
                            LogFlowFunc(("WM_USER + 1: CF_DIB\n"));
                            vboxrc = VbglR3ClipboardWriteData(pCtx->u32ClientID, VBOX_SHARED_CLIPBOARD_FMT_BITMAP,
                                                              lp, GlobalSize(hClip));
                            GlobalUnlock(hClip);
                        }
                        else
                        {
                            hClip = NULL;
                        }
                    }
                }
                else if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT)
                {
                    hClip = GetClipboardData(CF_UNICODETEXT);

                    if (hClip != NULL)
                    {
                        LPWSTR uniString = (LPWSTR)GlobalLock(hClip);

                        if (uniString != NULL)
                        {
                            LogFlowFunc(("WM_USER + 1: CF_UNICODETEXT\n"));
                            vboxrc = VbglR3ClipboardWriteData(pCtx->u32ClientID, VBOX_SHARED_CLIPBOARD_FMT_UNICODETEXT,
                                                              uniString, (lstrlenW(uniString) + 1) * 2);
                            GlobalUnlock(hClip);
                        }
                        else
                        {
                            hClip = NULL;
                        }
                    }
                }
                else if (u32Formats & VBOX_SHARED_CLIPBOARD_FMT_HTML)
                {
                    UINT format = RegisterClipboardFormat ("HTML Format");
                    if (format != 0)
                    {
                        hClip = GetClipboardData(format);
                        if (hClip != NULL)
                        {
                            LPVOID lp = GlobalLock(hClip);

                            if (lp != NULL)
                            {
                                LogFlowFunc(("WM_USER + 1: CF_HTML\n"));
                                vboxrc = VbglR3ClipboardWriteData(pCtx->u32ClientID, VBOX_SHARED_CLIPBOARD_FMT_HTML,
                                                                  lp, GlobalSize(hClip));
                                GlobalUnlock(hClip);
                            }
                            else
                            {
                                hClip = NULL;
                            }
                        }
                    }
                }

                CloseClipboard();
            }

            if (hClip == NULL)
            {
                /* Requested clipboard format is not available, send empty data. */
                VbglR3ClipboardWriteData(pCtx->u32ClientID, 0, NULL, 0);
            }
        } break;

        default:
        {
            rc = DefWindowProc(hwnd, msg, wParam, lParam);
        }
    }

#ifndef DEBUG_andy
    LogFlowFunc(("vboxClipboardProcessMsg returned with rc = %ld\n", rc));
#endif
    return rc;
}
Exemplo n.º 28
0
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static HWND hList;
	static HWND hButton;
	switch (msg)
	{
	case WM_CREATE:
		hButton = CreateWindow(TEXT("BUTTON"), TEXT("取得"), WS_VISIBLE | WS_CHILD | WS_DISABLED, 0, 0, 0, 0, hWnd, (HMENU)IDOK, ((LPCREATESTRUCT)lParam)->hInstance, 0);
		hList = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("LISTBOX"), 0, WS_VISIBLE | WS_CHILD | WS_VSCROLL | LBS_NOINTEGRALHEIGHT | LBS_HASSTRINGS | LBS_NOTIFY, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0);
		PostMessage(hWnd, WM_COMMAND, IDOK, 0);
		break;
	case WM_SIZE:
		MoveWindow(hButton, 10, 10, 256, 32, TRUE);
		MoveWindow(hList, 10, 50, LOWORD(lParam) - 20, HIWORD(lParam) - 60, TRUE);
		break;
	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK)
		{
			EnableWindow(hButton, FALSE);
			SendMessage(hList, LB_RESETCONTENT, 0, 0);
			DWORD_PTR dwSize;
			LPBYTE lpByte = DownloadToMemory(TEXT("https://api.github.com/users/kenjinote/repos"), &dwSize);
			{
				picojson::value v;
				std::string err;
				picojson::parse(v, lpByte, lpByte + dwSize, &err);
				if (err.empty())
				{
					picojson::array arr = v.get<picojson::array>();
					for (auto v : arr)
					{
						picojson::object obj = v.get<picojson::object>();
						const INT_PTR nIndex = SendMessageA(hList, LB_ADDSTRING, 0, (LPARAM)(obj["name"].to_str().c_str()));
						std::string strCloneUrl = obj["clone_url"].to_str();
						LPSTR lpszCloneUrl = (LPSTR)GlobalAlloc(0, strCloneUrl.size() + 1);
						lstrcpyA(lpszCloneUrl, strCloneUrl.c_str());
						SendMessage(hList, LB_SETITEMDATA, nIndex, (LPARAM)lpszCloneUrl);
					}
				}
			}
			GlobalFree(lpByte);
			EnableWindow(hButton, TRUE);
		}
		else if ((HWND)lParam == hList && HIWORD(wParam) == LBN_SELCHANGE)
		{
			const INT_PTR nIndex = SendMessage(hList, LB_GETCURSEL, 0, 0);
			if (nIndex != LB_ERR)
			{
				LPSTR lpData = (LPSTR)SendMessage(hList, LB_GETITEMDATA, nIndex, 0);
				HGLOBAL hMem = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, lstrlenA(lpData) + 1);
				LPSTR lpszBuf = (LPSTR)GlobalLock(hMem);
				lstrcpyA(lpszBuf, lpData);
				GlobalUnlock(hMem);
				OpenClipboard(0);
				EmptyClipboard();
				SetClipboardData(CF_TEXT, hMem);
				CloseClipboard();
			}
		}
		break;
	case WM_DESTROY:
		{
			const INT_PTR nSize = SendMessage(hList, LB_GETCOUNT, 0, 0);
			for (int i = 0; i < nSize; ++i)
			{
				LPSTR lpData = (LPSTR)SendMessage(hList, LB_GETITEMDATA, i, 0);
				GlobalFree(lpData);
			}
		}
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, msg, wParam, lParam);
	}
	return 0;
}
Exemplo n.º 29
0
static INT_PTR CALLBACK ReadAwayMsgDlgProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	AwayMsgDlgData *dat = (AwayMsgDlgData *)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);

	switch (message) {
		case WM_INITDIALOG:
			TranslateDialogDefault(hwndDlg);
			dat = (AwayMsgDlgData *)mir_alloc(sizeof(AwayMsgDlgData));
			SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)dat);

			dat->hContact = lParam;
			dat->hSeq = (HANDLE)CallContactService(dat->hContact, PSS_GETAWAYMSG, 0, 0);
			dat->hAwayMsgEvent = dat->hSeq ? HookEventMessage(ME_PROTO_ACK, hwndDlg, HM_AWAYMSG) : NULL;
			WindowList_Add(hWindowList, hwndDlg, dat->hContact);
			{
				TCHAR str[256], format[128];
				TCHAR *contactName = (TCHAR *)pcli->pfnGetContactDisplayName(dat->hContact, 0);
				char *szProto = GetContactProto(dat->hContact);
				WORD dwStatus = db_get_w(dat->hContact, szProto, "Status", ID_STATUS_OFFLINE);
				TCHAR *status = pcli->pfnGetStatusModeDescription(dwStatus, 0);

				GetWindowText(hwndDlg, format, _countof(format));
				mir_sntprintf(str, format, status, contactName);
				SetWindowText(hwndDlg, str);
				if (dat->hSeq) {
					GetDlgItemText(hwndDlg, IDC_RETRIEVING, format, _countof(format));
					mir_sntprintf(str, format, status);
				}
				else {
					mir_sntprintf(str, TranslateT("Failed to retrieve %s message."), status);
					SetDlgItemText(hwndDlg, IDOK, TranslateT("&Close"));
				}
				SetDlgItemText(hwndDlg, IDC_RETRIEVING, str);
				SendMessage(hwndDlg, WM_SETICON, ICON_BIG, (LPARAM)Skin_LoadProtoIcon(szProto, dwStatus));
				SendMessage(hwndDlg, WM_SETICON, ICON_SMALL, (LPARAM)Skin_LoadProtoIcon(szProto, dwStatus));
				EnableWindow(GetDlgItem(hwndDlg, IDC_COPY), FALSE);
			}
			Utils_RestoreWindowPosition(hwndDlg, lParam, "SRAway", "AwayMsgDlg");
			return TRUE;

		case HM_AWAYMSG:
		{
			ACKDATA *ack = (ACKDATA *)lParam;
			if (ack->hContact != dat->hContact || ack->type != ACKTYPE_AWAYMSG)
				break;
			if (ack->result != ACKRESULT_SUCCESS)
				break;
			if (dat->hAwayMsgEvent && ack->hProcess == dat->hSeq) {
				UnhookEvent(dat->hAwayMsgEvent);
				dat->hAwayMsgEvent = NULL;
			}

			TCHAR *tszMsg = StrNormNewline((TCHAR *)ack->lParam);
			SetDlgItemText(hwndDlg, IDC_MSG, tszMsg);
			mir_free(tszMsg);

			if (ack->lParam && *((char *)ack->lParam) != '\0')
				EnableWindow(GetDlgItem(hwndDlg, IDC_COPY), TRUE);
			ShowWindow(GetDlgItem(hwndDlg, IDC_RETRIEVING), SW_HIDE);
			ShowWindow(GetDlgItem(hwndDlg, IDC_MSG), SW_SHOW);
			SetDlgItemText(hwndDlg, IDOK, TranslateT("&Close"));
			break;
		}

		case WM_COMMAND:
			switch (LOWORD(wParam)) {
				case IDCANCEL:
				case IDOK:
					DestroyWindow(hwndDlg);
					break;

				case IDC_COPY:
					if (!OpenClipboard(hwndDlg))
						break;
					if (EmptyClipboard()) {
						TCHAR msg[1024];
						int len = GetDlgItemText(hwndDlg, IDC_MSG, msg, _countof(msg));
						if (len) {
							LPTSTR lptstrCopy;
							HGLOBAL hglbCopy = GlobalAlloc(GMEM_MOVEABLE, (len + 1) * sizeof(TCHAR));
							if (hglbCopy == NULL) {
								CloseClipboard();
								break;
							}
							lptstrCopy = (LPTSTR)GlobalLock(hglbCopy);
							memcpy(lptstrCopy, msg, len * sizeof(TCHAR));
							lptstrCopy[len] = (TCHAR)0;
							GlobalUnlock(hglbCopy);

							SetClipboardData(CF_UNICODETEXT, hglbCopy);

						}
					}
					CloseClipboard();
					break;
			}
			break;

		case WM_CLOSE:
			DestroyWindow(hwndDlg);
			break;

		case WM_DESTROY:
			if (dat->hAwayMsgEvent)
				UnhookEvent(dat->hAwayMsgEvent);
			Utils_SaveWindowPosition(hwndDlg, dat->hContact, "SRAway", "AwayMsgDlg");
			WindowList_Remove(hWindowList, hwndDlg);
			IcoLib_ReleaseIcon((HICON)SendMessage(hwndDlg, WM_SETICON, ICON_BIG, NULL));
			IcoLib_ReleaseIcon((HICON)SendMessage(hwndDlg, WM_SETICON, ICON_SMALL, NULL));
			mir_free(dat);
			break;
	}
	return FALSE;
}
Exemplo n.º 30
0
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static HWND hList;
	static HFONT hFont;
	static DWORD dwSplitLine;
	switch (msg)
	{
	case WM_CREATE:
		InitCommonControls();
		hFont = CreateFont(26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, TEXT("MS ゴシック"));
		hList = CreateWindowEx(0, TEXT("LISTBOX"), 0, WS_VISIBLE | WS_CHILD | WS_VSCROLL | LBS_NOINTEGRALHEIGHT | LBS_OWNERDRAWFIXED | LBS_EXTENDEDSEL | LBS_MULTIPLESEL, 0, 0, 0, 0, hWnd, (HMENU)IDC_LIST, ((LPCREATESTRUCT)lParam)->hInstance, 0);
		SendMessage(hList, WM_SETFONT, (WPARAM)hFont, 0);
		EditDefProc = (WNDPROC)SetWindowLong(hList, GWL_WNDPROC, (LONG)ListProc);
		{
			int n;
			LPTSTR* argv = CommandLineToArgvW(GetCommandLine(), &n);
			for (int i = 1; i<n; i++)
			{
				CalcSha1(hList, argv[i]);
				const DWORD dwTempWidth = GetStringWidth(hList, PathFindFileName(argv[i]));
				if (dwTempWidth>dwSplitLine)dwSplitLine = dwTempWidth;
			}
			if (argv) GlobalFree(argv);
			const DWORD dwLastItem = SendMessage(hList, LB_GETCOUNT, 0, 0);
			SendMessage(hList, LB_SELITEMRANGE, TRUE, MAKELPARAM(0, dwLastItem - 1));
		}
		DragAcceptFiles(hWnd, TRUE);
		break;
	case WM_ERASEBKGND:
		return 1;
	case WM_COMMAND:
		switch (LOWORD(wParam))
		{
		case ID_COPYTOCLIPBOARD:
		{
			const int nSelItems = SendMessage(hList, LB_GETSELCOUNT, 0, 0);
			if (nSelItems > 0)
			{
				int* pBuffer = (int*)GlobalAlloc(0, sizeof(int) * nSelItems);
				SendMessage(hList, LB_GETSELITEMS, nSelItems, (LPARAM)pBuffer);
				INT nLen = 0;
				for (int i = 0; i < nSelItems; i++)
				{
					DATA* pData = (DATA*)SendMessage(hList, LB_GETITEMDATA, pBuffer[i], 0);
					nLen += lstrlen(pData->szFilePath);
					nLen += lstrlen(pData->szHashValue);
					nLen += 3;
				}
				HGLOBAL hMem = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, sizeof(TCHAR)*(nLen + 1));
				LPTSTR lpszBuflpszBuf = (LPTSTR)GlobalLock(hMem);
				lpszBuflpszBuf[0] = 0;
				for (int i = 0; i < nSelItems; i++)
				{
					DATA* pData = (DATA*)SendMessage(hList, LB_GETITEMDATA, pBuffer[i], 0);
					lstrcat(lpszBuflpszBuf, pData->szFilePath);
					lstrcat(lpszBuflpszBuf, TEXT("\t"));
					lstrcat(lpszBuflpszBuf, pData->szHashValue);
					lstrcat(lpszBuflpszBuf, TEXT("\r\n"));
				}
				lpszBuflpszBuf[nLen] = 0;
				GlobalFree(pBuffer);
				GlobalUnlock(hMem);
				OpenClipboard(NULL);
				EmptyClipboard();
				SetClipboardData(CF_UNICODETEXT, hMem);
				CloseClipboard();
			}
		}
		break;
		case ID_SELECTALL:
			SendMessage(hList, LB_SETSEL, 1, -1);
			break;
		case ID_DELETE:
		{
			const int nSelItems = SendMessage(hList, LB_GETSELCOUNT, 0, 0);
			if (nSelItems > 0)
			{
				int* pBuffer = (int*)GlobalAlloc(0, sizeof(int) * nSelItems);
				SendMessage(hList, LB_GETSELITEMS, nSelItems, (LPARAM)pBuffer);
				for (int i = nSelItems - 1; i >= 0; i--)
				{
					DeleteItem(hList, pBuffer[i]);
				}
				GlobalFree(pBuffer);
				dwSplitLine = 0;
				const int nCount = SendMessage(hList, LB_GETCOUNT, 0, 0);
				for (int i = 0; i < nCount; i++)
				{
					const DATA* pData = (const DATA*)SendMessage(hList, LB_GETITEMDATA, i, 0);
					const DWORD dwTemp = GetStringWidth(hList, PathFindFileName(pData->szFilePath));
					if (dwTemp>dwSplitLine)dwSplitLine = dwTemp;
				}
			}
		}
		break;
		}
		break;
	case WM_MEASUREITEM:
		((LPMEASUREITEMSTRUCT)lParam)->itemHeight = 32;
		return 0;
	case WM_SIZE:
		MoveWindow(hList, 0, 0, LOWORD(lParam), HIWORD(lParam), 0);
		break;
	case WM_EXITTHREAD:
	{
		DATA* pData = (DATA*)lParam;
		WaitForSingleObject(pData->hThread, INFINITE);
		CloseHandle(pData->hThread);
		pData->hThread = 0;
		InvalidateRect(hList, 0, 0);
	}
	break;
	case WM_DRAWITEM:
		if ((UINT)wParam == IDC_LIST)
		{
			LPDRAWITEMSTRUCT lpdis = (LPDRAWITEMSTRUCT)lParam;
			if (lpdis->itemID == -1)
			{
				if (!SendMessage(hList, LB_GETCOUNT, 0, 0))
				{
					RECT rect;
					GetClientRect(hList, &rect);
					HBRUSH hBrush = CreateSolidBrush(GetSysColor(COLOR_WINDOW));
					FillRect(lpdis->hDC, &rect, hBrush);
					DeleteObject(hBrush);
					SetTextColor(lpdis->hDC, GetSysColor(COLOR_GRAYTEXT));
					DrawText(lpdis->hDC, TEXT("ここにファイルをドラッグ"), -1, &rect, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_CENTER);
				}
				break;
			}
			DATA* pData = (DATA*)SendMessage(hList, LB_GETITEMDATA, lpdis->itemID, 0);
			if ((lpdis->itemState)&(ODS_SELECTED))
			{
				SetBkColor(lpdis->hDC, GetSysColor(COLOR_HIGHLIGHT));
				SetTextColor(lpdis->hDC, GetSysColor(COLOR_HIGHLIGHTTEXT));
			}
			else
			{
				SetBkColor(lpdis->hDC, GetSysColor(COLOR_WINDOW));
				SetTextColor(lpdis->hDC, GetSysColor(COLOR_WINDOWTEXT));
			}
			RECT rect1 = lpdis->rcItem;
			rect1.right = dwSplitLine + 16;
			const LPCTSTR lpszFileName = PathFindFileName(pData->szFilePath);
			SetTextAlign(lpdis->hDC, TA_RIGHT);
			ExtTextOut(lpdis->hDC, rect1.right, rect1.top + 4, ETO_OPAQUE, &rect1, lpszFileName, lstrlen(lpszFileName), 0);
			RECT rect2 = lpdis->rcItem;
			rect2.left = dwSplitLine + 16;
			SetTextAlign(lpdis->hDC, TA_LEFT);
			ExtTextOut(lpdis->hDC, rect2.left + 32, rect2.top + 4, ETO_OPAQUE, &rect2, pData->szHashValue, lstrlen(pData->szHashValue), 0);
		}
		break;
	case WM_DROPFILES:
	{
		HDROP hDrop = (HDROP)wParam;
		TCHAR szFileName[MAX_PATH];
		UINT i;
		const DWORD dwFastItem = SendMessage(hList, LB_GETCOUNT, 0, 0);
		SendMessage(hList, LB_SETSEL, 0, -1);
		const UINT nFiles = DragQueryFile((HDROP)hDrop, 0xFFFFFFFF, NULL, 0);
		for (i = 0; i<nFiles; i++)
		{
			DragQueryFile(hDrop, i, szFileName, sizeof(szFileName));
			CalcSha1(hList, szFileName);
			const DWORD dwTempWidth = GetStringWidth(hList, PathFindFileName(szFileName));
			if (dwTempWidth>dwSplitLine)dwSplitLine = dwTempWidth;
		}
		DragFinish(hDrop);
		const DWORD dwLastItem = SendMessage(hList, LB_GETCOUNT, 0, 0);
		SendMessage(hList, LB_SELITEMRANGE, TRUE, MAKELPARAM(dwFastItem, dwLastItem - 1));
		SetForegroundWindow(hWnd);
	}
	break;
	case WM_CLOSE:
		DestroyWindow(hWnd);
		break;
	case WM_DESTROY:
	{
		const int nCount = SendMessage(hList, LB_GETCOUNT, 0, 0);
		for (int i = nCount - 1; i >= 0; i--)
		{
			DeleteItem(hList, i);
		}
	}
	DeleteObject(hFont);
	PostQuitMessage(0);
	break;
	default:
		return DefDlgProc(hWnd, msg, wParam, lParam);
	}
	return 0;
}