コード例 #1
0
ファイル: dde.cpp プロジェクト: kxepal/miranda-ng
static LRESULT CALLBACK DdeMessageWindow(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg) {
	case WM_DDE_INITIATE:
		{
			ATOM hSzApp = LOWORD(lParam); /* no UnpackDDElParam() here */
			ATOM hSzTopic = HIWORD(lParam);
			if ((hSzApp == GlobalFindAtom(DDEAPP) && hSzTopic == GlobalFindAtom(DDETOPIC)) || !hSzApp) {
				hSzApp = GlobalAddAtom(DDEAPP);
				hSzTopic = GlobalAddAtom(DDETOPIC);
				if (hSzApp && hSzTopic)
					/* PackDDElParam() only for posted msgs */
					SendMessage((HWND)wParam, WM_DDE_ACK, (WPARAM)hwnd, MAKELPARAM(hSzApp, hSzTopic));
				if (hSzApp) GlobalDeleteAtom(hSzApp);
				if (hSzTopic) GlobalDeleteAtom(hSzTopic);
			}
		}
		return 0;

	case WM_DDE_EXECUTE: /* posted message */
		HGLOBAL hCommand;
		if (UnpackDDElParam(msg, lParam, NULL, (PUINT_PTR)&hCommand)) {
			/* ANSI execute command can't happen for shell */
			if (IsWindowUnicode((HWND)wParam)) {
				TCHAR *pszCommand = (TCHAR*)GlobalLock(hCommand);
				if (pszCommand != NULL) {
					TCHAR *pszAction = GetExecuteParam(&pszCommand);
					TCHAR *pszArg = GetExecuteParam(&pszCommand);
					if (pszArg != NULL) {
						/* we are inside miranda here, we make it async so the shell does
							* not timeout regardless what the plugins try to do. */
						if (!mir_tstrcmpi(pszAction, _T("file")))
							CallFunctionAsync(FileActionAsync, mir_tstrdup(pszArg));
						else if (!mir_tstrcmpi(pszAction, _T("url")))
							CallFunctionAsync(UrlActionAsync, mir_tstrdup(pszArg));
					}
					GlobalUnlock(hCommand);
				}
			}

			DDEACK ack;
			memset(&ack, 0, sizeof(ack));
			lParam = ReuseDDElParam(lParam, msg, WM_DDE_ACK, *(PUINT)&ack, (UINT_PTR)hCommand);
			if (!PostMessage((HWND)wParam, WM_DDE_ACK, (WPARAM)hwnd, lParam)) {
				GlobalFree(hCommand);
				FreeDDElParam(WM_DDE_ACK, lParam);
			}
		}
		return 0;

	case WM_DDE_TERMINATE:
		PostMessage((HWND)wParam, msg, (WPARAM)hwnd, 0); /* ack reply */
		return 0;

	case WM_DDE_REQUEST:
	case WM_DDE_ADVISE:
	case WM_DDE_UNADVISE:
	case WM_DDE_POKE:
		/* fail safely for those to avoid memory leak in lParam */
		{
			ATOM hSzItem;
			DDEACK ack;
			memset(&ack, 0, sizeof(ack));
			if (UnpackDDElParam(msg, lParam, NULL, (PUINT_PTR)&hSzItem)) {
				lParam = ReuseDDElParam(lParam, msg, WM_DDE_ACK, *(PUINT)&ack, (UINT)hSzItem);
				if (!PostMessage((HWND)wParam, WM_DDE_ACK, (WPARAM)hwnd, lParam)) {
					if (hSzItem) GlobalDeleteAtom(hSzItem);
					FreeDDElParam(WM_DDE_ACK, lParam);
				}
			}
			return 0;
		}
	}
	return DefWindowProc(hwnd, msg, wParam, lParam);
}
コード例 #2
0
/******************************************************************
 *		WDML_ServerHandleAdvise
 *
 *
 */
static	WDML_QUEUE_STATE WDML_ServerHandleAdvise(WDML_CONV* pConv, WDML_XACT* pXAct)
{
    UINT		uType;
    WDML_LINK*		pLink;
    DDEADVISE*		pDdeAdvise;
    HDDEDATA		hDdeData = 0;
    BOOL		fAck = TRUE;

    pDdeAdvise = GlobalLock(pXAct->hMem);
    uType = XTYP_ADVSTART |
	    (pDdeAdvise->fDeferUpd ? XTYPF_NODATA : 0) |
	    (pDdeAdvise->fAckReq ? XTYPF_ACKREQ : 0);

    if (!(pConv->instance->CBFflags & CBF_FAIL_ADVISES))
    {
	hDdeData = WDML_InvokeCallback(pConv->instance, XTYP_ADVSTART, pDdeAdvise->cfFormat,
				       (HCONV)pConv, pConv->hszTopic, pXAct->hszItem, 0, 0, 0);
    }

    switch ((ULONG_PTR)hDdeData)
    {
    case 0:
	TRACE("No data returned from the Callback\n");
	fAck = FALSE;
	break;

    case (ULONG_PTR)CBR_BLOCK:
	return WDML_QS_BLOCK;

    default:
	/* billx: first to see if the link is already created. */
	pLink = WDML_FindLink(pConv->instance, (HCONV)pConv, WDML_SERVER_SIDE,
			      pXAct->hszItem, TRUE, pDdeAdvise->cfFormat);

	if (pLink != NULL)
	{
	    /* we found a link, and only need to modify it in case it changes */
	    pLink->transactionType = uType;
	}
	else
	{
	    TRACE("Adding Link with hConv %p\n", pConv);
	    WDML_AddLink(pConv->instance, (HCONV)pConv, WDML_SERVER_SIDE,
			 uType, pXAct->hszItem, pDdeAdvise->cfFormat);
	}
	break;
    }

    GlobalUnlock(pXAct->hMem);
    if (fAck)
    {
	GlobalFree(pXAct->hMem);
    }
    pXAct->hMem = 0;

    WDML_PostAck(pConv, WDML_SERVER_SIDE, 0, FALSE, fAck, pXAct->atom, pXAct->lParam, WM_DDE_ADVISE);

    WDML_DecHSZ(pConv->instance, pXAct->hszItem);

    return WDML_QS_HANDLED;
}
コード例 #3
0
// If handle_clipboard_request() fails, its caller sends VD_AGENT_CLIPBOARD message with type
// VD_AGENT_CLIPBOARD_NONE and no data, so the client will know the request failed.
bool VDAgent::handle_clipboard_request(VDAgentClipboardRequest* clipboard_request)
{
    VDAgentMessage* msg;
    uint32_t msg_size;
    UINT format;
    HANDLE clip_data;
    uint8_t* new_data = NULL;
    long new_size = 0;
    size_t len = 0;
    CxImage image;
    VDAgentClipboard* clipboard = NULL;

    if (_clipboard_owner != owner_guest) {
        vd_printf("Received clipboard request from client while clipboard is not owned by guest");
        return false;
    }
    if (!(format = get_clipboard_format(clipboard_request->type))) {
        vd_printf("Unsupported clipboard type %u", clipboard_request->type);
        return false;
    }
    // on encoding only, we use HBITMAP to keep the correct palette
    if (format == CF_DIB) {
        format = CF_BITMAP;
    }
    if (!IsClipboardFormatAvailable(format) || !OpenClipboard(_hwnd)) {
        return false;
    }
    if (!(clip_data = GetClipboardData(format))) {
        CloseClipboard();
        return false;
    }
    switch (clipboard_request->type) {
    case VD_AGENT_CLIPBOARD_UTF8_TEXT:
        if (!(new_data = (uint8_t*)GlobalLock(clip_data))) {
            break;
        }
        len = wcslen((LPCWSTR)new_data);
        new_size = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)new_data, (int)len, NULL, 0, NULL, NULL);
        break;
    case VD_AGENT_CLIPBOARD_IMAGE_PNG:
    case VD_AGENT_CLIPBOARD_IMAGE_BMP: {
        DWORD cximage_format = get_cximage_format(clipboard_request->type);
        HPALETTE pal = 0;

        ASSERT(cximage_format);
        if (IsClipboardFormatAvailable(CF_PALETTE)) {
            pal = (HPALETTE)GetClipboardData(CF_PALETTE);
        }
        if (!image.CreateFromHBITMAP((HBITMAP)clip_data, pal)) {
            vd_printf("Image create from handle failed");
            break;
        }
        if (!image.Encode(new_data, new_size, cximage_format)) {
            vd_printf("Image encode to type %u failed", clipboard_request->type);
            break;
        }
        vd_printf("Image encoded to %lu bytes", new_size);
        break;
    }
    }

    if (!new_size) {
        vd_printf("clipboard is empty");
        goto handle_clipboard_request_fail;
    }
    if ((_max_clipboard != -1) && (new_size > _max_clipboard)) {
        vd_printf("clipboard is too large (%ld > %d), discarding",
                  new_size, _max_clipboard);
        goto handle_clipboard_request_fail;
    }

    msg_size = sizeof(VDAgentMessage) + sizeof(VDAgentClipboard) + new_size;
    msg = (VDAgentMessage*)new uint8_t[msg_size];
    msg->protocol = VD_AGENT_PROTOCOL;
    msg->type = VD_AGENT_CLIPBOARD;
    msg->opaque = 0;
    msg->size = (uint32_t)(sizeof(VDAgentClipboard) + new_size);
    clipboard = (VDAgentClipboard*)msg->data;
    clipboard->type = clipboard_request->type;

    switch (clipboard_request->type) {
    case VD_AGENT_CLIPBOARD_UTF8_TEXT:
        WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)new_data, (int)len, (LPSTR)clipboard->data,
                            new_size, NULL, NULL);
        GlobalUnlock(clip_data);
        break;
    case VD_AGENT_CLIPBOARD_IMAGE_PNG:
    case VD_AGENT_CLIPBOARD_IMAGE_BMP:
        memcpy(clipboard->data, new_data, new_size);
        image.FreeMemory(new_data);
        break;
    }
    CloseClipboard();
    write_clipboard(msg, msg_size);
    delete[] (uint8_t *)msg;
    return true;

handle_clipboard_request_fail:
    if (clipboard_request->type == VD_AGENT_CLIPBOARD_UTF8_TEXT) {
       GlobalUnlock(clip_data);
    }
    CloseClipboard();
    return false;
}
コード例 #4
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;
}
コード例 #5
0
ファイル: writer.c プロジェクト: GYGit/reactos
static void test_bom(void)
{
    static const WCHAR versionW[] = {'v','e','r','s','i','o','n','=','"','1','.','0','"',0};
    static const WCHAR utf16W[] = {'u','t','f','-','1','6',0};
    static const WCHAR xmlW[] = {'x','m','l',0};
    static const WCHAR aW[] = {'a',0};
    IXmlWriterOutput *output;
    unsigned char *ptr;
    IXmlWriter *writer;
    IStream *stream;
    HGLOBAL hglobal;
    HRESULT hr;

    hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = CreateXmlWriterOutputWithEncodingName((IUnknown*)stream, NULL, utf16W, &output);
    ok(hr == S_OK, "got %08x\n", hr);

    hr = CreateXmlWriter(&IID_IXmlWriter, (void**)&writer, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);

    hr = IXmlWriter_SetProperty(writer, XmlWriterProperty_OmitXmlDeclaration, TRUE);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = IXmlWriter_SetOutput(writer, output);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    /* BOM is on by default */
    hr = IXmlWriter_WriteStartDocument(writer, XmlStandalone_Yes);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = IXmlWriter_Flush(writer);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = GetHGlobalFromStream(stream, &hglobal);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    ptr = GlobalLock(hglobal);
    ok(ptr[0] == 0xff && ptr[1] == 0xfe, "got %x,%x\n", ptr[0], ptr[1]);
    GlobalUnlock(hglobal);

    IStream_Release(stream);
    IUnknown_Release(output);

    /* start with PI */
    hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = CreateXmlWriterOutputWithEncodingName((IUnknown*)stream, NULL, utf16W, &output);
    ok(hr == S_OK, "got %08x\n", hr);

    hr = IXmlWriter_SetOutput(writer, output);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = IXmlWriter_WriteProcessingInstruction(writer, xmlW, versionW);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = IXmlWriter_Flush(writer);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = GetHGlobalFromStream(stream, &hglobal);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    ptr = GlobalLock(hglobal);
    ok(ptr[0] == 0xff && ptr[1] == 0xfe, "got %x,%x\n", ptr[0], ptr[1]);
    GlobalUnlock(hglobal);

    IUnknown_Release(output);
    IStream_Release(stream);

    /* start with element */
    hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = CreateXmlWriterOutputWithEncodingName((IUnknown*)stream, NULL, utf16W, &output);
    ok(hr == S_OK, "got %08x\n", hr);

    hr = IXmlWriter_SetOutput(writer, output);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = IXmlWriter_WriteStartElement(writer, NULL, aW, NULL);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = IXmlWriter_Flush(writer);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = GetHGlobalFromStream(stream, &hglobal);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    ptr = GlobalLock(hglobal);
    ok(ptr[0] == 0xff && ptr[1] == 0xfe, "got %x,%x\n", ptr[0], ptr[1]);
    GlobalUnlock(hglobal);

    IUnknown_Release(output);
    IStream_Release(stream);

    /* WriteElementString */
    hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = CreateXmlWriterOutputWithEncodingName((IUnknown*)stream, NULL, utf16W, &output);
    ok(hr == S_OK, "got %08x\n", hr);

    hr = IXmlWriter_SetOutput(writer, output);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = IXmlWriter_WriteElementString(writer, NULL, aW, NULL, NULL);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = IXmlWriter_Flush(writer);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = GetHGlobalFromStream(stream, &hglobal);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    ptr = GlobalLock(hglobal);
    ok(ptr[0] == 0xff && ptr[1] == 0xfe, "got %x,%x\n", ptr[0], ptr[1]);
    GlobalUnlock(hglobal);

    IUnknown_Release(output);
    IStream_Release(stream);

    IXmlWriter_Release(writer);
}
コード例 #6
0
ファイル: nt-feature.c プロジェクト: 0xPr0xy/ImageMagick
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   I m a g e T o H B i t m a p                                               %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ImageToHBITMAP() creates a Windows HBITMAP from an image.
%
%  The format of the ImageToHBITMAP method is:
%
%      HBITMAP ImageToHBITMAP(Image *image)
%
%  A description of each parameter follows:
%
%    o image: the image to convert.
%
*/
MagickExport void *ImageToHBITMAP(Image *image)
{
  BITMAP
    bitmap;

  ExceptionInfo
    *exception;

  HANDLE
    bitmap_bitsH;

  HBITMAP
    bitmapH;

  register ssize_t
    x;

  register const PixelPacket
    *p;

  register RGBQUAD
    *q;

  RGBQUAD
    *bitmap_bits;

  size_t
    length;

  ssize_t
    y;

  (void) ResetMagickMemory(&bitmap,0,sizeof(bitmap));
  bitmap.bmType=0;
  bitmap.bmWidth=(LONG) image->columns;
  bitmap.bmHeight=(LONG) image->rows;
  bitmap.bmWidthBytes=4*bitmap.bmWidth;
  bitmap.bmPlanes=1;
  bitmap.bmBitsPixel=32;
  bitmap.bmBits=NULL;
  length=bitmap.bmWidthBytes*bitmap.bmHeight;
  bitmap_bitsH=(HANDLE) GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,length);
  if (bitmap_bitsH == NULL)
    {
      char
        *message;

      message=GetExceptionMessage(errno);
      (void) ThrowMagickException(&image->exception,GetMagickModule(),
        ResourceLimitError,"MemoryAllocationFailed","`%s'",message);
      message=DestroyString(message);
      return(NULL);
    }
  bitmap_bits=(RGBQUAD *) GlobalLock((HGLOBAL) bitmap_bitsH);
  q=bitmap_bits;
  if (bitmap.bmBits == NULL)
    bitmap.bmBits=bitmap_bits;
  (void) TransformImageColorspace(image,RGBColorspace);
  exception=(&image->exception);
  for (y=0; y < (ssize_t) image->rows; y++)
  {
    p=GetVirtualPixels(image,0,y,image->columns,1,exception);
    if (p == (const PixelPacket *) NULL)
      break;
    for (x=0; x < (ssize_t) image->columns; x++)
    {
      q->rgbRed=ScaleQuantumToChar(GetRedPixelComponent(p));
      q->rgbGreen=ScaleQuantumToChar(GetGreenPixelComponent(p));
      q->rgbBlue=ScaleQuantumToChar(GetBluePixelComponent(p));
      q->rgbReserved=0;
      p++;
      q++;
    }
  }
  bitmap.bmBits=bitmap_bits;
  bitmapH=CreateBitmapIndirect(&bitmap);
  if (bitmapH == NULL)
    {
      char
        *message;

      message=GetExceptionMessage(errno);
      (void) ThrowMagickException(&image->exception,GetMagickModule(),
        ResourceLimitError,"MemoryAllocationFailed","`%s'",message);
      message=DestroyString(message);
    }
  GlobalUnlock((HGLOBAL) bitmap_bitsH);
  GlobalFree((HGLOBAL) bitmap_bitsH);
  return((void *) bitmapH);
}
コード例 #7
0
IFACEMETHODIMP LiferayNativityContextMenus::Initialize(LPCITEMIDLIST pidlFolder, LPDATAOBJECT pDataObj, HKEY hKeyProgID)
{
	if (pDataObj)
	{
		FORMATETC fe = { CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };

		STGMEDIUM stm;

		if (FAILED(pDataObj->GetData(&fe, &stm)))
		{
			return E_INVALIDARG;
		}

		HDROP hDrop = static_cast<HDROP>(GlobalLock(stm.hGlobal));

		if (hDrop == NULL)
		{
			return E_INVALIDARG;
		}

		_nFiles = DragQueryFile(hDrop, 0xFFFFFFFF, NULL, 0);

		if (_nFiles > 0)
		{
			_contextMenuUtil = new ContextMenuUtil();
			wchar_t szFileName[MAX_PATH];

			for (UINT i = 0; i < _nFiles; i++)
			{
				UINT success = DragQueryFile(hDrop, i, szFileName, ARRAYSIZE(szFileName));

				if (success != 0)
				{
					_contextMenuUtil->AddFile(szFileName);
				}
			}
		}

		GlobalUnlock(stm.hGlobal);

		ReleaseStgMedium(&stm);
	}
	else if (pidlFolder)
	{
		wstring folderPath;

		folderPath.resize(MAX_PATH);

		if (!SHGetPathFromIDList(pidlFolder, &folderPath[0]))
		{
			return E_INVALIDARG;
		}

		_nFiles = 1;

		_contextMenuUtil = new ContextMenuUtil();

		_contextMenuUtil->AddFile(folderPath);
	}

	return S_OK;
}
コード例 #8
0
ファイル: moviemaker.cpp プロジェクト: xinyaojiejie/Dale
static HANDLE  MakeDib( HBITMAP hbitmap, UINT bits )
{
	HANDLE              hdib ;
	HDC                 hdc ;
	BITMAP              bitmap ;
	UINT                wLineLen ;
	DWORD               dwSize ;
	DWORD               wColSize ;
	LPBITMAPINFOHEADER  lpbi ;
	LPBYTE              lpBits ;
	
	GetObject(hbitmap,sizeof(BITMAP),&bitmap) ;

	//
	// DWORD align the width of the DIB
	// Figure out the size of the colour table
	// Calculate the size of the DIB
	//
	wLineLen = (bitmap.bmWidth*bits+31)/32 * 4;
	wColSize = sizeof(RGBQUAD)*((bits <= 8) ? 1<<bits : 0);
	dwSize = sizeof(BITMAPINFOHEADER) + wColSize +
		(DWORD)(UINT)wLineLen*(DWORD)(UINT)bitmap.bmHeight;

	//
	// Allocate room for a DIB and set the LPBI fields
	//
	hdib = GlobalAlloc(GHND,dwSize);
	if (!hdib)
		return hdib ;

	lpbi = (LPBITMAPINFOHEADER)GlobalLock(hdib) ;

	lpbi->biSize = sizeof(BITMAPINFOHEADER) ;
	lpbi->biWidth = bitmap.bmWidth ;
	lpbi->biHeight = bitmap.bmHeight ;
	lpbi->biPlanes = 1 ;
	lpbi->biBitCount = (WORD) bits ;
	lpbi->biCompression = BI_RGB ;
	lpbi->biSizeImage = dwSize - sizeof(BITMAPINFOHEADER) - wColSize ;
	lpbi->biXPelsPerMeter = 0 ;
	lpbi->biYPelsPerMeter = 0 ;
	lpbi->biClrUsed = (bits <= 8) ? 1<<bits : 0;
	lpbi->biClrImportant = 0 ;

	//
	// Get the bits from the bitmap and stuff them after the LPBI
	//
	lpBits = (LPBYTE)(lpbi+1)+wColSize ;

	hdc = CreateCompatibleDC(NULL) ;

	GetDIBits(hdc,hbitmap,0,bitmap.bmHeight,lpBits,(LPBITMAPINFO)lpbi, DIB_RGB_COLORS);

	// Fix this if GetDIBits messed it up....
	lpbi->biClrUsed = (bits <= 8) ? 1<<bits : 0;

	DeleteDC(hdc) ;
	GlobalUnlock(hdib);

	return hdib ;
}
コード例 #9
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;
	//}
}
コード例 #10
0
BYTE *ServerVideoManager::getPartialScreenshot(RECT r)
{
	HDC hDC = GetDC(0);
	int w=(int)((r.right - r.left)/scale_fact);
	int h=(int)((r.bottom - r.top)/scale_fact);
	HDC tmp = CreateCompatibleDC(hDC);
	HBITMAP tmp_bmp = CreateCompatibleBitmap(hDC,w,h);

	SelectObject(tmp,tmp_bmp);

	if(!StretchBlt(	tmp,
					0,0,
					w,h,
					hDC,
					r.left,
					r.top,
					r.right-r.left,
					r.bottom-r.top,
					SRCCOPY
	))
		printError(L"StretchBlt");

	POINT curPos;
	GetCursorPos(&curPos);

	if(	curPos.x>=r.left	&&	curPos.x<r.right	&&
		curPos.y>=r.top		&&	curPos.y<r.bottom)
	{
		// The cursor is inside the area; display it
		ICONINFO iconInfo;

		GetIconInfo(GetCursor(), &iconInfo);
		curPos.x -= ((int) iconInfo.xHotspot) + r.left ;
		curPos.y -= ((int) iconInfo.yHotspot) + r.top;
		
		// Draw the cursor
		DrawIconEx(	tmp,
					(int)(curPos.x/scale_fact), (int)(curPos.y/scale_fact),
					hCursor,
					0,0,
					0,NULL, DI_NORMAL);
	}


	BITMAP bmp;
	if(!GetObject(tmp_bmp,sizeof(BITMAP),&bmp))
		printError(L"GetObject");

	bytes_per_pixel=bmp.bmBitsPixel/8;
	int size=bmp.bmWidthBytes*bmp.bmHeight;

	BITMAPINFOHEADER  bi;
	bi.biSize = sizeof(BITMAPINFOHEADER);    
	bi.biWidth = w;    
	bi.biHeight = h;  
	bi.biBitCount = bmp.bmBitsPixel;    
	bi.biCompression = BI_RGB;    
	bi.biSizeImage = size; 
	bi.biPlanes = 1; 
	bi.biXPelsPerMeter = 0;    
	bi.biYPelsPerMeter = 0;    
	bi.biClrUsed = 0;    
	bi.biClrImportant = 0;

	DWORD dwBmpSize = ((bmp.bmWidth * bi.biBitCount + 31) / 32) * 4 * bmp.bmHeight;


	HANDLE hDIB = GlobalAlloc(GHND,dwBmpSize); 
	BYTE *lpbitmap = (BYTE *)GlobalLock(hDIB); 

	
	// Gets the "bits" from the bitmap and copies them into a buffer 
	// which is pointed to by lpbitmap.
	if(!GetDIBits(	hDC, tmp_bmp, 0,
					(UINT)bmp.bmHeight,
					reinterpret_cast<LPVOID>(lpbitmap),
					(BITMAPINFO *)&bi, DIB_RGB_COLORS))
		printError(L"GetDIBits");
	
	BYTE *bmp_copy=new BYTE[size];
	memcpy(bmp_copy,lpbitmap,size);
	
	GlobalUnlock(hDIB);    
	GlobalFree(hDIB);
	

	DeleteDC(tmp);
	DeleteObject(tmp_bmp);

	ReleaseDC(0,hDC);

	return bmp_copy;
}
コード例 #11
0
ファイル: ole2impl.c プロジェクト: AmesianX/RosWine
/******************************************************************************
 *              OleDuplicateData        [OLE32.@]
 *
 * Duplicates clipboard data.
 *
 * PARAMS
 *  hSrc     [I] Handle of the source clipboard data.
 *  cfFormat [I] The clipboard format of hSrc.
 *  uiFlags  [I] Flags to pass to GlobalAlloc.
 *
 * RETURNS
 *  Success: handle to the duplicated data.
 *  Failure: NULL.
 */
HANDLE WINAPI OleDuplicateData(HANDLE hSrc, CLIPFORMAT cfFormat,
	                          UINT uiFlags)
{
    HANDLE hDst = NULL;

    TRACE("(%p,%x,%x)\n", hSrc, cfFormat, uiFlags);

    if (!uiFlags) uiFlags = GMEM_MOVEABLE;

    switch (cfFormat)
    {
    case CF_ENHMETAFILE:
        hDst = CopyEnhMetaFileW(hSrc, NULL);
        break;
    case CF_METAFILEPICT:
        hDst = CopyMetaFileW(hSrc, NULL);
        break;
    case CF_PALETTE:
        {
            LOGPALETTE * logpalette;
            UINT nEntries = GetPaletteEntries(hSrc, 0, 0, NULL);
            if (!nEntries) return NULL;
            logpalette = HeapAlloc(GetProcessHeap(), 0,
                FIELD_OFFSET(LOGPALETTE, palPalEntry[nEntries]));
            if (!logpalette) return NULL;
            if (!GetPaletteEntries(hSrc, 0, nEntries, logpalette->palPalEntry))
            {
                HeapFree(GetProcessHeap(), 0, logpalette);
                return NULL;
            }
            logpalette->palVersion = 0x300;
            logpalette->palNumEntries = (WORD)nEntries;

            hDst = CreatePalette(logpalette);

            HeapFree(GetProcessHeap(), 0, logpalette);
            break;
        }
    case CF_BITMAP:
        {
            LONG size;
            BITMAP bm;
            if (!GetObjectW(hSrc, sizeof(bm), &bm))
                return NULL;
            size = GetBitmapBits(hSrc, 0, NULL);
            if (!size) return NULL;
            bm.bmBits = HeapAlloc(GetProcessHeap(), 0, size);
            if (!bm.bmBits) return NULL;
            if (GetBitmapBits(hSrc, size, bm.bmBits))
                hDst = CreateBitmapIndirect(&bm);
            HeapFree(GetProcessHeap(), 0, bm.bmBits);
            break;
        }
    default:
        {
            SIZE_T size = GlobalSize(hSrc);
            LPVOID pvSrc = NULL;
            LPVOID pvDst = NULL;

            /* allocate space for object */
            if (!size) return NULL;
            hDst = GlobalAlloc(uiFlags, size);
            if (!hDst) return NULL;

            /* lock pointers */
            pvSrc = GlobalLock(hSrc);
            if (!pvSrc)
            {
                GlobalFree(hDst);
                return NULL;
            }
            pvDst = GlobalLock(hDst);
            if (!pvDst)
            {
                GlobalUnlock(hSrc);
                GlobalFree(hDst);
                return NULL;
            }
            /* copy data */
            memcpy(pvDst, pvSrc, size);

            /* cleanup */
            GlobalUnlock(hDst);
            GlobalUnlock(hSrc);
        }
    }

    TRACE("returning %p\n", hDst);
    return hDst;
}
コード例 #12
0
STDMETHODIMP VBoxDnDDropTarget::Drop(IDataObject *pDataObject,
                                     DWORD grfKeyState, POINTL pt, DWORD *pdwEffect)
{
    AssertPtrReturn(pDataObject, E_INVALIDARG);
    AssertPtrReturn(pdwEffect, E_INVALIDARG);

#ifdef DEBUG
    LogFlowFunc(("mFormatEtc.cfFormat=%RI16 (%s), pDataObject=0x%p, grfKeyState=0x%x, x=%ld, y=%ld\n",
                 mFormatEtc.cfFormat, VBoxDnDDataObject::ClipboardFormatToString(mFormatEtc.cfFormat),
                 pDataObject, grfKeyState, pt.x, pt.y));
#endif
    HRESULT hr = S_OK;

    if (mFormatEtc.cfFormat) /* Did we get a supported format yet? */
    {
        /* Make sure the data object's data format is still the same
         * as we got it in DragEnter(). */
        hr = pDataObject->QueryGetData(&mFormatEtc);
        AssertMsg(SUCCEEDED(hr),
                  ("Data format changed between DragEnter() and Drop(), cfFormat=%RI16 (%s), hr=%Rhrc\n",
                  mFormatEtc.cfFormat, VBoxDnDDataObject::ClipboardFormatToString(mFormatEtc.cfFormat),
                  hr));
    }

    int rc = VINF_SUCCESS;

    if (SUCCEEDED(hr))
    {
        STGMEDIUM stgMed;
        hr = pDataObject->GetData(&mFormatEtc, &stgMed);
        if (SUCCEEDED(hr))
        {
            /*
             * First stage: Prepare the access to the storage medium.
             *              For now we only support HGLOBAL stuff.
             */
            PVOID pvData = NULL; /** @todo Put this in an own union? */

            switch (mFormatEtc.tymed)
            {
                case TYMED_HGLOBAL:
                    pvData = GlobalLock(stgMed.hGlobal);
                    if (!pvData)
                    {
                        LogFlowFunc(("Locking HGLOBAL storage failed with %Rrc\n",
                                     RTErrConvertFromWin32(GetLastError())));
                        rc = VERR_INVALID_HANDLE;
                        hr = E_INVALIDARG; /* Set special hr for OLE. */
                    }
                    break;

                default:
                    AssertMsgFailed(("Storage medium type %RI32 supported\n",
                                     mFormatEtc.tymed));
                    rc = VERR_NOT_SUPPORTED;
                    hr = DV_E_TYMED; /* Set special hr for OLE. */
                    break;
            }

            if (RT_SUCCESS(rc))
            {
                /* Second stage: Do the actual copying of the data object's data,
                                 based on the storage medium type. */
                switch (mFormatEtc.cfFormat)
                {
                    case CF_UNICODETEXT:
                    {
                        AssertPtr(pvData);
                        size_t cbSize = GlobalSize(pvData);
                        LogFlowFunc(("CF_UNICODETEXT 0x%p got %zu bytes\n", pvData, cbSize));
                        if (cbSize)
                        {
                            char *pszText = NULL;
                            rc = RTUtf16ToUtf8((PCRTUTF16)pvData, &pszText);
                            if (RT_SUCCESS(rc))
                            {
                                mpvData = (void *)pszText;
                                mcbData = strlen(pszText) + 1; /* Include termination. */

                                /* Note: Don't free data of pszText, mpvData now owns it. */
                            }
                        }

                        break;
                    }

                    case CF_TEXT:
                    {
                        AssertPtr(pvData);
                        size_t cbSize = GlobalSize(pvData);
                        LogFlowFunc(("CF_TEXT 0x%p got %zu bytes\n", pvData, cbSize));
                        if (cbSize)
                        {
                            char *pszText = NULL;
                            rc = RTStrCurrentCPToUtf8(&pszText, (char *)pvData);
                            if (RT_SUCCESS(rc))
                            {
                                mpvData = (void *)pszText;
                                mcbData = strlen(pszText) + 1; /* Include termination. */

                                /* Note: Don't free data of pszText, mpvData now owns it. */
                            }
                        }

                        break;
                    }

                    case CF_HDROP:
                    {
                        AssertPtr(pvData);

                        /* Convert to a string list, separated by \r\n. */
                        DROPFILES *pDropFiles = (DROPFILES *)pvData;
                        AssertPtr(pDropFiles);
                        bool fUnicode = RT_BOOL(pDropFiles->fWide);

                        /* Get the offset of the file list. */
                        Assert(pDropFiles->pFiles >= sizeof(DROPFILES));
                        /* Note: This is *not* pDropFiles->pFiles! DragQueryFile only
                         *       will work with the plain storage medium pointer! */
                        HDROP hDrop = (HDROP)(pvData);

                        /* First, get the file count. */
                        /** @todo Does this work on Windows 2000 / NT4? */
                        char *pszFiles = NULL;
                        uint32_t cchFiles = 0;
                        UINT cFiles = DragQueryFile(hDrop, UINT32_MAX /* iFile */,
                                                    NULL /* lpszFile */, 0 /* cchFile */);
                        LogFlowFunc(("CF_HDROP got %RU16 file(s)\n", cFiles));

                        for (UINT i = 0; i < cFiles; i++)
                        {
                            UINT cch = DragQueryFile(hDrop, i /* File index */,
                                                     NULL /* Query size first */,
                                                     0 /* cchFile */);
                            Assert(cch);

                            if (RT_FAILURE(rc))
                                break;

                            char *pszFile = NULL; /* UTF-8 version. */
                            UINT cchFile = 0;
                            if (fUnicode)
                            {
                                /* Allocate enough space (including terminator). */
                                WCHAR *pwszFile = (WCHAR *)RTMemAlloc((cch + 1) * sizeof(WCHAR));
                                if (pwszFile)
                                {
                                    cchFile = DragQueryFileW(hDrop, i /* File index */,
                                                             pwszFile, cch + 1 /* Include terminator */);
                                    AssertMsg(cchFile == cch, ("cchCopied (%RU16) does not match cchFile (%RU16)\n",
                                                               cchFile, cch));
                                    int rc2 = RTUtf16ToUtf8(pwszFile, &pszFile);
                                    AssertRC(rc2);
                                }
                                else
                                    rc = VERR_NO_MEMORY;
                            }
                            else /* ANSI */
                            {
                                /* Allocate enough space (including terminator). */
                                pszFile = (char *)RTMemAlloc((cch + 1) * sizeof(char));
                                if (pszFile)
                                {
                                    cchFile = DragQueryFileA(hDrop, i /* File index */,
                                                             pszFile, cchFile + 1 /* Include terminator */);
                                    AssertMsg(cchFile == cch, ("cchCopied (%RU16) does not match cchFile (%RU16)\n",
                                                               cchFile, cch));
                                }
                                else
                                    rc = VERR_NO_MEMORY;
                            }

                            if (RT_SUCCESS(rc))
                            {
                                LogFlowFunc(("\tFile: %s (cchFile=%RU32)\n",
                                             pszFile, cchFile));

                                rc = RTStrAAppendExN(&pszFiles, 1 /* cPairs */,
                                                     pszFile, cchFile);
                                if (RT_SUCCESS(rc))
                                    cchFiles += cchFile;
                            }

                            if (pszFile)
                                RTMemFree(pszFile);

                            if (RT_FAILURE(rc))
                                break;

                            /* Add separation between filenames.
                             * Note: Also do this for the last element of the list. */
                            rc = RTStrAAppendExN(&pszFiles, 1 /* cPairs */,
                                                 "\r\n", 2 /* Bytes */);
                            if (RT_SUCCESS(rc))
                                cchFiles += 2; /* Include \r\n */
                        }

                        if (RT_SUCCESS(rc))
                        {
                            cchFiles += 1; /* Add string termination. */
                            uint32_t cbFiles = cchFiles * sizeof(char);

                            LogFlowFunc(("cFiles=%u, cchFiles=%RU32, cbFiles=%RU32, pszFiles=0x%p\n",
                                         cFiles, cchFiles, cbFiles, pszFiles));

                            /* Translate the list into URI elements. */
                            DnDURIList lstURI;
                            rc = lstURI.AppendNativePathsFromList(pszFiles, cbFiles,
                                                                  DNDURILIST_FLAGS_ABSOLUTE_PATHS);
                            if (RT_SUCCESS(rc))
                            {
                                RTCString strRoot = lstURI.RootToString();
                                size_t cbRoot = strRoot.length() + 1; /* Include termination */

                                mpvData = RTMemAlloc(cbRoot);
                                if (mpvData)
                                {
                                    memcpy(mpvData, strRoot.c_str(), cbRoot);
                                    mcbData = cbRoot;
                                }
                                else
                                    rc = VERR_NO_MEMORY;
                            }
                        }

                        LogFlowFunc(("Building CF_HDROP list rc=%Rrc, pszFiles=0x%p, cFiles=%RU16, cchFiles=%RU32\n",
                                     rc, pszFiles, cFiles, cchFiles));

                        if (pszFiles)
                            RTStrFree(pszFiles);
                        break;
                    }

                    default:
                        /* Note: Should not happen due to the checks done in DragEnter(). */
                        AssertMsgFailed(("Format of type %RI16 (%s) not supported\n",
                                         mFormatEtc.cfFormat,
                                         VBoxDnDDataObject::ClipboardFormatToString(mFormatEtc.cfFormat)));
                        hr = DV_E_CLIPFORMAT; /* Set special hr for OLE. */
                        break;
                }

                /*
                 * Third stage: Unlock + release access to the storage medium again.
                 */
                switch (mFormatEtc.tymed)
                {
                    case TYMED_HGLOBAL:
                        GlobalUnlock(stgMed.hGlobal);
                        break;

                    default:
                        AssertMsgFailed(("Really should not happen -- see init stage!\n"));
                        break;
                }
            }

            /* Release storage medium again. */
            ReleaseStgMedium(&stgMed);

            /* Signal waiters. */
            mDroppedRc = rc;
            RTSemEventSignal(hEventDrop);
        }
    }

    if (RT_SUCCESS(rc))
    {
        /* Note: pt is not used since we don't need to differentiate within our
         *       proxy window. */
        *pdwEffect = VBoxDnDDropTarget::GetDropEffect(grfKeyState, *pdwEffect);
    }
    else
        *pdwEffect = DROPEFFECT_NONE;

    if (mpWndParent)
        mpWndParent->hide();

    LogFlowFunc(("Returning with hr=%Rhrc (%Rrc), mFormatEtc.cfFormat=%RI16 (%s), *pdwEffect=%RI32\n",
                 hr, rc, mFormatEtc.cfFormat, VBoxDnDDataObject::ClipboardFormatToString(mFormatEtc.cfFormat),
                 *pdwEffect));

    return hr;
}
コード例 #13
0
DVV::DVV
(
		DVD*	dvd,
		int		tx,
		int		ty
)
{
	_dwstyle = WS_OVERLAPPEDWINDOW;



	_txF = _txB = tx;
	_tyF = _tyB = ty;

			// Vu chez Frankies, Probabl Pb d'alignement .
	while (_txB%4) _txB ++;
	while (_tyB%4) _tyB ++;

//===============================
//   CREATION DE LA FENETRE
//================================

	{
		RECT r;
		r.left = 0;
		r.top = 0;
		r.right = _txF;
		r.bottom = _tyF;

			// renvoie les coordonnees de la Fenetre, y compris
			// enjolivures dans le systeme de coordonnees utilisateur
		AdjustWindowRect(&r,_dwstyle,FALSE);

		_hWnd = CreateWindow
		(
			DVD::_AppName, 
			DVD::_Elise_Name,    
            _dwstyle, 
            CW_USEDEFAULT, 
			0, 
            r.right-r.left,
			r.bottom-r.top,  
            NULL,              
            NULL,              
            dvd->_hInstance,          
            NULL               
         );
	
	}

   if ( !_hWnd ) 
      e-xit(-1);

   ShowWindow( _hWnd, dvd->_nCmdShow ); 
   UpdateWindow( _hWnd );   
   _hdc = GetDC(_hWnd);
   dvd->init_carac(_hdc);
   _nb_oct = dvd->_nb_oct_pp;

//===============================
//   CREATION DU BITMAP DE 1 LIGNE
//================================

   _last_y = -1;
   _bmi =	(BITMAPINFO *) 
			malloc 
			(
				  sizeof (BITMAPINFO)
				+ NB_COLOUR*sizeof(RGBQUAD)
				+ _txB*1*_nb_oct 
			);

	_bmi->bmiHeader.biSize = (DWORD) sizeof (BITMAPINFOHEADER) ;
	_bmi->bmiHeader.biWidth = (LONG) _txB ;
	_bmi->bmiHeader.biHeight = (LONG) 1 ; // -ny
	_bmi->bmiHeader.biPlanes = (WORD) 1 ;
	_bmi->bmiHeader.biBitCount = (WORD) (8 * _nb_oct);
	_bmi->bmiHeader.biCompression = (DWORD) BI_RGB ;
	_bmi->bmiHeader.biSizeImage = (DWORD) 0 ;
	_bmi->bmiHeader.biXPelsPerMeter = (LONG) 0 ;
	_bmi->bmiHeader.biYPelsPerMeter = (LONG) 0 ;
	_bmi->bmiHeader.biClrUsed = (LONG) NB_COLOUR ;
	_bmi->bmiHeader.biClrImportant = (LONG) NB_COLOUR ;
	
	// sans doute inutile avant de gerer les palettes, 
	// surement a modifier avec gestion des palettes,
	// surement inutile en mode 16 ou 24 bits
	/*
		{
			int x;
			for (x=0; x<128; ++x) 
			{
				_bmi->bmiColors[x] . rgbBlue = 2*x ;
				_bmi->bmiColors[x] . rgbGreen = 2*x ;
				_bmi->bmiColors[x] . rgbRed = 2*x ;
				_bmi->bmiColors[x] . rgbReserved = 0 ;
			}
		}
	*/

	int offset_im = _bmi->bmiHeader.biSize 
					+ NB_COLOUR*sizeof(RGBQUAD);

	_im =		(unsigned char*)_bmi + offset_im;
	_hbm = CreateDIBitmap
			(
				_hdc,
				(LPBITMAPINFOHEADER)_bmi,
				(DWORD)CBM_INIT,
				(LPSTR)_bmi + offset_im,
				(LPBITMAPINFO)_bmi,
				DIB_RGB_COLORS 
			);

	if (_hbm==0)
		e-xit(-1);


//================================================
//   CREATION DU DC/BITMAP          
// Copie betement dans le "Richard Simon"
// Absolument pas bite une seule ligne de ce
// charabia. Apparament ca marche.
//================================================

     _bi.biSize     = sizeof(BITMAPINFOHEADER);
     _bi.biWidth    = _txB;
     _bi.biHeight   = _tyB;
     _bi.biPlanes   = 1;
     _bi.biBitCount = 8*_nb_oct;
     _bi.biCompression   = BI_RGB;
     _bi.biSizeImage     = 0;
     _bi.biXPelsPerMeter = 0;
     _bi.biYPelsPerMeter = 0;
     _bi.biClrUsed       = 0;
     _bi.biClrImportant  = 0;

     // Create DIB.
     //............
     _hBitmap = CreateDIBitmap( _hdc, &_bi, 0L, NULL,NULL, 0 );

     // Allocate memory for BITMAPINFO structure.
     //..........................................
     _hDIB    = GlobalAlloc( GHND, 
                            sizeof( BITMAPINFOHEADER )+
                            NB_COLOUR * sizeof( RGBQUAD ) );

     _lpbi = (BITMAPINFOHEADER*)GlobalLock( _hDIB );

     // Copy bi to top of BITMAPINFO structure.
     //........................................
     *_lpbi = _bi;

     // Use GetDIBits() to init bi struct data.
     //........................................
     GetDIBits( _hdc, _hBitmap, 0, 50, NULL, 
                (LPBITMAPINFO)_lpbi, DIB_RGB_COLORS );
     GlobalUnlock( _hDIB );

     // Create a memory device context 
     // and select the DIB into it.
     //...............................
     _hMemDC = CreateCompatibleDC( _hdc );
     SelectObject( _hMemDC, _hBitmap );

	 SetProp(_hWnd,"EliseThis",this);
}
コード例 #14
0
ファイル: shellitem.c プロジェクト: Dietr1ch/wine
HRESULT WINAPI SHGetItemFromDataObject(IDataObject *pdtobj,
    DATAOBJ_GET_ITEM_FLAGS dwFlags, REFIID riid, void **ppv)
{
    FORMATETC fmt;
    STGMEDIUM medium;
    HRESULT ret;

    TRACE("%p, %x, %s, %p\n", pdtobj, dwFlags, debugstr_guid(riid), ppv);

    if(!pdtobj)
        return E_INVALIDARG;

    fmt.cfFormat = RegisterClipboardFormatW(CFSTR_SHELLIDLISTW);
    fmt.ptd = NULL;
    fmt.dwAspect = DVASPECT_CONTENT;
    fmt.lindex = -1;
    fmt.tymed = TYMED_HGLOBAL;

    ret = IDataObject_GetData(pdtobj, &fmt, &medium);
    if(SUCCEEDED(ret))
    {
        LPIDA pida = GlobalLock(medium.u.hGlobal);

        if((pida->cidl > 1 && !(dwFlags & DOGIF_ONLY_IF_ONE)) ||
           pida->cidl == 1)
        {
            LPITEMIDLIST pidl;

            /* Get the first pidl (parent + child1) */
            pidl = ILCombine((LPCITEMIDLIST) ((LPBYTE)pida+pida->aoffset[0]),
                             (LPCITEMIDLIST) ((LPBYTE)pida+pida->aoffset[1]));

            ret = SHCreateItemFromIDList(pidl, riid, ppv);
            ILFree(pidl);
        }
        else
        {
            ret = E_FAIL;
        }

        GlobalUnlock(medium.u.hGlobal);
        GlobalFree(medium.u.hGlobal);
    }

    if(FAILED(ret) && !(dwFlags & DOGIF_NO_HDROP))
    {
        TRACE("Attempting to fall back on CF_HDROP.\n");

        fmt.cfFormat = CF_HDROP;
        fmt.ptd = NULL;
        fmt.dwAspect = DVASPECT_CONTENT;
        fmt.lindex = -1;
        fmt.tymed = TYMED_HGLOBAL;

        ret = IDataObject_GetData(pdtobj, &fmt, &medium);
        if(SUCCEEDED(ret))
        {
            DROPFILES *df = GlobalLock(medium.u.hGlobal);
            LPBYTE files = (LPBYTE)df + df->pFiles;
            BOOL multiple_files = FALSE;

            ret = E_FAIL;
            if(!df->fWide)
            {
                WCHAR filename[MAX_PATH];
                PCSTR first_file = (PCSTR)files;
                if(*(files + lstrlenA(first_file) + 1) != 0)
                    multiple_files = TRUE;

                if( !(multiple_files && (dwFlags & DOGIF_ONLY_IF_ONE)) )
                {
                    MultiByteToWideChar(CP_ACP, 0, first_file, -1, filename, MAX_PATH);
                    ret = SHCreateItemFromParsingName(filename, NULL, riid, ppv);
                }
            }
            else
            {
                PCWSTR first_file = (PCWSTR)files;
                if(*((PCWSTR)files + lstrlenW(first_file) + 1) != 0)
                    multiple_files = TRUE;

                if( !(multiple_files && (dwFlags & DOGIF_ONLY_IF_ONE)) )
                    ret = SHCreateItemFromParsingName(first_file, NULL, riid, ppv);
            }

            GlobalUnlock(medium.u.hGlobal);
            GlobalFree(medium.u.hGlobal);
        }
    }

    if(FAILED(ret) && !(dwFlags & DOGIF_NO_URL))
    {
        FIXME("Failed to create item, should try CF_URL.\n");
    }

    return ret;
}
コード例 #15
0
/*!
	クリップボードのデータをいただく
	@param[in]	pdStyle	矩形かどうかを確認
	@return		確保した文字列・mallocしてるので、函数呼んだ方でfree忘れないように
*/
LPTSTR DocClipboardDataGet( PUINT pdStyle )
{
	LPTSTR	ptString = NULL, ptClipTxt;
	LPSTR	pcStr, pcClipTp;	//	変換用臨時
	DWORD	cbSize;
	UINT	ixSqrFmt, dEnumFmt;
	INT		ixCount, iC;
	HANDLE	hClipData;

	ixSqrFmt = RegisterClipboardFormat( CLIP_SQUARE );

	//	クリップボードの中身をチェキ・どっちにしてもユニコードテキストフラグはある
	if( IsClipboardFormatAvailable( CF_UNICODETEXT ) )
	{
		if( pdStyle )	//	矩形であるか
		{
			if( IsClipboardFormatAvailable( ixSqrFmt ) ){	*pdStyle = D_SQUARE;	}
		}

		OpenClipboard( NULL );	//	クリップボードをオーポンする
		//	開けっ放しだと他のアプリに迷惑なのですぐ閉めるように

		dEnumFmt = 0;	//	初期値は0
		ixCount = CountClipboardFormats(  );
		for( iC = 0; ixCount > iC; iC++ )
		{	//	順番に列挙して、先にヒットしたフォーマットで扱う
			dEnumFmt = EnumClipboardFormats( dEnumFmt );
			if( CF_UNICODETEXT == dEnumFmt || CF_TEXT == dEnumFmt ){	break;	}
		}
		if( 0 == dEnumFmt ){	return NULL;	}
		//	それ以上列挙が無いか、函数失敗なら0になる

		//	クリップボードのデータをゲッツ!
		//	ハンドルのオーナーはクリップボードなので、こちらからは操作しないように
		//	中身の変更などもってのほかである
		hClipData = GetClipboardData( dEnumFmt );

		if( CF_UNICODETEXT == dEnumFmt )
		{
			//	取得データを処理。TEXTなら、ハンドルはグローバルメモリハンドル
			//	新たにコピーされたらハンドルは無効になるので、中身をコピーせよ
			ptClipTxt = (LPTSTR)GlobalLock( hClipData );
			cbSize    = GlobalSize( (HGLOBAL)hClipData );
			//	確保出来るのはバイトサイズ・テキストだと末尾のNULLターミネータ含む

			if( 0 < cbSize )
			{
				ptString = (LPTSTR)malloc( cbSize );
				StringCchCopy( ptString, (cbSize / 2), ptClipTxt );
			}
		}
		else	//	非ユニコードが優先されている場合
		{
			pcClipTp = (LPSTR)GlobalLock( hClipData );
			cbSize   = GlobalSize( (HGLOBAL)hClipData );

			if( 0 < cbSize )
			{
				pcStr = (LPSTR)malloc( cbSize );
				StringCchCopyA( pcStr, cbSize, pcClipTp );

				ptString = SjisDecodeAlloc( pcStr );	//	SJISの内容をユニコードにする
				free( pcStr );
			}
		}


		//	使い終わったら閉じておく
		GlobalUnlock( hClipData );
		CloseClipboard(  );
	}

	return ptString;
}
コード例 #16
0
void CEditModeSelectView::OnDraw(CDC* pDC)
{
	
	CNoteEditingToolDoc* pDoc = GetDocument();
	// TODO: 여기에 그리기 코드를 추가합니다.
	
	// 더블버퍼링을 위해
	
	CDC memCDC;
	CBitmap bForMemCDC;
	CRect rect;
	// 창 크기를 받아온다.
	GetClientRect(&rect);


	bForMemCDC.DeleteObject();
	bForMemCDC.CreateCompatibleBitmap(pDC, rect.Width(), rect.Height());

	memCDC.CreateCompatibleDC(pDC);
	memCDC.SelectObject(&bForMemCDC);

	


	//Graphics graphics(pDC->m_hDC);
	Graphics graphics(memCDC.m_hDC);
		
	char noteEditingMode = pDoc->getNoteEditingMode();
	char noteWriteType = pDoc->getNoteWriteType();


	// 각각의 아이콘들을 출력 할 좌표를 저장하는 함수.
	int positionX = 0;
	int positionY = 0;


	// 배경 그리기
	HRSRC hResource = FindResource(AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDB_PNG_BACK), _T("PNG"));
	if(!hResource) return;

	DWORD imageSize = SizeofResource(AfxGetApp()->m_hInstance, hResource);
	HGLOBAL hGlobal = LoadResource(AfxGetApp()->m_hInstance, hResource);
	LPVOID pData = LockResource(hGlobal);

	HGLOBAL hBuffer = GlobalAlloc(GMEM_MOVEABLE, imageSize);
	LPVOID pBuffer = GlobalLock(hBuffer);

	CopyMemory(pBuffer,pData,imageSize);
	GlobalUnlock(hBuffer);

	IStream *pStream;
	HRESULT hr = CreateStreamOnHGlobal(hBuffer, TRUE, &pStream);

	Image imagePNG(pStream);


	pStream->Release();
	if (imagePNG.GetLastStatus() != Ok) return;

	graphics.DrawImage(&imagePNG, 0, 0, imagePNG.GetWidth(), imagePNG.GetHeight());



	
	// 현재 선택중인 위치의 음영
	hResource = FindResource(AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDB_PNG_SEL_OK), _T("PNG"));
	if(!hResource) return;
	imageSize = SizeofResource(AfxGetApp()->m_hInstance, hResource);
	hGlobal = LoadResource(AfxGetApp()->m_hInstance, hResource);
	pData = LockResource(hGlobal);
	hBuffer = GlobalAlloc(GMEM_MOVEABLE, imageSize);
	pBuffer = GlobalLock(hBuffer);
	CopyMemory(pBuffer,pData,imageSize);
	GlobalUnlock(hBuffer);
	hr = CreateStreamOnHGlobal(hBuffer, TRUE, &pStream);
	
	Image imagePNGSelOk(pStream);
	pStream->Release();
	if (imagePNGSelOk.GetLastStatus() != Ok) return;
	
	// 음영 위치를 상태에 맞게 변화시킨다.
	if ( calSelectedMenuCursor(noteWriteType, positionX, positionY) < 0 )
	{
		AfxMessageBox(_T("에러!"));
	}
	else
	{
		graphics.DrawImage(&imagePNGSelOk, positionX, positionY, imagePNGSelOk.GetWidth(), imagePNGSelOk.GetHeight());
	}


	// 현재 선택중인 편집 모드의 음영
	hResource = FindResource(AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDB_PNG_MODE_SEL), _T("PNG"));
	if(!hResource) return;
	imageSize = SizeofResource(AfxGetApp()->m_hInstance, hResource);
	hGlobal = LoadResource(AfxGetApp()->m_hInstance, hResource);
	pData = LockResource(hGlobal);
	hBuffer = GlobalAlloc(GMEM_MOVEABLE, imageSize);
	pBuffer = GlobalLock(hBuffer);
	CopyMemory(pBuffer,pData,imageSize);
	GlobalUnlock(hBuffer);
	hr = CreateStreamOnHGlobal(hBuffer, TRUE, &pStream);
	
	Image imagePNGModeSelOk(pStream);
	pStream->Release();
	if (imagePNGModeSelOk.GetLastStatus() != Ok) return;

	// 음영 위치를 상태에 맞게 변화시킨다.
	if ( calSelectedModeCursor(noteEditingMode, positionX, positionY) < 0 )
	{
		AfxMessageBox(_T("에러!"));
	}
	else
	{
		graphics.DrawImage(&imagePNGModeSelOk, positionX, positionY, imagePNGModeSelOk.GetWidth(), imagePNGModeSelOk.GetHeight());
	}


	// 현재 선택중인 재생 모드의 음영
	hResource = FindResource(AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDB_PNG_MODE_SEL), _T("PNG"));
	if(!hResource) return;
	imageSize = SizeofResource(AfxGetApp()->m_hInstance, hResource);
	hGlobal = LoadResource(AfxGetApp()->m_hInstance, hResource);
	pData = LockResource(hGlobal);
	hBuffer = GlobalAlloc(GMEM_MOVEABLE, imageSize);
	pBuffer = GlobalLock(hBuffer);
	CopyMemory(pBuffer,pData,imageSize);
	GlobalUnlock(hBuffer);
	hr = CreateStreamOnHGlobal(hBuffer, TRUE, &pStream);

	Image imagePNGPlaySelOk(pStream);
	pStream->Release();
	if (imagePNGPlaySelOk.GetLastStatus() != Ok) return;


	// 음영 위치를 상태에 맞게 변화시킨다.
	if ( calSelectedPlayCursor(pDoc->getNotePickingViewPtr()->getNowPlayingStatus(), positionX, positionY) < 0 )
	{
		// 그리지 않는다.
		//AfxMessageBox(_T("에러!"));
	}
	else
	{
		graphics.DrawImage(&imagePNGPlaySelOk, positionX, positionY, imagePNGPlaySelOk.GetWidth(), imagePNGPlaySelOk.GetHeight());
	}




	// 연필
	hResource = FindResource(AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDB_PNG_PENCIL), _T("PNG"));
	if(!hResource) return;
	imageSize = SizeofResource(AfxGetApp()->m_hInstance, hResource);
	hGlobal = LoadResource(AfxGetApp()->m_hInstance, hResource);
	pData = LockResource(hGlobal);
	hBuffer = GlobalAlloc(GMEM_MOVEABLE, imageSize);
	pBuffer = GlobalLock(hBuffer);
	CopyMemory(pBuffer,pData,imageSize);
	GlobalUnlock(hBuffer);
	hr = CreateStreamOnHGlobal(hBuffer, TRUE, &pStream);

	Image imagePNGPencil(pStream);
	pStream->Release();
	if (imagePNGPencil.GetLastStatus() != Ok) return;

	graphics.DrawImage(&imagePNGPencil, V_PENCIL_OFFSET_X, V_PENCIL_OFFSET_Y, imagePNGPencil.GetWidth(), imagePNGPencil.GetHeight());



	// 글자 넣기
	hResource = FindResource(AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDB_PNG_TEXT), _T("PNG"));
	if(!hResource) return;
	imageSize = SizeofResource(AfxGetApp()->m_hInstance, hResource);
	hGlobal = LoadResource(AfxGetApp()->m_hInstance, hResource);
	pData = LockResource(hGlobal);
	hBuffer = GlobalAlloc(GMEM_MOVEABLE, imageSize);
	pBuffer = GlobalLock(hBuffer);
	CopyMemory(pBuffer,pData,imageSize);
	GlobalUnlock(hBuffer);
	*pStream;
	hr = CreateStreamOnHGlobal(hBuffer, TRUE, &pStream);
	Image imagePNGText(pStream);

	pStream->Release();
	if (imagePNGText.GetLastStatus() != Ok) return;
	graphics.DrawImage(&imagePNGText, V_TEXT_OFFSET_X, V_TEXT_OFFSET_Y, imagePNGText.GetWidth(), imagePNGText.GetHeight());
	
	

	// 마지막에 한번에 화면 그리기
	pDC->BitBlt(0, 0, rect.Width(), rect.Height(), &memCDC, 0, 0, SRCCOPY);


}
コード例 #17
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(); 	
}
コード例 #18
0
// 
// initialization
//
STDMETHODIMP CSDShellExt::Initialize (LPCITEMIDLIST pidlFolder,	LPDATAOBJECT pDataObj, HKEY hProgID) {
    FORMATETC fmt = { CF_HDROP, NULL, DVASPECT_CONTENT,
                  -1, TYMED_HGLOBAL };
    STGMEDIUM stg = { TYMED_HGLOBAL };
    HDROP     hDrop;

    //
    // Look for CF_HDROP data in the data object. If there
    // is no such data, return an error back to Explorer.
    //
    if (FAILED(pDataObj->GetData(&fmt, &stg))) {
        return E_INVALIDARG;
    }

    //
    // check if extension is enabled
    //
    DWORD bufferSize = 4;
    DWORD keyType = REG_DWORD;
    SHGetValue(HKEY_CURRENT_USER, SecureDeleteKey, ShellNormalEnabled, &keyType, &normalEnabled, &bufferSize);
    SHGetValue(HKEY_CURRENT_USER, SecureDeleteKey, ShellMoveEnabled, &keyType, &moveEnabled, &bufferSize);
    SHGetValue(HKEY_CURRENT_USER, SecureDeleteKey, ShellRecycleEnabled, &keyType, &recycleEnabled, &bufferSize);

    if(!normalEnabled && !moveEnabled && !recycleEnabled) {
        // none of the features enabled
        return E_INVALIDARG;
    }

    //
    // reset data header
    //
    dataHeader.operationType = 0;
    dataHeader.objectCount = 0;

    //
    // get drop folder if drag-n-drop operation
    //
    if(pidlFolder != NULL && SHGetPathFromIDList(pidlFolder, dataHeader.data1)) {
        dataHeader.operationType = MOVE_OPERATION;
    }
 
    //
    // Get a pointer to the actual data.
    //
    hDrop = (HDROP)GlobalLock(stg.hGlobal);
    
    //
    // Make sure it worked.
    //
    if (hDrop == NULL) {
        return E_INVALIDARG;
    }

    //
    // get the files
    //
    unsigned int fileNumber = DragQueryFile (hDrop, 0xFFFFFFFF, NULL, 0);
    HRESULT hr = S_OK;

    if (fileNumber == 0) {
        GlobalUnlock (stg.hGlobal);
        ReleaseStgMedium (&stg);
        return E_INVALIDARG;
    }

    //
    // get the file names
    //
    wchar_t buffer[MAX_PATH];
    ClearFileList();

    for(unsigned int i = 0;i < fileNumber;i++) {
        if(DragQueryFile(hDrop, i, buffer, MAX_PATH) == 0) {
            //
            // error, abort
            //
            hr = E_INVALIDARG;
            break;
        }
            
        //
        // allocate string
        //
        int length = wcslen(buffer);
        wchar_t *name = new wchar_t[length + 1];
        wcscpy(name, buffer);

        //
        // insert into the list
        //
        fileList.insert(&name);
    }

    GlobalUnlock(stg.hGlobal);
    ReleaseStgMedium(&stg);
    return hr;
}
コード例 #19
0
ファイル: nt-feature.c プロジェクト: 0xPr0xy/ImageMagick
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   C r o p I m a g e T o H B i t m a p                                       %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  CropImageToHBITMAP() extracts a specified region of the image and returns
%  it as a Windows HBITMAP. While the same functionality can be accomplished by
%  invoking CropImage() followed by ImageToHBITMAP(), this method is more
%  efficient since it copies pixels directly to the HBITMAP.
%
%  The format of the CropImageToHBITMAP method is:
%
%      HBITMAP CropImageToHBITMAP(Image* image,const RectangleInfo *geometry,
%        ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o image: the image.
%
%    o geometry: Define the region of the image to crop with members
%      x, y, width, and height.
%
%    o exception: return any errors or warnings in this structure.
%
*/
MagickExport void *CropImageToHBITMAP(Image *image,
  const RectangleInfo *geometry,ExceptionInfo *exception)
{
#define CropImageTag  "Crop/Image"

  BITMAP
    bitmap;

  HBITMAP
    bitmapH;

  HANDLE
    bitmap_bitsH;

  MagickBooleanType
    proceed;

  RectangleInfo
    page;

  register const PixelPacket
    *p;

  register RGBQUAD
    *q;

  RGBQUAD
    *bitmap_bits;

  ssize_t
    y;

  /*
    Check crop geometry.
  */
  assert(image != (const Image *) NULL);
  assert(image->signature == MagickSignature);
  if (image->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
  assert(geometry != (const RectangleInfo *) NULL);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickSignature);
  if (((geometry->x+(ssize_t) geometry->width) < 0) ||
      ((geometry->y+(ssize_t) geometry->height) < 0) ||
      (geometry->x >= (ssize_t) image->columns) ||
      (geometry->y >= (ssize_t) image->rows))
    ThrowImageException(OptionError,"GeometryDoesNotContainImage");
  page=(*geometry);
  if ((page.x+(ssize_t) page.width) > (ssize_t) image->columns)
    page.width=image->columns-page.x;
  if ((page.y+(ssize_t) page.height) > (ssize_t) image->rows)
    page.height=image->rows-page.y;
  if (page.x < 0)
    {
      page.width+=page.x;
      page.x=0;
    }
  if (page.y < 0)
    {
      page.height+=page.y;
      page.y=0;
    }

  if ((page.width == 0) || (page.height == 0))
    ThrowImageException(OptionError,"GeometryDimensionsAreZero");
  /*
    Initialize crop image attributes.
  */
  bitmap.bmType         = 0;
  bitmap.bmWidth        = (LONG) page.width;
  bitmap.bmHeight       = (LONG) page.height;
  bitmap.bmWidthBytes   = bitmap.bmWidth * 4;
  bitmap.bmPlanes       = 1;
  bitmap.bmBitsPixel    = 32;
  bitmap.bmBits         = NULL;

  bitmap_bitsH=(HANDLE) GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,page.width*
    page.height*bitmap.bmBitsPixel);
  if (bitmap_bitsH == NULL)
    return(NULL);
  bitmap_bits=(RGBQUAD *) GlobalLock((HGLOBAL) bitmap_bitsH);
  if ( bitmap.bmBits == NULL )
    bitmap.bmBits = bitmap_bits;
  if (image->colorspace != RGBColorspace)
    TransformImageColorspace(image,RGBColorspace);
  /*
    Extract crop image.
  */
  q=bitmap_bits;
  for (y=0; y < (ssize_t) page.height; y++)
  {
    p=GetVirtualPixels(image,page.x,page.y+y,page.width,1,exception);
    if (p == (const PixelPacket *) NULL)
      break;

#if MAGICKCORE_QUANTUM_DEPTH == 8
      /* Form of PixelPacket is identical to RGBQUAD when MAGICKCORE_QUANTUM_DEPTH==8 */
      CopyMagickMemory((void*)q,(const void*)p,page.width*sizeof(PixelPacket));
      q += page.width;

#else  /* 16 or 32 bit Quantum */
      {
        ssize_t
          x;

        /* Transfer pixels, scaling to Quantum */
        for( x=(ssize_t) page.width ; x> 0 ; x-- )
          {
            q->rgbRed = ScaleQuantumToChar(GetRedPixelComponent(p));
            q->rgbGreen = ScaleQuantumToChar(GetGreenPixelComponent(p));
            q->rgbBlue = ScaleQuantumToChar(GetBluePixelComponent(p));
            q->rgbReserved = 0;
            ++q;
            ++p;
          }
      }
#endif
    proceed=SetImageProgress(image,CropImageTag,y,page.height);
    if (proceed == MagickFalse)
      break;
  }
  if (y < (ssize_t) page.height)
    {
      GlobalUnlock((HGLOBAL) bitmap_bitsH);
      GlobalFree((HGLOBAL) bitmap_bitsH);
      return((void *) NULL);
    }
  bitmap.bmBits=bitmap_bits;
  bitmapH=CreateBitmapIndirect(&bitmap);
  GlobalUnlock((HGLOBAL) bitmap_bitsH);
  GlobalFree((HGLOBAL) bitmap_bitsH);
  return((void *) bitmapH);
}
コード例 #20
0
ファイル: sdlapp.cpp プロジェクト: JickLee/Core
bool SDLApp::getClipboardText(std::string& text) {

    SDL_SysWMinfo wininfo;
    SDL_VERSION(&wininfo.version);
    SDL_GetWMInfo(&wininfo);

#if defined(_WIN32)
    if(!IsClipboardFormatAvailable(CF_TEXT) || !OpenClipboard(wininfo.window)) return false;

    HGLOBAL handle = GetClipboardData(CF_TEXT);

    if (!handle) {
        CloseClipboard();
        return false;
    }

    const char* global_str = (const char*) GlobalLock(handle);

    text.assign(global_str);

    GlobalUnlock(handle);

    CloseClipboard();

    return true;

#elif defined(USE_X11)
    Window owner;
    Atom selection;

    wininfo.info.x11.lock_func();

    owner = XGetSelectionOwner(wininfo.info.x11.display, xa_clipboard);

    wininfo.info.x11.unlock_func();

    if ( (owner == None) || (owner == wininfo.info.x11.window) ) {

        owner     = DefaultRootWindow(wininfo.info.x11.display);
        selection = XA_CUT_BUFFER0;

    } else {

        owner = wininfo.info.x11.window;

        wininfo.info.x11.lock_func();

        selection = XInternAtom(wininfo.info.x11.display, "SDL_SELECTION", False);

        XConvertSelection(wininfo.info.x11.display, xa_clipboard, XA_STRING, selection, owner, CurrentTime);

        wininfo.info.x11.unlock_func();

        int selection_response = 0;
        SDL_Event event;

        while ( !selection_response ) {
            SDL_WaitEvent(&event);

            if ( event.type == SDL_SYSWMEVENT ) {
                XEvent xevent = event.syswm.msg->event.xevent;

                if ( (xevent.type == SelectionNotify) && (xevent.xselection.requestor == owner) )
                    selection_response = 1;
            }
        }
    }

    wininfo.info.x11.lock_func();

    unsigned char *selection_data;
    unsigned long selection_length;
    unsigned long overflow;
    int selection_format;
    Atom selection_type;

    bool assigned = false;

    if ( XGetWindowProperty(wininfo.info.x11.display, owner, selection, 0, INT_MAX/4,
                            False, XA_STRING, &selection_type, &selection_format,
                       &selection_length, &overflow, &selection_data) == Success ) {

        if ( selection_type == XA_STRING ) {
            text.assign((const char*)selection_data);
            assigned = true;
        }

        XFree(selection_data);
    }

    wininfo.info.x11.unlock_func();

    return assigned;
#else
    return false;   
#endif
}
コード例 #21
0
bool vsx_widget_base_edit::event_key_down(signed long key, bool alt, bool ctrl, bool shift) {
  if (!editing_enabled) return true;
  std::vector<vsx_string>::iterator it = lines.begin();
  std::vector<int>::iterator itlv = lines_visible.begin();

  std::vector<vsx_string>::iterator itp = lines_p.begin();
  int c2 = 0;
  scroll_x = floor(scroll_x);
  vsx_string tempstring;
  vsx_string tempstring2;
  //printf("key: %d\n",key);
  if (ctrl && !alt && !shift) {
    //printf("ctrl! %d\n",key);
    switch(key) {
      case 10:
        //save();
      break;
      case 'v':
      case 'V':
#ifdef _WIN32
        HANDLE hData;

        LPVOID pData;
        char* pszData = 0;
        HWND hwnd = GetForegroundWindow();
        if (!IsClipboardFormatAvailable(CF_TEXT)) return false;
        OpenClipboard(hwnd);
        hData = GetClipboardData(CF_TEXT);
        pData = GlobalLock(hData);
        if (pszData) free(pszData);
        pszData = (char*)malloc(strlen((char*)pData) + 1);
        strcpy(pszData, (LPSTR)pData);
        vsx_string res = pszData;
        GlobalUnlock(hData);
        CloseClipboard();
        res = str_replace("\n","",res);
        process_characters = false;
        for (int i = 0; i < res.size(); ++i) {
          event_key_down(res[i],false,false,false);
        }
        free(pszData);
        process_characters = true;
        process_lines();
// copying
/*HGLOBAL hData;
    LPVOID pData;
    OpenClipboard(hwnd);
    EmptyClipboard();
    hData = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
                        strlen(pszData) + 1);
    pData = GlobalLock(hData);
    strcpy((LPSTR)pData, pszData);
    GlobalUnlock(hData);
    SetClipboardData(CF_TEXT, hData);
    CloseClipboard();*/
#endif
      break;
    }
  } else
  switch(key) {
    // arrow left
    case -GLFW_KEY_LEFT:
      --caretx;
      if (caretx < 0) {
        if (scroll_x) {
          ++caretx;
          --scroll_x;
          //fix_pos();
        } else
        if (carety) {
          --carety;
        event_key_down(-GLFW_KEY_END);
        } else caretx = 0;
      }
      break;
    // arrow right
    case -GLFW_KEY_RIGHT:
      ++caretx;
      if ((size_t)caretx > lines[carety+(int)scroll_y].size()-(int)scroll_x) {
        event_key_down(-GLFW_KEY_DOWN);
        event_key_down(-GLFW_KEY_HOME);
      }
      if (caretx > characters_width-3) {
        --caretx;
        ++scroll_x;
      }
      break;
    // arrow up
    case -GLFW_KEY_UP:
      if (!single_row) {
        --carety;
        if (carety < 0) {
          carety = 0;
          if (scroll_y) {
            --scroll_y;
            //fix_pos();
          }
        }
        if ((size_t)caretx > lines[carety+(int)scroll_y].size()-(int)scroll_x)
        event_key_down(-GLFW_KEY_END);
         //caretx = lines[carety+(int)scroll_y].size()-(int)scroll_x;
        }
      break;
    // page up
    case -GLFW_KEY_PAGEUP:
      if (!single_row) {
        for (int zz = 0; zz < characters_height*0.95; ++zz) {
        event_key_down(-GLFW_KEY_UP);
        }
      }
      break;
    // arrow down
    case -GLFW_KEY_DOWN:
      if (!single_row) {
        ++carety;
        if (carety > lines.size()-1-scroll_y) carety = (int)((float)lines.size()-1.0f-scroll_y);
        if (carety > characters_height-2) {
          ++scroll_y;
          --carety;
        }
        if ((size_t)caretx > lines[carety+(int)scroll_y].size()-(int)scroll_x)
         caretx = lines[carety+(int)scroll_y].size()-(int)scroll_x;
      }
      break;
    // page down
    case -GLFW_KEY_PAGEDOWN:
      if (!single_row) {
        for (int zz = 0; zz < characters_height*0.95; ++zz) {
        event_key_down(-GLFW_KEY_DOWN,false,false,false);
        }
      }
      break;
    // home
    case -GLFW_KEY_HOME:
      scroll_x = 0;
      caretx = 0;
      //fix_pos();
      break;
    // end
    case -GLFW_KEY_END:
      caretx = lines[carety+(int)scroll_y].size()-(int)scroll_x;
      //if (caretx < 0) caretx = 0;
      if (caretx > characters_width-3) {
        scroll_x += caretx - characters_width+3;
        //fix_pos();
        caretx = (int)characters_width-3;
      }
      if (caretx < 0) {
        scroll_x += caretx-5;//lines[carety+(int)scroll_y].size()-5;
        if (scroll_x < 0) scroll_x = 0;
        caretx = lines[carety+(int)scroll_y].size()-(int)scroll_x;
      }
      //fix_pos();
    break;
    // backspace
    case -GLFW_KEY_BACKSPACE:
      if (caretx+(int)scroll_x) {
        lines[carety+(int)scroll_y].erase(caretx-1+(int)scroll_x,1);
        --caretx;
        if (caretx < 0) {--scroll_x; ++caretx;}
        process_line(carety+(int)scroll_y);
        //fix_pos();
      } else {
        if (scroll_y+carety) {
          while (c2 < carety+scroll_y) { ++c2; ++it; ++itp; ++itlv; }
          //++it;
          tempstring = lines[carety+(int)scroll_y];
          lines.erase(it);
          lines_p.erase(itp);
          lines_visible.erase(itlv);
        event_key_down(-GLFW_KEY_UP,false,false,false);
        event_key_down(-GLFW_KEY_END,false,false,false);
          lines[carety+(int)scroll_y] += tempstring;
          lines_p[carety+(int)scroll_y] += tempstring;
          process_line(carety+(int)scroll_y);
          process_line(carety+(int)scroll_y+1);
          //fix_pos();
        }
      }
      if (mirror_keystrokes_object) mirror_keystrokes_object->event_key_down(key, alt, ctrl, shift);
    break;
    // delete
    case -GLFW_KEY_DEL:
      event_key_down(-GLFW_KEY_RIGHT,false,false,false);
      event_key_down(-GLFW_KEY_BACKSPACE,false,false,false);
      process_line(carety+(int)scroll_y);
      if (mirror_keystrokes_object) mirror_keystrokes_object->event_key_down(key, alt, ctrl, shift);
    break;
    // enter
    case -GLFW_KEY_ENTER:
      if (single_row) {
        vsx_string d;
        if (command_prefix.size()) d = command_prefix+" ";
        command_q_b.add_raw(d+lines[0]);
        parent->vsx_command_queue_b(this);
      } else {
        if ((size_t)caretx+(size_t)scroll_x > lines[carety+(int)scroll_y].size()) event_key_down(-35,false,false,false);
        while (c2 < carety+(int)scroll_y) { ++c2; ++it; ++itp; ++itlv; }
        ++it;
        ++itp;
        ++itlv;
        tempstring = lines[carety+(int)scroll_y].substr(caretx+(int)scroll_x,lines[carety+(int)scroll_y].size()-(caretx+(int)scroll_x));
        tempstring2 = lines[carety+(int)scroll_y].substr(0,caretx+(int)scroll_x);
        lines[carety+(int)scroll_y] = tempstring2;
        lines.insert(it,tempstring);
        lines_visible.insert(itlv,0);

        tempstring = lines_p[carety+(int)scroll_y].substr(caretx+(int)scroll_x,lines_p[carety+(int)scroll_y].size()-(caretx+(int)scroll_x));
        tempstring2 = lines_p[carety+(int)scroll_y].substr(0,caretx+(int)scroll_x);
        lines_p[carety+(int)scroll_y] = tempstring2;
        lines_p.insert(itp,tempstring);

        event_key_down(-GLFW_KEY_DOWN,false,false,false);
        event_key_down(-GLFW_KEY_HOME,false,false,false);
        process_line(carety-1+(int)scroll_y);
        process_line(carety+(int)scroll_y);
      }
      if (mirror_keystrokes_object) mirror_keystrokes_object->event_key_down(key, alt, ctrl, shift);
    break;
    // esc
    case -GLFW_KEY_ESC:
    // da rest:
      if (single_row) {
        command_q_b.add_raw("cancel");
        parent->vsx_command_queue_b(this);
      } else
      a_focus = k_focus = parent;
    break;
    default:
      if (key > 0) {
        if (allowed_chars.size()) {
          if (allowed_chars.find(key) == -1) {
            break;
          }
        }
        lines[carety+(int)scroll_y].insert(caretx+(int)scroll_x,(char)key);
        updates++;
        ++caretx;
        if ((size_t)caretx > lines[carety+(int)scroll_y].size()-(int)scroll_x)
        caretx = lines[carety+(int)scroll_y].size()-(int)scroll_x;
        int t_scroll_x = (int)scroll_x;
        if (caretx+(int)scroll_x > characters_width) ++scroll_x;
        //fix_pos();
        //cout << scroll_x - t_scroll_x << endl;
        caretx -= (int)scroll_x - t_scroll_x;
        process_line(carety+(int)scroll_y);
        if (mirror_keystrokes_object) mirror_keystrokes_object->event_key_down(key, alt, ctrl, shift);
      }
    // FROO
  }
  calculate_scroll_size();
  //process_lines();
  if (longest_line-characters_width <= 0) {
    scrollbar_pos_x = 0;
  } else {
    scrollbar_pos_x = (float)scroll_x/(longest_line-characters_width);
  }
  if (longest_y-characters_height <= 0) {
    scrollbar_pos_y = 0;
  } else {
    scrollbar_pos_y = (float)scroll_y/(longest_y-characters_height);
  }
  //printf("scroll_x: %f scroll_y: %f\n caretx: %d  carety: %d\n",scroll_x,scroll_y,caretx,carety);
  return false;
}
コード例 #22
0
//////////////////////////////////////////////////////////////////////////
// IDataObject
//////////////////////////////////////////////////////////////////////////
STDMETHODIMP GitDataObject::GetData(FORMATETC* pformatetcIn, STGMEDIUM* pmedium)
{
	if (!pformatetcIn)
		return E_INVALIDARG;
	if (!pmedium)
		return E_POINTER;
	pmedium->hGlobal = nullptr;

	if ((pformatetcIn->tymed & TYMED_ISTREAM) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && (pformatetcIn->cfFormat == CF_FILECONTENTS))
	{
		// supports the IStream format.
		// The lindex param is the index of the file to return
		CString filepath;
		IStream* pIStream = nullptr;

		// Note: we don't get called for directories since those are simply created and don't
		// need to be fetched.

		// Note2: It would be really nice if we could get a stream from the subversion library
		// from where we could read the file contents. But the Subversion lib is not implemented
		// to *read* from a remote stream but so that the library *writes* to a stream we pass.
		// Since we can't get such a read stream, we have to fetch the file in whole first to
		// a temp location and then pass the shell an IStream for that temp file.

		if (m_revision.IsEmpty())
		{
			if ((pformatetcIn->lindex >= 0) && (pformatetcIn->lindex < (LONG)m_allPaths.size()))
				filepath = g_Git.CombinePath(m_allPaths[pformatetcIn->lindex]);
		}
		else
		{
			filepath = CTempFiles::Instance().GetTempFilePath(true).GetWinPathString();
			if ((pformatetcIn->lindex >= 0) && (pformatetcIn->lindex < (LONG)m_allPaths.size()))
			{
				if (g_Git.GetOneFile(m_revision.ToString(), m_allPaths[pformatetcIn->lindex], filepath))
				{
					DeleteFile(filepath);
					return STG_E_ACCESSDENIED;
				}
			}
		}

		HRESULT res = SHCreateStreamOnFileEx(filepath, STGM_READ, FILE_ATTRIBUTE_NORMAL, FALSE, nullptr, &pIStream);
		if (res == S_OK)
		{
			// http://blogs.msdn.com/b/oldnewthing/archive/2014/09/18/10558763.aspx
			LARGE_INTEGER liZero = { 0, 0 };
			pIStream->Seek(liZero, STREAM_SEEK_END, nullptr);

			pmedium->pstm = pIStream;
			pmedium->tymed = TYMED_ISTREAM;
			return S_OK;
		}
		return res;
	}
	else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && (pformatetcIn->cfFormat == CF_FILEDESCRIPTOR))
	{
		for (int i = 0; i < m_gitPaths.GetCount(); ++i)
		{
			if (m_gitPaths[i].m_Action & (CTGitPath::LOGACTIONS_MISSING | CTGitPath::LOGACTIONS_DELETED) || m_gitPaths[i].IsDirectory())
				continue;
			m_allPaths.push_back(m_gitPaths[i]);
		}

		size_t dataSize = sizeof(FILEGROUPDESCRIPTOR) + ((max(1, m_allPaths.size()) - 1) * sizeof(FILEDESCRIPTOR));
		HGLOBAL data = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT, dataSize);

		FILEGROUPDESCRIPTOR* files = (FILEGROUPDESCRIPTOR*)GlobalLock(data);
		files->cItems = static_cast<UINT>(m_allPaths.size());
		int index = 0;
		for (auto it = m_allPaths.cbegin(); it != m_allPaths.cend(); ++it)
		{
			CString temp(m_iStripLength > 0 ? it->GetWinPathString().Mid(m_iStripLength + 1) : (m_iStripLength == 0 ? it->GetWinPathString() : it->GetUIFileOrDirectoryName()));
			if (temp.GetLength() < MAX_PATH)
				wcscpy_s(files->fgd[index].cFileName, (LPCTSTR)temp);
			else
			{
				files->cItems--;
				continue;
			}
			files->fgd[index].dwFlags = FD_ATTRIBUTES | FD_PROGRESSUI | FD_FILESIZE | FD_LINKUI;
			files->fgd[index].dwFileAttributes = FILE_ATTRIBUTE_NORMAL;

			// Always set the file size to 0 even if we 'know' the file size (infodata.size64).
			// Because for text files, the file size is too low due to the EOLs getting converted
			// to CRLF (from LF as stored in the repository). And a too low file size set here
			// prevents the shell from reading the full file later - it only reads the stream up
			// to the number of bytes specified here. Which means we would end up with a truncated
			// text file (binary files are still ok though).
			files->fgd[index].nFileSizeLow = 0;
			files->fgd[index].nFileSizeHigh = 0;

			++index;
		}

		GlobalUnlock(data);

		pmedium->hGlobal = data;
		pmedium->tymed = TYMED_HGLOBAL;
		return S_OK;
	}
	// handling CF_PREFERREDDROPEFFECT is necessary to tell the shell that it should *not* ask for the
	// CF_FILEDESCRIPTOR until the drop actually occurs. If we don't handle CF_PREFERREDDROPEFFECT, the shell
	// will ask for the file descriptor for every object (file/folder) the mouse pointer hovers over and is
	// a potential drop target.
	else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->cfFormat == CF_PREFERREDDROPEFFECT))
	{
		HGLOBAL data = GlobalAlloc(GMEM_MOVEABLE | GMEM_SHARE | GMEM_ZEROINIT, sizeof(DWORD));
		DWORD* effect = (DWORD*)GlobalLock(data);
		(*effect) = DROPEFFECT_COPY;
		GlobalUnlock(data);
		pmedium->hGlobal = data;
		pmedium->tymed = TYMED_HGLOBAL;
		return S_OK;
	}
	else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && (pformatetcIn->cfFormat == CF_TEXT))
	{
		// caller wants text
		// create the string from the path list
		CString text;
		if (!m_gitPaths.IsEmpty())
		{
			// create a single string where the URLs are separated by newlines
			for (int i = 0; i < m_gitPaths.GetCount(); ++i)
			{
				text += m_gitPaths[i].GetWinPathString();
				text += L"\r\n";
			}
		}
		CStringA texta = CUnicodeUtils::GetUTF8(text);
		pmedium->tymed = TYMED_HGLOBAL;
		pmedium->hGlobal = GlobalAlloc(GHND, (texta.GetLength() + 1) * sizeof(char));
		if (pmedium->hGlobal)
		{
			char* pMem = (char*)GlobalLock(pmedium->hGlobal);
			strcpy_s(pMem, texta.GetLength() + 1, (LPCSTR)texta);
			GlobalUnlock(pmedium->hGlobal);
		}
		pmedium->pUnkForRelease = nullptr;
		return S_OK;
	}
	else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && ((pformatetcIn->cfFormat == CF_UNICODETEXT) || (pformatetcIn->cfFormat == CF_INETURL) || (pformatetcIn->cfFormat == CF_SHELLURL)))
	{
		// caller wants Unicode text
		// create the string from the path list
		CString text;
		if (!m_gitPaths.IsEmpty())
		{
			// create a single string where the URLs are separated by newlines
			for (int i = 0; i < m_gitPaths.GetCount(); ++i)
			{
				if (pformatetcIn->cfFormat == CF_UNICODETEXT)
					text += m_gitPaths[i].GetWinPathString();
				else
					text += g_Git.CombinePath(m_gitPaths[i]);
				text += L"\r\n";
			}
		}
		pmedium->tymed = TYMED_HGLOBAL;
		pmedium->hGlobal = GlobalAlloc(GHND, (text.GetLength() + 1) * sizeof(TCHAR));
		if (pmedium->hGlobal)
		{
			TCHAR* pMem = (TCHAR*)GlobalLock(pmedium->hGlobal);
			wcscpy_s(pMem, text.GetLength() + 1, (LPCTSTR)text);
			GlobalUnlock(pmedium->hGlobal);
		}
		pmedium->pUnkForRelease = nullptr;
		return S_OK;
	}
	else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && (pformatetcIn->cfFormat == CF_HDROP))
	{
		int nLength = 0;

		for (int i = 0; i < m_gitPaths.GetCount(); ++i)
		{
			if (m_gitPaths[i].m_Action & (CTGitPath::LOGACTIONS_MISSING | CTGitPath::LOGACTIONS_DELETED) || m_gitPaths[i].IsDirectory())
				continue;

			nLength += g_Git.CombinePath(m_gitPaths[i]).GetLength();
			nLength += 1; // '\0' separator
		}

		int nBufferSize = sizeof(DROPFILES) + (nLength + 1) * sizeof(TCHAR);
		auto pBuffer = std::make_unique<char[]>(nBufferSize);
		SecureZeroMemory(pBuffer.get(), nBufferSize);

		DROPFILES* df = (DROPFILES*)pBuffer.get();
		df->pFiles = sizeof(DROPFILES);
		df->fWide = 1;

		TCHAR* pFilenames = (TCHAR*)(pBuffer.get() + sizeof(DROPFILES));
		TCHAR* pCurrentFilename = pFilenames;

		for (int i = 0; i < m_gitPaths.GetCount(); ++i)
		{
			if (m_gitPaths[i].m_Action & (CTGitPath::LOGACTIONS_MISSING | CTGitPath::LOGACTIONS_DELETED) || m_gitPaths[i].IsDirectory())
				continue;
			CString str = g_Git.CombinePath(m_gitPaths[i]);
			wcscpy_s(pCurrentFilename, str.GetLength() + 1, (LPCWSTR)str);
			pCurrentFilename += str.GetLength();
			*pCurrentFilename = '\0'; // separator between file names
			pCurrentFilename++;
		}
		*pCurrentFilename = '\0'; // terminate array

		pmedium->tymed = TYMED_HGLOBAL;
		pmedium->hGlobal = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE | GMEM_DDESHARE, nBufferSize);
		if (pmedium->hGlobal)
		{
			LPVOID pMem = ::GlobalLock(pmedium->hGlobal);
			if (pMem)
				memcpy(pMem, pBuffer.get(), nBufferSize);
			GlobalUnlock(pmedium->hGlobal);
		}
		pmedium->pUnkForRelease = nullptr;
		return S_OK;
	}
	else if ((pformatetcIn->tymed & TYMED_HGLOBAL) && (pformatetcIn->dwAspect == DVASPECT_CONTENT) && (pformatetcIn->cfFormat == CF_FILE_ATTRIBUTES_ARRAY))
	{
		int nBufferSize = sizeof(FILE_ATTRIBUTES_ARRAY) + m_gitPaths.GetCount() * sizeof(DWORD);
		auto pBuffer = std::make_unique<char[]>(nBufferSize);
		SecureZeroMemory(pBuffer.get(), nBufferSize);

		FILE_ATTRIBUTES_ARRAY* cf = (FILE_ATTRIBUTES_ARRAY*)pBuffer.get();
		cf->cItems = m_gitPaths.GetCount();
		cf->dwProductFileAttributes = DWORD_MAX;
		cf->dwSumFileAttributes = 0;
		for (int i = 0; i < m_gitPaths.GetCount(); ++i)
		{
			DWORD fileattribs = FILE_ATTRIBUTE_NORMAL;
			cf->rgdwFileAttributes[i] = fileattribs;
			cf->dwProductFileAttributes &= fileattribs;
			cf->dwSumFileAttributes |= fileattribs;
		}

		pmedium->tymed = TYMED_HGLOBAL;
		pmedium->hGlobal = GlobalAlloc(GMEM_ZEROINIT | GMEM_MOVEABLE | GMEM_DDESHARE, nBufferSize);
		if (pmedium->hGlobal)
		{
			LPVOID pMem = ::GlobalLock(pmedium->hGlobal);
			if (pMem)
				memcpy(pMem, pBuffer.get(), nBufferSize);
			GlobalUnlock(pmedium->hGlobal);
		}
		pmedium->pUnkForRelease = nullptr;
		return S_OK;
	}

	for (size_t i = 0; i < m_vecFormatEtc.size(); ++i)
	{
		if ((pformatetcIn->tymed == m_vecFormatEtc[i]->tymed) &&
			(pformatetcIn->dwAspect == m_vecFormatEtc[i]->dwAspect) &&
			(pformatetcIn->cfFormat == m_vecFormatEtc[i]->cfFormat))
		{
			CopyMedium(pmedium, m_vecStgMedium[i], m_vecFormatEtc[i]);
			return S_OK;
		}
	}

	return DV_E_FORMATETC;
}
コード例 #23
0
ファイル: writer.c プロジェクト: GYGit/reactos
static void test_omitxmldeclaration(void)
{
    static const char prologversion[] = "<?xml version=\"1.0\"?>";
    static const WCHAR versionW[] = {'v','e','r','s','i','o','n','=','"','1','.','0','"',0};
    static const WCHAR xmlW[] = {'x','m','l',0};
    IXmlWriter *writer;
    HGLOBAL hglobal;
    IStream *stream;
    HRESULT hr;
    char *ptr;

    hr = CreateXmlWriter(&IID_IXmlWriter, (void**)&writer, NULL);
    ok(hr == S_OK, "Expected S_OK, got %08x\n", hr);

    stream = writer_set_output(writer);

    hr = IXmlWriter_SetProperty(writer, XmlWriterProperty_OmitXmlDeclaration, TRUE);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = IXmlWriter_WriteStartDocument(writer, XmlStandalone_Yes);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = IXmlWriter_Flush(writer);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = GetHGlobalFromStream(stream, &hglobal);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    ptr = GlobalLock(hglobal);
    ok(!ptr, "got %p\n", ptr);
    GlobalUnlock(hglobal);

    /* one more time */
    hr = IXmlWriter_WriteStartDocument(writer, XmlStandalone_Yes);
    ok(hr == WR_E_INVALIDACTION, "got 0x%08x\n", hr);

    IStream_Release(stream);

    /* now add PI manually, and try to start a document */
    stream = writer_set_output(writer);

    hr = IXmlWriter_WriteProcessingInstruction(writer, xmlW, versionW);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = IXmlWriter_Flush(writer);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    CHECK_OUTPUT(stream, prologversion);

    hr = IXmlWriter_WriteStartDocument(writer, XmlStandalone_Yes);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    hr = IXmlWriter_Flush(writer);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    CHECK_OUTPUT(stream, prologversion);

    hr = IXmlWriter_WriteStartDocument(writer, XmlStandalone_Yes);
    ok(hr == WR_E_INVALIDACTION, "got 0x%08x\n", hr);

    hr = IXmlWriter_Flush(writer);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    CHECK_OUTPUT(stream, prologversion);

    /* another attempt to add 'xml' PI */
    hr = IXmlWriter_WriteProcessingInstruction(writer, xmlW, versionW);
    ok(hr == WR_E_INVALIDACTION, "got 0x%08x\n", hr);

    hr = IXmlWriter_Flush(writer);
    ok(hr == S_OK, "got 0x%08x\n", hr);

    IStream_Release(stream);
    IXmlWriter_Release(writer);
}
コード例 #24
0
ファイル: bximage.c プロジェクト: PennPanda/MIT--6.828
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;
}
コード例 #25
0
static void test_persist_save_data(const char *testname, IHlink *lnk,
                                   const unsigned char *expected_data,
                                   unsigned int expected_data_size,
                                   const unsigned char *expected_data_alt,
                                   unsigned int expected_data_alt_size)
{
    HRESULT hr;
    IStream *stream;
    IPersistStream *ps;
    HGLOBAL hglobal;
    DWORD data_size;
    const unsigned char *data;
    DWORD i;
    BOOL same;
    unsigned int expected_data_win9x_size = 0;

    hr = IHlink_QueryInterface(lnk, &IID_IPersistStream, (void **)&ps);
    ok(hr == S_OK, "IHlink_QueryInterface failed with error 0x%08x\n", hr);

    hr = CreateStreamOnHGlobal(NULL, TRUE, &stream);
    ok(hr == S_OK, "CreateStreamOnHGlobal failed with error 0x%08x\n", hr);

    hr = IPersistStream_Save(ps, stream, TRUE);
    ok(hr == S_OK, "IPersistStream_Save failed with error 0x%08x\n", hr);

    hr = GetHGlobalFromStream(stream, &hglobal);
    ok(hr == S_OK, "GetHGlobalFromStream failed with error 0x%08x\n", hr);

    data_size = GlobalSize(hglobal);

    data = GlobalLock(hglobal);

    if (expected_data_size % 4)
        expected_data_win9x_size =  4 * ((expected_data_size / 4) + 1);

    /* first check we have the right amount of data */
    ok((data_size == expected_data_size) ||
       (data_size == expected_data_alt_size) ||
       broken(data_size == expected_data_win9x_size), /* Win9x and WinMe */
       "%s: Size of saved data differs (expected %d or %d, actual %d)\n",
       testname, expected_data_size, expected_data_alt_size, data_size);

    same = TRUE;
    /* then do a byte-by-byte comparison */
    for (i = 0; i < min(data_size, expected_data_size); i++)
    {
        if ((expected_data[i] != data[i]) &&
                (((expected_data != expected_hlink_data2) &&
                  (expected_data != expected_hlink_data3)) ||
                 ((i < 52 || i >= 56) && (i < 80 || i >= 84))))
        {
            same = FALSE;
            break;
        }
    }

    if (!same && (expected_data_alt != expected_data))
    {
        /* then try the alternate data */
        same = TRUE;
        for (i = 0; i < min(data_size, expected_data_alt_size); i++)
        {
            if ((expected_data_alt[i] != data[i]) &&
                    (((expected_data_alt != expected_hlink_data2) &&
                      (expected_data_alt != expected_hlink_data3)) ||
                     ((i < 52 || i >= 56) && (i < 80 || i >= 84))))
            {
                same = FALSE;
                break;
            }
        }
    }

    ok(same, "%s: Saved data differs\n", testname);
    if (!same)
    {
        for (i = 0; i < data_size; i++)
        {
            if (i % 8 == 0) printf("    ");
            printf("0x%02x,", data[i]);
            if (i % 8 == 7) printf("\n");
        }
        printf("\n");
    }

    GlobalUnlock(hglobal);

    IStream_Release(stream);
    IPersistStream_Release(ps);
}
コード例 #26
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
}
コード例 #27
0
ファイル: CtlPanel.cpp プロジェクト: jimmccurdy/ArchiveGit
//--------------------------------------------------------------------------//
//--------------------------------------------------------------------------//
LRESULT CCtlPanel::OnPrint(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL&  bHandled)
{
	if (!m_pAGDoc)
		return true;

	AGDOCTYPE DocType = m_pAGDoc->GetDocType();
	bool bSingleFold = (DocType == DOC_CARD_SINGLEFOLD_PORTRAIT || DocType == DOC_CARD_SINGLEFOLD_LANDSCAPE);

	PRINTDLG pd;
	memset(&pd, 0, sizeof(pd));
	pd.lStructSize = sizeof(pd);
	pd.hwndOwner = GetParent();
	pd.hDevMode = m_hDevMode;
	pd.hDevNames = m_hDevNames;
	pd.hInstance = _Module.GetResourceInstance();
	pd.lCustData = (DWORD)&bSingleFold;
	pd.lpfnPrintHook = PrintHookProc;
	pd.lpPrintTemplateName = MAKEINTRESOURCE(IDD_PRINT);
	pd.Flags = PD_ENABLEPRINTTEMPLATE | PD_ENABLEPRINTHOOK;

	if (PrintDlg(&pd))
	{
		DEVNAMES* pDevNames = (DEVNAMES*)GlobalLock(pd.hDevNames);
		DEVMODE* pDevMode = (DEVMODE*)GlobalLock(pd.hDevMode);
		char* pszDriver = ((char*)pDevNames) + pDevNames->wDriverOffset;
		char* pszDevice = ((char*)pDevNames) + pDevNames->wDeviceOffset;
		char* pszOutput = ((char*)pDevNames) + pDevNames->wOutputOffset;

		int nDuplex;
		if (!GetRegistryDuplex(pszDevice, nDuplex))
			nDuplex = -1;

		if (bSingleFold && nDuplex == -1)
		{
			CDblSideIntro	Intro;
			CDblSideStep1	Step1;
			CDblSideStep2	Step2;
			CDblSideEnd 	End;

			PROPSHEETPAGE* pPropPages = new PROPSHEETPAGE[4];
			pPropPages[0] = Intro.m_psp;
			pPropPages[1] = Step1.m_psp;
			pPropPages[2] = Step2.m_psp;
			pPropPages[3] = End.m_psp;

			Intro.m_pszDriver = Step1.m_pszDriver = pszDriver;
			Intro.m_pszDevice = Step1.m_pszDevice = pszDevice;
			Intro.m_pszOutput = Step1.m_pszOutput = pszOutput;
			Intro.m_pDevMode = Step1.m_pDevMode = pDevMode;

			PROPSHEETHEADER psh;
			psh.dwSize = sizeof(PROPSHEETHEADER);
			psh.dwFlags = PSH_WIZARD | PSH_PROPSHEETPAGE;
			psh.hwndParent = GetParent();
			psh.hInstance = NULL;
			psh.hIcon = NULL;
			psh.pszCaption = NULL;
			psh.nPages = 4;
			psh.nStartPage = 0;
			psh.ppsp = pPropPages;
			psh.pfnCallback = NULL;

			::PropertySheet(&psh);
			if (End.IsFinished())
			{
				nDuplex = Step2.GetSelected();
				SetRegistryDuplex(pszDevice, nDuplex);
			}

			delete [] pPropPages;
		}

		if (!(bSingleFold && nDuplex == -1))
		{
			CWaitDlg WaitDlg;
			WaitDlg.Create(GetParent());
			WaitDlg.UpdateWindow();

			MSG msg;
			while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
			{
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}

			bool bRotated = false;
			int nCopies = pd.nCopies;
			while (nCopies-- > 0)
			{
				if (bSingleFold)
				{
					m_pAGDoc->PrintCardSingle(PRINT_OUTSIDE, pszDriver, pszDevice, pszOutput, pDevMode, bRotated);
				}
				else
				{
					m_pAGDoc->PrintCardQuarter(pszDriver, pszDevice, pszOutput, pDevMode);
				}
			}

			WaitDlg.DestroyWindow();

			if (bSingleFold)
			{
				char szFace[10];
				if (nDuplex > 2)
					lstrcpy(szFace, "UP");
				else
					lstrcpy(szFace, "DOWN");

				DWORD dwOrientation = ::DeviceCapabilities(pszDevice,
				  pszOutput, DC_ORIENTATION, NULL, pDevMode);

				bool bHorz = (DocType == DOC_CARD_SINGLEFOLD_LANDSCAPE || DocType == DOC_CARD_QUARTERFOLD_LANDSCAPE);
				if (!bHorz && dwOrientation == 270)
					bRotated = !bRotated;

				char szDirection[15];
				int nDirection = PaperDirection[nDuplex % 2][bHorz][bRotated];
				if (nDirection == 1)
					lstrcpy(szDirection, "AWAY FROM");
				else
					lstrcpy(szDirection, "TOWARD");

				char szMsg[256];
				wsprintf(szMsg, "To print the inside of your card, reinsert the page with the printed side %s\nand the front panel of the card %s the printer.\n\n\nClick OK when you are ready to print the inside.",
				  szFace, szDirection);

				if (MessageBox(szMsg, "Print inside", MB_OKCANCEL) == IDOK)
				{
					WaitDlg.Create(GetParent());
					WaitDlg.UpdateWindow();

					MSG msg;
					while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
					{
						TranslateMessage(&msg);
						DispatchMessage(&msg);
					}

					nCopies = pd.nCopies;
					while (nCopies-- > 0)
					{
						m_pAGDoc->PrintCardSingle(PRINT_INSIDE, pszDriver,
						  pszDevice, pszOutput, pDevMode, bRotated);
					}

					WaitDlg.DestroyWindow();
				}
			}
		}

		GlobalUnlock(pd.hDevNames);
		GlobalUnlock(pd.hDevMode);
	}

	m_hDevMode = pd.hDevMode;
	m_hDevNames = pd.hDevNames;

	m_pMainWnd->SetFocus();
	
	return true;
}
コード例 #28
0
int
TkSelGetSelection(
    Tcl_Interp *interp,		/* Interpreter to use for reporting errors. */
    Tk_Window tkwin,		/* Window on whose behalf to retrieve the
				 * selection (determines display from which to
				 * retrieve). */
    Atom selection,		/* Selection to retrieve. */
    Atom target,		/* Desired form in which selection is to be
				 * returned. */
    Tk_GetSelProc *proc,	/* Procedure to call to process the selection,
				 * once it has been retrieved. */
    ClientData clientData)	/* Arbitrary value to pass to proc. */
{
    char *data, *destPtr;
    Tcl_DString ds;
    HGLOBAL handle;
    Tcl_Encoding encoding;
    int result, locale;

    if ((selection != Tk_InternAtom(tkwin, "CLIPBOARD"))
	    || (target != XA_STRING)
	    || !OpenClipboard(NULL)) {
	goto error;
    }

    /*
     * Attempt to get the data in Unicode form if available as this is less
     * work that CF_TEXT.
     */

    result = TCL_ERROR;
    if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
	handle = GetClipboardData(CF_UNICODETEXT);
	if (!handle) {
	    CloseClipboard();
	    goto error;
	}
	data = GlobalLock(handle);
	Tcl_DStringInit(&ds);
	Tcl_UniCharToUtfDString((Tcl_UniChar *)data,
		Tcl_UniCharLen((Tcl_UniChar *)data), &ds);
	GlobalUnlock(handle);
    } else if (IsClipboardFormatAvailable(CF_TEXT)) {
	/*
	 * Determine the encoding to use to convert this text.
	 */

	if (IsClipboardFormatAvailable(CF_LOCALE)) {
	    handle = GetClipboardData(CF_LOCALE);
	    if (!handle) {
		CloseClipboard();
		goto error;
	    }

	    /*
	     * Get the locale identifier, determine the proper code page to
	     * use, and find the corresponding encoding.
	     */

	    Tcl_DStringInit(&ds);
	    Tcl_DStringAppend(&ds, "cp######", -1);
	    data = GlobalLock(handle);

	    /*
	     * Even though the documentation claims that GetLocaleInfo expects
	     * an LCID, on Windows 9x it really seems to expect a LanguageID.
	     */

	    locale = LANGIDFROMLCID(*((int*)data));
	    GetLocaleInfoA(locale, LOCALE_IDEFAULTANSICODEPAGE,
		    Tcl_DStringValue(&ds)+2, Tcl_DStringLength(&ds)-2);
	    GlobalUnlock(handle);

	    encoding = Tcl_GetEncoding(NULL, Tcl_DStringValue(&ds));
	    Tcl_DStringFree(&ds);
	} else {
	    encoding = NULL;
	}

	/*
	 * Fetch the text and convert it to UTF.
	 */

	handle = GetClipboardData(CF_TEXT);
	if (!handle) {
	    if (encoding) {
		Tcl_FreeEncoding(encoding);
	    }
	    CloseClipboard();
	    goto error;
	}
	data = GlobalLock(handle);
	Tcl_ExternalToUtfDString(encoding, data, -1, &ds);
	GlobalUnlock(handle);
	if (encoding) {
	    Tcl_FreeEncoding(encoding);
	}

    } else {
	CloseClipboard();
	goto error;
    }

    /*
     * Translate CR/LF to LF.
     */

    data = destPtr = Tcl_DStringValue(&ds);
    while (*data) {
	if (data[0] == '\r' && data[1] == '\n') {
	    data++;
	} else {
	    *destPtr++ = *data++;
	}
    }
    *destPtr = '\0';

    /*
     * Pass the data off to the selection procedure.
     */

    result = proc(clientData, interp, Tcl_DStringValue(&ds));
    Tcl_DStringFree(&ds);
    CloseClipboard();
    return result;

  error:
    Tcl_SetObjResult(interp, Tcl_ObjPrintf(
	    "%s selection doesn't exist or form \"%s\" not defined",
	    Tk_GetAtomName(tkwin, selection), Tk_GetAtomName(tkwin, target)));
    Tcl_SetErrorCode(interp, "TK", "SELECTION", "EXISTS", NULL);
    return TCL_ERROR;
}
コード例 #29
0
ファイル: wf_cliprdr.c プロジェクト: Alialusi/FreeRDP
static void wf_cliprdr_process_cb_data_request_event(wfContext* wfc, RDP_CB_DATA_REQUEST_EVENT* event)
{
	HANDLE hClipdata;
	int size = 0;
	char* buff = NULL;
	char* globlemem = NULL;
	UINT32 local_format;
	cliprdrContext* cliprdr = (cliprdrContext*) wfc->cliprdr_context;
	RDP_CB_DATA_RESPONSE_EVENT* response_event;

	local_format = event->format;

	if (local_format == FORMAT_ID_PALETTE)
	{
		/* TODO: implement this */
		DEBUG_CLIPRDR("FORMAT_ID_PALETTE is not supported yet.");
	}
	else if (local_format == FORMAT_ID_METAFILE)
	{
		/* TODO: implement this */
		DEBUG_CLIPRDR("FORMAT_ID_MATEFILE is not supported yet.");
	}
	else if (local_format == RegisterClipboardFormatW(L"FileGroupDescriptorW"))
	{
		HRESULT result;
		LPDATAOBJECT dataObj;
		FORMATETC format_etc;
		STGMEDIUM stg_medium;
		DROPFILES *dropFiles;

		int len;
		int i;
		wchar_t *wFileName;
		unsigned int uSize;

		DEBUG_CLIPRDR("file descriptors request.");
		result = OleGetClipboard(&dataObj);
		if (!SUCCEEDED(result))
		{
			DEBUG_CLIPRDR("OleGetClipboard failed.");
		}

		ZeroMemory(&format_etc, sizeof(FORMATETC));
		ZeroMemory(&stg_medium, sizeof(STGMEDIUM));

		/* try to get FileGroupDescriptorW struct from OLE */
		format_etc.cfFormat = local_format;
		format_etc.tymed = TYMED_HGLOBAL;
		format_etc.dwAspect = 1;
		format_etc.lindex = -1;
		format_etc.ptd = 0;

		result = IDataObject_GetData(dataObj, &format_etc, &stg_medium);
		if (SUCCEEDED(result))
		{
			DEBUG_CLIPRDR("Got FileGroupDescriptorW.");
			globlemem = (char *)GlobalLock(stg_medium.hGlobal);
			uSize = GlobalSize(stg_medium.hGlobal);
			size = uSize;
			buff = malloc(uSize);
			memcpy(buff, globlemem, uSize);
			GlobalUnlock(stg_medium.hGlobal);

			ReleaseStgMedium(&stg_medium);

			clear_file_array(cliprdr);
		}
		else
		{
			/* get DROPFILES struct from OLE */
			format_etc.cfFormat = CF_HDROP;
			format_etc.tymed = TYMED_HGLOBAL;
			format_etc.dwAspect = 1;
			format_etc.lindex = -1;

			result = IDataObject_GetData(dataObj, &format_etc, &stg_medium);
			if (!SUCCEEDED(result)) {
				DEBUG_CLIPRDR("dataObj->GetData failed.");
			}

			globlemem = (char *)GlobalLock(stg_medium.hGlobal);

			if (globlemem == NULL)
			{
				GlobalUnlock(stg_medium.hGlobal);

				ReleaseStgMedium(&stg_medium);
				cliprdr->nFiles = 0;

				goto exit;
			}
			uSize = GlobalSize(stg_medium.hGlobal);

			dropFiles = (DROPFILES *)malloc(uSize);
			memcpy(dropFiles, globlemem, uSize);

			GlobalUnlock(stg_medium.hGlobal);

			ReleaseStgMedium(&stg_medium);

			clear_file_array(cliprdr);

			if (dropFiles->fWide)
			{
				wchar_t *p;
				int str_len;
				int offset;
				int pathLen;

				/* dropFiles contains file names */
				for (wFileName = (wchar_t *)((char *)dropFiles + dropFiles->pFiles); (len = wcslen(wFileName)) > 0; wFileName += len + 1)
				{
					/* get path name */
					str_len = wcslen(wFileName);
					offset = str_len;
					/* find the last '\' in full file name */
					for (p = wFileName + offset; *p != L'\\'; p--)
					{
						;
					}
					p += 1;
					pathLen = wcslen(wFileName) - wcslen(p);

					wf_cliprdr_add_to_file_arrays(cliprdr, wFileName, pathLen);

					if ((cliprdr->fileDescriptor[cliprdr->nFiles - 1]->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
					{
						/* this is a directory */
						wf_cliprdr_traverse_directory(cliprdr, wFileName, pathLen);
					}
				}
			}
			else
			{
				char *p;
				for (p = (char *)((char *)dropFiles + dropFiles->pFiles); (len = strlen(p)) > 0; p += len + 1, cliprdr->nFiles++)
				{
					int cchWideChar;

					cchWideChar = MultiByteToWideChar(CP_ACP, MB_COMPOSITE, p, len, NULL, 0);
					cliprdr->file_names[cliprdr->nFiles] = (LPWSTR)malloc(cchWideChar);
					MultiByteToWideChar(CP_ACP, MB_COMPOSITE, p, len, cliprdr->file_names[cliprdr->nFiles], cchWideChar);

					if (cliprdr->nFiles == cliprdr->file_array_size)
					{
						cliprdr->file_array_size *= 2;
						cliprdr->fileDescriptor = (FILEDESCRIPTORW **)realloc(cliprdr->fileDescriptor, cliprdr->file_array_size * sizeof(FILEDESCRIPTORW *));
						cliprdr->file_names = (wchar_t **)realloc(cliprdr->file_names, cliprdr->file_array_size * sizeof(wchar_t *));
					}
				}
			}

exit:
			size = 4 + cliprdr->nFiles * sizeof(FILEDESCRIPTORW);
			buff = (char *)malloc(size);

			Write_UINT32(buff, cliprdr->nFiles);

			for (i = 0; i < cliprdr->nFiles; i++)
			{
				if (cliprdr->fileDescriptor[i])
				{
					memcpy(buff + 4 + i * sizeof(FILEDESCRIPTORW), cliprdr->fileDescriptor[i], sizeof(FILEDESCRIPTORW));
				}
			}
		}

		IDataObject_Release(dataObj);
	}
	else
	{
		if (!OpenClipboard(cliprdr->hwndClipboard))
		{
			DEBUG_CLIPRDR("OpenClipboard failed with 0x%x", GetLastError());
			return;
		}

		hClipdata = GetClipboardData(event->format);

		if (!hClipdata)
		{
			DEBUG_CLIPRDR("GetClipboardData failed.");
			CloseClipboard();
			return;
		}

		globlemem = (char*) GlobalLock(hClipdata);
		size = (int) GlobalSize(hClipdata);

		buff = (char*) malloc(size);
		memcpy(buff, globlemem, size);

		GlobalUnlock(hClipdata);

		CloseClipboard();
	}

	response_event = (RDP_CB_DATA_RESPONSE_EVENT*) freerdp_event_new(CliprdrChannel_Class,
			CliprdrChannel_DataResponse, NULL, NULL);

	response_event->data = (BYTE *)buff;
	response_event->size = size;

	freerdp_channels_send_event(cliprdr->channels, (wMessage*) response_event);

	/* Note: don't free buffer here. */
}
コード例 #30
0
ファイル: setup.c プロジェクト: hiinoue/psqlodbc
/*--------
 *	ConfigDSN
 *
 *	Description:	ODBC Setup entry point
 *				This entry point is called by the ODBC Installer
 *				(see file header for more details)
 *	Input	 :	hwnd ----------- Parent window handle
 *				fRequest ------- Request type (i.e., add, config, or remove)
 *				lpszDriver ----- Driver name
 *				lpszAttributes - data source attribute string
 *	Output	 :	TRUE success, FALSE otherwise
 *--------
 */
BOOL		CALLBACK
ConfigDSN(HWND hwnd,
		  WORD fRequest,
		  LPCSTR lpszDriver,
		  LPCSTR lpszAttributes)
{
	BOOL		fSuccess;		/* Success/fail flag */
	GLOBALHANDLE hglbAttr;
	LPSETUPDLG	lpsetupdlg;


	/* Allocate attribute array */
	hglbAttr = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, sizeof(SETUPDLG));
	if (!hglbAttr)
		return FALSE;
	lpsetupdlg = (LPSETUPDLG) GlobalLock(hglbAttr);
	/* Parse attribute string */
	if (lpszAttributes)
		ParseAttributes(lpszAttributes, lpsetupdlg);

	/* Save original data source name */
	if (lpsetupdlg->ci.dsn[0])
		lstrcpy(lpsetupdlg->szDSN, lpsetupdlg->ci.dsn);
	else
		lpsetupdlg->szDSN[0] = '\0';

	/* Remove data source */
	if (ODBC_REMOVE_DSN == fRequest)
	{
		/* Fail if no data source name was supplied */
		if (!lpsetupdlg->ci.dsn[0])
			fSuccess = FALSE;

		/* Otherwise remove data source from ODBC.INI */
		else
			fSuccess = SQLRemoveDSNFromIni(lpsetupdlg->ci.dsn);
	}
	/* Add or Configure data source */
	else
	{
		/* Save passed variables for global access (e.g., dialog access) */
		lpsetupdlg->hwndParent = hwnd;
		lpsetupdlg->lpszDrvr = lpszDriver;
		lpsetupdlg->fNewDSN = (ODBC_ADD_DSN == fRequest);
		lpsetupdlg->fDefault = !lstrcmpi(lpsetupdlg->ci.dsn, INI_DSN);

		/*
		 * Display the appropriate dialog (if parent window handle
		 * supplied)
		 */
		if (hwnd)
		{
			/* Display dialog(s) */
			fSuccess = (IDOK == DialogBoxParam(s_hModule,
				MAKEINTRESOURCE(DLG_CONFIG),
				hwnd,
				ConfigDlgProc,
				(LPARAM) lpsetupdlg));
		}
		else if (lpsetupdlg->ci.dsn[0])
			fSuccess = SetDSNAttributes(hwnd, lpsetupdlg, NULL);
		else
			fSuccess = FALSE;
	}

	GlobalUnlock(hglbAttr);
	GlobalFree(hglbAttr);

	return fSuccess;
}