Пример #1
0
static QClipboardData *clipboardData()
{
    if (ptrClipboardData == 0) {
        ptrClipboardData = new QClipboardData;
        // this needs to be done here to avoid recursion
        Q_ASSERT(ptrClipboardData->clipBoardViewer->testAttribute(Qt::WA_WState_Created));
        ptrClipboardData->nextClipboardViewer = SetClipboardViewer(ptrClipboardData->clipBoardViewer->internalWinId());
    }
    return ptrClipboardData;
}
Пример #2
0
void QWindowsClipboard::registerViewer()
{
    m_clipboardViewer = QWindowsContext::instance()->
        createDummyWindow(QStringLiteral("Qt5ClipboardView"), L"Qt5ClipboardView",
                          qClipboardViewerWndProc, WS_OVERLAPPED);
    m_nextClipboardViewer = SetClipboardViewer(m_clipboardViewer);

    if (QWindowsContext::verboseOLE)
        qDebug("%s m_clipboardViewer: %p next=%p", __FUNCTION__,
               m_clipboardViewer, m_nextClipboardViewer);
}
Пример #3
0
BOOL
vncDesktop::InitWindow()
{
	if (m_wndClass == 0) {
		// Create the window class
		WNDCLASSEX wndclass;

		wndclass.cbSize			= sizeof(wndclass);
		wndclass.style			= 0;
		wndclass.lpfnWndProc	= &DesktopWndProc;
		wndclass.cbClsExtra		= 0;
		wndclass.cbWndExtra		= 0;
		wndclass.hInstance		= hAppInstance;
		wndclass.hIcon			= NULL;
		wndclass.hCursor		= NULL;
		wndclass.hbrBackground	= (HBRUSH) GetStockObject(WHITE_BRUSH);
		wndclass.lpszMenuName	= (const char *) NULL;
		wndclass.lpszClassName	= szDesktopSink;
		wndclass.hIconSm		= NULL;

		// Register it
		m_wndClass = RegisterClassEx(&wndclass);
		if (!m_wndClass) {
			//vnclog.Print(LL_INTERR, VNCLOG("failed to register window class\n"));
			return FALSE;
		}
	}

	// And create a window
	m_hwnd = CreateWindow(szDesktopSink,
				"WinVNC",
				WS_OVERLAPPEDWINDOW,
				CW_USEDEFAULT,
				CW_USEDEFAULT,
				400, 200,
				NULL,
				NULL,
				hAppInstance,
				NULL);

	if (m_hwnd == NULL) {
		//vnclog.Print(LL_INTERR, VNCLOG("failed to create hook window\n"));
		return FALSE;
	}

	// Set the "this" pointer for the window
	SetWindowLong(m_hwnd, GWL_USERDATA, (long)this);

	// Enable clipboard hooking
	m_hnextviewer = SetClipboardViewer(m_hwnd);

	return TRUE;
}
JNIEXPORT jint JNICALL Java_com_iteye_weimingtom_wce_clipboard_ClipboardJNI_setClipboardViewer
  (JNIEnv *env, jclass cls, jint hWndNewViewer)
{
	HWND ret = 0; 
	ret = SetClipboardViewer((HANDLE)hWndNewViewer);
#if 0
	if (ret == NULL) 
	{
		ErrorExit("SetClipboardViewer");
	}
#endif
	return (jint)ret; 
}
Пример #5
0
BOOL CNewFile::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Add ouselves to the clipboard chain so we find out when cb changes (via WM_DRAWCLIPBOARD)
	next_cb_hwnd_ = SetClipboardViewer();

	// We have hijacked the "New File" dialog for the purpose of inserting a 
	// block filled in the same ways as the new file dialog.  The only diff.
	// to the dialog is the title (and IDC_FILL_DISK check box is hidden).
	if (insert_block_mode_)
		SetWindowText(_T("Insert Block"));

	// Check if text or binary data available from clipboard and get first bit as a sample
	check_clipboard();

	ASSERT(GetDlgItem(IDC_SPIN_SIZE_FACTOR) != NULL);
	((CSpinButtonCtrl *)GetDlgItem(IDC_SPIN_SIZE_FACTOR))->SetRange32(1, INT_MAX);

	ASSERT(GetDlgItem(IDC_SPIN_DECIMAL_SIZE) != NULL);
	((CSpinButtonCtrl *)GetDlgItem(IDC_SPIN_DECIMAL_SIZE))->SetRange32(0, INT_MAX);
	ctl_hex_size_.set_right_align();
	ctl_hex_value_.set_group_by(2);

	char buf[24];

	// Update the decimal number
	//sprintf(buf, "%I64u", (__int64(fill_.size_high)<<32) + fill_.size_low);
	sprintf(buf, "%I64u", __int64(fill_size_));
	ctl_decimal_size_.SetWindowText(buf);
	ctl_decimal_size_.add_commas();

	// Update the hex number
	//sprintf(buf, "%I64x", (__int64(fill_.size_high)<<32) + fill_.size_low);
	sprintf(buf, "%I64x", __int64(fill_size_));
	ctl_hex_size_.SetWindowText(buf);
	ctl_hex_size_.add_spaces();

	// Update the repeat count
	sprintf(buf, "%I64u", __int64(fill_repeat_));
	ctl_size_factor_.SetWindowText(buf);
	ctl_size_factor_.add_commas();

	in_update_ = FALSE;

	fix_controls();

	return TRUE;
}
Пример #6
0
/**************************************************************************
 *              ChangeClipboardChain (USER32.@)
 */
BOOL WINAPI ChangeClipboardChain(HWND hWnd, HWND hWndNext)
{
    BOOL bRet = TRUE;
    HWND hWndViewer = GetClipboardViewer();

    if (hWndViewer)
    {
        if (WIN_GetFullHandle(hWnd) == hWndViewer)
            SetClipboardViewer(WIN_GetFullHandle(hWndNext));
        else
            bRet = !SendMessageW(hWndViewer, WM_CHANGECBCHAIN, (WPARAM)hWnd, (LPARAM)hWndNext);
    }
    else
        ERR("hWndViewer is lost\n");

    return bRet;
}
Пример #7
0
	LRESULT onCreate(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
	{
		// Add the window to the clipboard viewer chain. 
		RegisterHotKey(hWnd, 1, MOD_CONTROL | MOD_ALT, VK_RETURN);
		RegisterHotKey(hWnd, 2, MOD_CONTROL | MOD_ALT, VK_UP);
		if (listener.prepare())
			listener.start();
		hwndNextViewer = SetClipboardViewer(hWnd);
		hList = CreateWindowW(L"ListBox", L"Listbox", WS_CHILD | LBS_NOTIFY,
			CW_USEDEFAULT, 0, 600, 600, hWnd, (HMENU)ID_LIST, hInst, NULL);
		
		//SendMessage(hList, LB_ADDSTRING, 0, (LPARAM)L"Text");
		//DefProc = (TDefProc)SetWindowLongPtr(hList, GWLP_WNDPROC, (LONG)&WndProc);
		ShowWindow(hList, SW_HIDE);
		//ShowWindow(hWnd, SW_HIDE);
		return 0;

	}
Пример #8
0
//*****************************************************************************
//
// @pymethod <o PyHANDLE>|win32clipboard|SetClipboardViewer|The SetClipboardViewer function
// adds the specified window to the chain of clipboard viewers. Clipboard
// viewer windows receive a WM_DRAWCLIPBOARD message whenever the content of
// the clipboard changes.
// @rdesc   Returns a handle to the next window in chain, or None if no other viewer exists.
static PyObject *
py_set_clipboard_viewer(PyObject* self, PyObject* args)
{

  // @pyparm <o PyHANDLE>|hWndNewViewer||Integer handle to the window to be added to
  // the clipboard chain.
  HWND hWndNewViewer;
  PyObject *obhwnd;
  if (!PyArg_ParseTuple(args, "O:SetClipboardViewer", &obhwnd))
    return NULL;
  if (!PyWinObject_AsHANDLE(obhwnd, (HANDLE *)&hWndNewViewer))
	  return NULL;
  HWND rc;
  Py_BEGIN_ALLOW_THREADS;
  rc = SetClipboardViewer(hWndNewViewer);
  Py_END_ALLOW_THREADS;

  // Function can return NULL on success if there is no other viewer
  if (rc!=NULL)
    return PyWinLong_FromHANDLE(rc);
  DWORD e=GetLastError();
  if (e)
    return PyWin_SetAPIError("SetClipboardViewer",e);
  Py_INCREF(Py_None);
  return Py_None;

  // @comm The windows that are part of the clipboard viewer chain, called
  // clipboard viewer windows, must process the clipboard messages
  // WM_CHANGECBCHAIN and WM_DRAWCLIPBOARD. Each clipboard viewer window calls
  // the SendMessage function to pass these messages to the next window in the
  // clipboard viewer chain.<nl>
  // A clipboard viewer window must eventually remove itself from the clipboard
  // viewer chain by calling the ChangeClipboardChain function -- for example,
  // in response to theWM_DESTROY message. 

  // @pyseeapi SetClipboardViewer

  // @rdesc If the function succeeds, the return value identifies the next
  // window in the clipboard viewer chain.<nl>
  // If an error occurs or there are no other windows in the clipboard viewer
  // chain, win32api.error is raised with the GetLastError info.

}
Пример #9
0
void QWindowsClipboard::registerViewer()
{
    m_clipboardViewer = QWindowsContext::instance()->
        createDummyWindow(QStringLiteral("Qt5ClipboardView"), L"Qt5ClipboardView",
                          qClipboardViewerWndProc, WS_OVERLAPPED);

    // Try format listener API (Vista onwards) first.
    if (QWindowsContext::user32dll.addClipboardFormatListener && QWindowsContext::user32dll.removeClipboardFormatListener) {
        m_formatListenerRegistered = QWindowsContext::user32dll.addClipboardFormatListener(m_clipboardViewer);
        if (!m_formatListenerRegistered)
            qErrnoWarning("AddClipboardFormatListener() failed.");
    }

    if (!m_formatListenerRegistered)
        m_nextClipboardViewer = SetClipboardViewer(m_clipboardViewer);

    qCDebug(lcQpaMime) << __FUNCTION__ << "m_clipboardViewer:" << m_clipboardViewer
        << "format listener:" << m_formatListenerRegistered
        << "next:" << m_nextClipboardViewer;
}
Пример #10
0
/*
 * Creates a hidden window and adds it to the clipboard chain
 */
static gboolean
register_clipboard_notification (GdkDisplay *display)
{
  GdkWin32Display *display_win32 = GDK_WIN32_DISPLAY (display);
  WNDCLASS wclass = { 0, };
  ATOM klass;

  wclass.lpszClassName = "GdkClipboardNotification";
  wclass.lpfnWndProc = _clipboard_window_procedure;
  wclass.hInstance = _gdk_app_hmodule;

  klass = RegisterClass (&wclass);
  if (!klass)
    return FALSE;

  display_win32->clipboard_hwnd = CreateWindow (MAKEINTRESOURCE (klass),
                                                NULL, WS_POPUP,
                                                0, 0, 0, 0, NULL, NULL,
                                                _gdk_app_hmodule, NULL);

  if (display_win32->clipboard_hwnd == NULL)
    goto failed;

  SetLastError (0);
  _hwnd_next_viewer = SetClipboardViewer (display_win32->clipboard_hwnd);

  if (_hwnd_next_viewer == NULL && GetLastError() != 0)
    goto failed;

  /* FIXME: http://msdn.microsoft.com/en-us/library/ms649033(v=VS.85).aspx */
  /* This is only supported by Vista, and not yet by mingw64 */
  /* if (AddClipboardFormatListener (hwnd) == FALSE) */
  /*   goto failed; */

  return TRUE;

failed:
  g_critical ("Failed to install clipboard viewer");
  UnregisterClass (MAKEINTRESOURCE (klass), _gdk_app_hmodule);
  return FALSE;
}
Пример #11
0
void fsClipboardCatchMgr::Enable(BOOL bEnable)
{
	

	if (bEnable)
	{
		if (m_bEnabled == FALSE)
		{
			m_hNextViewer = SetClipboardViewer ();
			m_bEnabled = TRUE;
		}
	}
	else
	{
		if (m_bEnabled)
		{
			ChangeClipboardChain (m_hNextViewer);
			m_bEnabled = FALSE;
		}
	}
}
Пример #12
0
BOOL COpenDlg::OnInitDialog()
{
	CStandAloneDialog::OnInitDialog();

	CRegDWORD lastRadioButton(L"Software\\TortoiseGitMerge\\OpenRadio", IDC_MERGERADIO);
	if (((DWORD)lastRadioButton != IDC_MERGERADIO)&&((DWORD)lastRadioButton != IDC_APPLYRADIO))
		lastRadioButton = IDC_MERGERADIO;
	GroupRadio((DWORD)lastRadioButton);
	CheckRadioButton(IDC_MERGERADIO, IDC_APPLYRADIO, (DWORD)lastRadioButton);

	// turn on auto completion for the edit controls
	AutoCompleteOn(IDC_BASEFILEEDIT);
	AutoCompleteOn(IDC_THEIRFILEEDIT);
	AutoCompleteOn(IDC_YOURFILEEDIT);
	AutoCompleteOn(IDC_DIFFFILEEDIT);
	AutoCompleteOn(IDC_DIRECTORYEDIT);

	m_cFormat = RegisterClipboardFormat(L"TGIT_UNIFIEDDIFF");
	m_nextViewer = SetClipboardViewer();

	return TRUE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}
Пример #13
0
/* Add ourselves into the chain of cliboard listeners */
static void addToCBChain (VBOXCLIPBOARDCONTEXT *pCtx)
{
    pCtx->hwndNextInChain = SetClipboardViewer (pCtx->hwnd);
}
/* ************************************
* MainWndProc
* 窗口消息处理函数
**************************************/
LRESULT CALLBACK MainWndProc(
							 HWND hwnd,
							 UINT uMsg,
							 WPARAM wParam,
							 LPARAM lParam)
{
	static HWND hwndNextViewer;

	HDC hdc;
	HDC hdcMem;
	PAINTSTRUCT ps;
	LPPAINTSTRUCT lpps;
	RECT rc;
	LPRECT lprc;
	HGLOBAL hglb;
	LPSTR lpstr;
	HBITMAP hbm;
	HENHMETAFILE hemf;
	HWND hwndOwner;

	switch (uMsg)
	{
	case WM_PAINT: // 收到WM_PAINT消息后显示粘贴板中的数据
		hdc = BeginPaint(hwnd, &ps);
		// uForamt全局变量,在WM_DRAWCLIPBOARD和WM_COMMAND
		// 消息处理中,使用SetAutoView设置
		// 根据粘贴板中数据的不同格式,使用不同的显示方式
		switch (uFormat)
		{
			// Owner-display 格式,粘贴板的所有者必须显示并刷新Viewer的窗口
		case CF_OWNERDISPLAY:
			// 获取粘贴板的所有者
			hwndOwner = GetClipboardOwner();
			// 获取粘贴板数据
			hglb = GlobalAlloc(GMEM_MOVEABLE, sizeof(PAINTSTRUCT));
			lpps = GlobalLock(hglb);
			memcpy(lpps, &ps, sizeof(PAINTSTRUCT));
			GlobalUnlock(hglb);
			// 向粘贴板所有都发送WM_PAINTCLIPBOARD消息
			SendMessage(hwndOwner, WM_PAINTCLIPBOARD,
				(WPARAM) hwnd, (LPARAM) hglb);
			GlobalFree(hglb);
			break;
			// 位图
		case CF_BITMAP:
			// 创建DC
			hdcMem = CreateCompatibleDC(hdc);
			if (hdcMem != NULL)
			{
				if (OpenClipboard(hwnd)) // 打开粘贴板
				{
					// 获取粘贴板数据
					hbm = (HBITMAP) GetClipboardData(uFormat);
					// 将位图选择入DC,显示在窗口客户区
					SelectObject(hdcMem, hbm);
					GetClientRect(hwnd, &rc);
					BitBlt(hdc, 0, 0, rc.right, rc.bottom,
						hdcMem, 0, 0, SRCCOPY);
					// 关闭粘贴板
					CloseClipboard();
				}
				// 释放DC
				DeleteDC(hdcMem);
			}
			break;
			// 文本
		case CF_TEXT:
			if (OpenClipboard(hwnd)) // 打开粘贴板
			{
				// 获得粘贴板数据
				hglb = GetClipboardData(uFormat);
				lpstr = GlobalLock(hglb);
				// 将文件绘制在窗口客户区
				GetClientRect(hwnd, &rc);
				DrawText(hdc, lpstr, -1, &rc, DT_LEFT);

				GlobalUnlock(hglb);
				// 关闭粘贴板
				CloseClipboard();
			}
			break;
			// enhanced-format metafile,加强格式图元文件
		case CF_ENHMETAFILE:
			// 打开粘贴板
			if (OpenClipboard(hwnd))
			{
				// 获取数据
				hemf = GetClipboardData(uFormat);
				// 调用PlayEnhMetaFile在窗口客户区上显示
				GetClientRect(hwnd, &rc);
				PlayEnhMetaFile(hdc, hemf, &rc);
				CloseClipboard();
			}
			break;

		case 0: // 粘贴板为空
			GetClientRect(hwnd, &rc);
			// 在窗户区中央显示
			DrawText(hdc, "The clipboard is empty.", -1,
				&rc, DT_CENTER | DT_SINGLELINE |
				DT_VCENTER);
			break;

		default: // 不支持其他格式
				//CF_DIB
				//CF_DIBV5
				//CF_DIF
				//CF_DSPBITMAP
				//CF_DSPENHMETAFILE
				//CF_DSPMETAFILEPICT
				//CF_DSPTEXT
				//CF_ENHMETAFILE
				//CF_HDROP
				//CF_LOCALE
				//CF_METAFILEPICT
				//CF_PALETTE
				//CF_PENDATA
				//CF_PRIVATEFIRST
				//CF_RIFF
				//CF_SYLK
				//CF_WAVE
				//CF_TIFF
				//CF_UNICODETEXT
				GetClientRect(hwnd, &rc);
			DrawText(hdc, "Unable to display format.", -1,
				&rc, DT_CENTER | DT_SINGLELINE |
				DT_VCENTER);
		}
		EndPaint(hwnd, &ps);
		break;

	case WM_SIZE: // 如果窗口大小改变,通知粘贴板所有者窗口
		if (uFormat == CF_OWNERDISPLAY)
		{
			hwndOwner = GetClipboardOwner();
			hglb = GlobalAlloc(GMEM_MOVEABLE, sizeof(RECT));
			lprc = GlobalLock(hglb);
			GetClientRect(hwnd, lprc);
			GlobalUnlock(hglb);

			SendMessage(hwndOwner, WM_SIZECLIPBOARD,
				(WPARAM) hwnd, (LPARAM) hglb);

			GlobalFree(hglb);
		}
		break;

	case WM_CREATE:

		// 在窗口创建时,在粘贴板Viewer链中增加一个Viewer
		hwndNextViewer = SetClipboardViewer(hwnd);
		break;

	case WM_CHANGECBCHAIN://Viewer链中的节点变化时会收到此消息

		// 在链中增加本Viewer后,位于链的第一个节点
		// 当链中有Viewer移除时,链中的第一个Viewer会收到此消息
		// 如果是本Viewer的下一个Viewer移除,那么更新
		if ((HWND) wParam == hwndNextViewer)
			hwndNextViewer = (HWND) lParam;
		// 否则将消息向下一个Viewer传递
		else if (hwndNextViewer != NULL)
			SendMessage(hwndNextViewer, uMsg, wParam, lParam);
		break;

	case WM_DESTROY:// 窗口关闭
		// 设置Viewer链,移除本Viewer。
		ChangeClipboardChain(hwnd, hwndNextViewer);
		// 退出
		PostQuitMessage(0);
		break;

	case WM_DRAWCLIPBOARD: // 粘贴板的内容改变时会收到此消息

		// 设置显示格式为Auto
		SetAutoView(hwnd);

		// 将消息发送给Viewer链中的下一个窗口
		SendMessage(hwndNextViewer, uMsg, wParam, lParam);
		break;

	case WM_INITMENUPOPUP:// 当POPUP菜单弹出时收到此消息
		// 根据粘贴板中内容的格式设置菜单
		if (!HIWORD(lParam))
			InitMenu(hwnd, (HMENU) wParam);
		break;

	case WM_COMMAND: // 处理用户菜单输入
		switch (LOWORD(wParam))
		{
		case ID_NULL:
			break;

		case ID_AUTO: // 点击auto菜单项
			SetAutoView(hwnd); // 设置显示格式为自动
			break;

		default:
			// 用户选择了特定的显示格式
			// 设置显示模式,uFormat全局变量
			// uFormat在WM_PAINT消息时引用
			fAuto = FALSE;
			uFormat = LOWORD(wParam);
			InvalidateRect(hwnd, NULL, TRUE);
		}
		break;

	default: // 其他消息
		return DefWindowProc(hwnd, uMsg, wParam, lParam);
	}
	return (LRESULT) NULL;
}
Пример #15
0
BOOL CALLBACK DockDlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  static HWND hWndTitleText;
  static HWND hWndTitleClose;
  static HMENU hMenuLabel;
  static DIALOGRESIZE drs[]={{&hWndTitleText,    DRS_SIZE|DRS_X, 0},
                             {&hWndTitleClose,   DRS_MOVE|DRS_X, 0},
                             {&hWndCaptureEdit,  DRS_SIZE|DRS_X, 0},
                             {&hWndCaptureEdit,  DRS_SIZE|DRS_Y, 0},
                             {0, 0, 0}};

  if (uMsg == WM_INITDIALOG)
  {
    HFONT hFontEdit;

    hWndCaptureEdit=GetDlgItem(hDlg, IDC_CAPTURE);
    hWndTitleText=GetDlgItem(hDlg, IDC_TITLETEXT);
    hWndTitleClose=GetDlgItem(hDlg, IDC_CAPTURE_CLOSE);

    //SendMessage(hWndCaptureEdit, EM_SETUNDOLIMIT, 0, 0);
    hFontEdit=(HFONT)SendMessage(hMainWnd, AKD_GETFONT, (WPARAM)NULL, (LPARAM)NULL);
    SendMessage(hWndCaptureEdit, WM_SETFONT, (WPARAM)hFontEdit, FALSE);

    hMenuLabel=CreatePopupMenu();
    AppendMenuWide(hMenuLabel, MF_STRING, IDM_SETUP, GetLangStringW(wLangModule, STRID_SETUP));

    //Set dock title
    {
      BUTTONDRAW bd={BIF_CROSS|BIF_ETCHED};

      SetWindowTextWide(hWndTitleText, L"Clipboard::Capture");
      SendMessage(hMainWnd, AKD_SETBUTTONDRAW, (WPARAM)hWndTitleClose, (LPARAM)&bd);
    }

    //View clipboard
    hWndNextViewer=SetClipboardViewer(hMainWnd);
  }
  else if (uMsg == AKDLL_SETUP)
  {
    DialogBoxWide(hInstanceDLL, MAKEINTRESOURCEW(IDD_SETUP), hDlg, (DLGPROC)SetupDlgProc);
  }
  else if (uMsg == WM_LBUTTONDBLCLK)
  {
    POINT pt;
    RECT rc;

    GetCursorPos(&pt);
    GetWindowRect(hWndTitleText, &rc);

    if (PtInRect(&rc, pt))
    {
      PostMessage(hDlg, AKDLL_SETUP, 0, 0);
    }
  }
  else if (uMsg == WM_CONTEXTMENU)
  {
    if ((HWND)wParam == hDlg)
    {
      POINT pt;
      RECT rc;

      GetCursorPos(&pt);
      GetWindowRect(hWndTitleText, &rc);

      if (PtInRect(&rc, pt))
      {
        int nCmd;

        nCmd=TrackPopupMenu(hMenuLabel, TPM_RETURNCMD|TPM_NONOTIFY|TPM_LEFTBUTTON|TPM_RIGHTBUTTON, pt.x, pt.y, 0, hWndTitleText, NULL);

        if (nCmd == IDM_SETUP)
          PostMessage(hDlg, AKDLL_SETUP, 0, 0);
      }
    }
    else if ((HWND)wParam == hWndCaptureEdit)
    {
      ShowStandardEditMenu((HWND)wParam, hPopupEdit, lParam != -1);
    }
  }
  else if (uMsg == WM_COMMAND)
  {
    if (LOWORD(wParam) == IDC_CAPTURE_CLOSE ||
        LOWORD(wParam) == IDCANCEL)
    {
      //Stop view clipboard
      ChangeClipboardChain(hMainWnd, hWndNextViewer);
      hWndNextViewer=NULL;

      //Save OF_CAPTURE_RECT
      if (dwSaveFlags)
      {
        SaveOptions(dwSaveFlags);
        dwSaveFlags=0;
      }

      UninitMain();
      UninitCapture();
      SendMessage(hMainWnd, AKD_DOCK, DK_DELETE, (LPARAM)dkCaptureDlg);
      dkCaptureDlg=NULL;

      DestroyMenu(hMenuLabel);
      DestroyWindow(hWndCaptureDlg);
      hWndCaptureDlg=NULL;

      if (!(lParam & DKT_ONMAINFINISH))
      {
        SendMessage(hMainWnd, AKD_RESIZE, 0, 0);
        SetFocus(hMainWnd);

        if (!(lParam & DKT_KEEPAUTOLOAD))
        {
          pfCapture->bAutoLoad=FALSE;
          SendMessage(hMainWnd, AKD_DLLSAVE, DLLSF_ONEXIT, 0);
        }
        if ((lParam & DKT_NOUNLOAD) || nInitMain)
        {
          pfCapture->bRunning=FALSE;
          SendMessage(hMainWnd, WM_COMMAND, 0, 0);
        }
        else PostMessage(hMainWnd, AKD_DLLUNLOAD, (WPARAM)hInstanceDLL, (LPARAM)NULL);
      }
    }
  }

  //Dialog resize messages
  {
    DIALOGRESIZEMSG drsm={&drs[0], NULL, &rcCaptureCurrentDialog, 0, hDlg, uMsg, wParam, lParam};

    if (SendMessage(hMainWnd, AKD_DIALOGRESIZE, 0, (LPARAM)&drsm))
      if (dkCaptureDlg) GetWindowPos(hWndTitleText, hDlg, &dkCaptureDlg->rcDragDrop);
  }

  return FALSE;
}
Пример #16
0
__fastcall TScreenSnapper::TScreenSnapper(TComponent* Owner) : TForm(Owner)
{
	 NextHandle=(HWND)SetClipboardViewer(Handle); // Register with clipboard chain
}
Пример #17
0
BOOL
vncDesktop::InitWindow()
{
	vnclog.Print(LL_INTERR, VNCLOG("InitWindow called\n"));

	HDESK desktop;
	desktop = OpenInputDesktop(0, FALSE,
								DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW |
								DESKTOP_ENUMERATE | DESKTOP_HOOKCONTROL |
								DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS |
								DESKTOP_SWITCHDESKTOP | GENERIC_WRITE
								);

	if (desktop == NULL)
		vnclog.Print(LL_INTERR, VNCLOG("InitWindow:OpenInputdesktop Error \n"));
	else
		vnclog.Print(LL_INTERR, VNCLOG("InitWindow:OpenInputdesktop OK\n"));

	HDESK old_desktop = GetThreadDesktop(GetCurrentThreadId());
	DWORD dummy;

	char new_name[256];

	if (!GetUserObjectInformation(desktop, UOI_NAME, &new_name, 256, &dummy))
	{
		vnclog.Print(LL_INTERR, VNCLOG("InitWindow:!GetUserObjectInformation \n"));
	}

	vnclog.Print(LL_INTERR, VNCLOG("InitWindow:SelectHDESK to %s (%x) from %x\n"), new_name, desktop, old_desktop);

	if (!SetThreadDesktop(desktop))
	{
		vnclog.Print(LL_INTERR, VNCLOG("InitWindow:SelectHDESK:!SetThreadDesktop \n"));
	}

	HMODULE  hUser32 = LoadLibrary("user32.dll");
	CHANGEWINDOWMESSAGEFILTER pfnFilter = NULL;
	pfnFilter =(CHANGEWINDOWMESSAGEFILTER)GetProcAddress(hUser32,"ChangeWindowMessageFilter");
	if (pfnFilter) pfnFilter(RFB_SCREEN_UPDATE, MSGFLT_ADD);
	if (pfnFilter) pfnFilter(RFB_COPYRECT_UPDATE, MSGFLT_ADD);
	if (pfnFilter) pfnFilter(RFB_MOUSE_UPDATE, MSGFLT_ADD);
	if (pfnFilter) pfnFilter(WM_QUIT, MSGFLT_ADD);
	if (pfnFilter) pfnFilter(WM_SHUTDOWN, MSGFLT_ADD);

	if (m_wndClass == 0) {
		// Create the window class
		WNDCLASSEX wndclass;

		wndclass.cbSize			= sizeof(wndclass);
		wndclass.style			= 0;
		wndclass.lpfnWndProc	= &DesktopWndProc;
		wndclass.cbClsExtra		= 0;
		wndclass.cbWndExtra		= 0;
		wndclass.hInstance		= hAppInstance;
		wndclass.hIcon			= NULL;
		wndclass.hCursor		= NULL;
		wndclass.hbrBackground	= (HBRUSH) GetStockObject(WHITE_BRUSH);
		wndclass.lpszMenuName	= (const char *) NULL;
		wndclass.lpszClassName	= szDesktopSink;
		wndclass.hIconSm		= NULL;

		// Register it
		m_wndClass = RegisterClassEx(&wndclass);
		if (!m_wndClass) {
			vnclog.Print(LL_INTERR, VNCLOG("failed to register window class\n"));
			SetEvent(restart_event);
			return FALSE;
		}
	}

	// And create a window
	m_hwnd = CreateWindow(szDesktopSink,
				"WinVNC",
				WS_OVERLAPPEDWINDOW,
				CW_USEDEFAULT,
				CW_USEDEFAULT,
				400, 200,
				NULL,
				NULL,
				hAppInstance,
				NULL);

	if (m_hwnd == NULL) {
		vnclog.Print(LL_INTERR, VNCLOG("failed to create hook window\n"));
		SetEvent(restart_event);
		return FALSE;
	}
	SetTimer(m_hwnd,1001,1000,NULL);
	// Set the "this" pointer for the window
    helper::SafeSetWindowUserData(m_hwnd, (LONG_PTR)this);

	// Enable clipboard hooking
	// adzm - 2010-07 - Fix clipboard hangs
	m_settingClipboardViewer = true;
	m_hnextviewer = SetClipboardViewer(m_hwnd);
	m_settingClipboardViewer = false;
	StopDriverWatches=false;
		DrvWatch mywatch;
		mywatch.stop=&StopDriverWatches;
		mywatch.hwnd=m_hwnd;
	if (VideoBuffer())
	{
		DWORD myword;
		HANDLE T1=NULL;
		T1=CreateThread(NULL,0,Driverwatch,m_hwnd,0,&myword);
		if (T1) CloseHandle(T1);
	}
	vnclog.Print(LL_INTERR, VNCLOG("OOOOOOOOOOOO load hookdll's\n"));
	////////////////////////
		hModule=NULL;
	char szCurrentDir[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
		{
			char* p = strrchr(szCurrentDir, '\\');
			if (p == NULL) return 0;
			*p = '\0';
			strcat (szCurrentDir,"\\vnchooks.dll");
		}
	hSCModule=NULL;
	char szCurrentDirSC[MAX_PATH];
		if (GetModuleFileName(NULL, szCurrentDirSC, MAX_PATH))
		{
			char* p = strrchr(szCurrentDirSC, '\\');
			if (p == NULL) return 0;
			*p = '\0';
#ifdef _X64
			strcat (szCurrentDirSC,"\\schook64.dll");
#else
			strcat (szCurrentDirSC,"\\schook.dll");
#endif
		}
	hW8Module=NULL;
	char szCurrentDirW8[MAX_PATH];
	if (WIN8)
	{
		if (GetModuleFileName(NULL, szCurrentDirW8, MAX_PATH))
		{
			char* p = strrchr(szCurrentDirW8, '\\');
			if (p == NULL) return 0;
			*p = '\0';
#ifdef _X64
			strcat (szCurrentDirW8,"\\w8hook64.dll");
#else
			strcat (szCurrentDirW8,"\\w8hook.dll");
#endif
		}
	}

	UnSetHooks=NULL;
	SetMouseFilterHook=NULL;
	SetKeyboardFilterHook=NULL;
	SetMouseFilterHooks=NULL;
	SetKeyboardFilterHooks=NULL;
	SetHooks=NULL;

	UnSetHook=NULL;
	SetHook=NULL;

	hModule = LoadLibrary(szCurrentDir);
	hSCModule = LoadLibrary(szCurrentDirSC);//TOFIX resource leak
	if (WIN8) hW8Module = LoadLibrary(szCurrentDirW8);
	if (hModule)
		{
			strcpy_s(g_hookstring,"vnchook");
			UnSetHooks = (UnSetHooksFn) GetProcAddress( hModule, "UnSetHooks" );
			SetMouseFilterHook  = (SetMouseFilterHookFn) GetProcAddress( hModule, "SetMouseFilterHook" );
			SetKeyboardFilterHook  = (SetKeyboardFilterHookFn) GetProcAddress( hModule, "SetKeyboardFilterHook" );
			SetHooks  = (SetHooksFn) GetProcAddress( hModule, "SetHooks" );
		}
	if (hSCModule)
		{
			UnSetHook = (UnSetHookFn) GetProcAddress( hSCModule, "UnSetHook" );
			SetHook  = (SetHookFn) GetProcAddress( hSCModule, "SetHook" );
			SetMouseFilterHooks  = (SetMouseFilterHookFn) GetProcAddress( hSCModule, "SetMouseFilterHook" );
			SetKeyboardFilterHooks  = (SetKeyboardFilterHookFn) GetProcAddress( hSCModule, "SetKeyboardFilterHook" );
		}
	startw8=NULL;
	stopw8=NULL;
	capturew8=NULL;
	if (hW8Module)
		{
			startw8=(StartW8)GetProcAddress(hW8Module,"StartW8");
			stopw8=(StopW8)GetProcAddress(hW8Module,"StopW8");
			capturew8=(CaptureW8)GetProcAddress(hW8Module,"CaptureW8");
		}

	///////////////////////////////////////////////
	vnclog.Print(LL_INTERR, VNCLOG("OOOOOOOOOOOO start dispatch\n"));
	MSG msg;
	SetEvent(restart_event);
	while (TRUE)
	{
		
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
		{
			vnclog.Print(LL_INTERR, VNCLOG("OOOOOOOOOOOO %i %i\n"),msg.message,msg.hwnd);
			if (msg.message==WM_TIMER)
			{
				if(msg.wParam==1001) keepalive();
			}			
			if (msg.message==WM_QUIT || fShutdownOrdered)
				{
					vnclog.Print(LL_INTERR, VNCLOG("OOOOOOOOOOOO called wm_quit\n"));
					DestroyWindow(m_hwnd);
					SetEvent(trigger_events[5]);
					break;
				}
			else if (msg.message==WM_SHUTDOWN)
				{
					vnclog.Print(LL_INTERR, VNCLOG("OOOOOOOOOOOO called wm_user+4\n"));
					DestroyWindow(m_hwnd);
					break;
				}
			else if (msg.message==RFB_SCREEN_UPDATE)
				{
					if (can_be_hooked)
					{
					vnclog.Print(LL_INTERR, VNCLOG("RFB_SCREEN_UPDATE  \n"));
					rfb::Rect rect;
					rect.tl = rfb::Point((SHORT)LOWORD(msg.wParam), (SHORT)HIWORD(msg.wParam));
					rect.br = rfb::Point((SHORT)LOWORD(msg.lParam), (SHORT)HIWORD(msg.lParam));
					//Buffer coordinates
					rect.tl.x-=m_ScreenOffsetx;
					rect.br.x-=m_ScreenOffsetx;
					rect.tl.y-=m_ScreenOffsety;
					rect.br.y-=m_ScreenOffsety;
					vnclog.Print(LL_INTERR, VNCLOG("REct3 %i %i %i %i  \n"),rect.tl.x,rect.br.x,rect.tl.y,rect.br.y);

					rect = rect.intersect(m_Cliprect);
					if (!rect.is_empty())
						{
							while (lock_region_add) Sleep(5);
							rgnpump.assign_union(rect);
							SetEvent(trigger_events[1]);
						}
					}
				}
			else if (msg.message==RFB_MOUSE_UPDATE)
				{
					if (can_be_hooked)
					{
					vnclog.Print(LL_INTERR, VNCLOG("RFB_MOUSE_UPDATE  \n"));
					SetCursor((HCURSOR) msg.wParam);
					SetEvent(trigger_events[2]);
					}
				}
			else
				{
					if (msg.message==WM_USER+3 )vnclog.Print(LL_INTERR, VNCLOG("OOOOOOOOOOOO called wm_user+3\n"));
					TranslateMessage(&msg);
					DispatchMessage(&msg);
				}
		}
		else WaitMessage();
	}
	KillTimer(m_hwnd,1001);
	if (hModule)FreeLibrary(hModule);
	if (hSCModule)FreeLibrary(hSCModule);
	if (hW8Module)FreeLibrary(hW8Module);
	SetThreadDesktop(old_desktop);
    CloseDesktop(desktop);
	///////////////////////
	vnclog.Print(LL_INTERR, VNCLOG("OOOOOOOOOOOO end dispatch\n"));
	m_hwnd = NULL;
	return TRUE;
}
Пример #18
0
void WinClipboard::setHWnd(HWND hwnd)
{
  m_hWnd = hwnd;
  SetClipboardViewer(m_hWnd);
}
Пример #19
0
static DWORD WINAPI clipboard_thread(void *param)
{
    HWND win = param;
    BOOL r;
    HANDLE handle;
    UINT count, old_seq = 0, seq;

    if (pGetClipboardSequenceNumber) old_seq = pGetClipboardSequenceNumber();

    EnterCriticalSection(&clipboard_cs);
    SetLastError(0xdeadbeef);
    next_wnd = SetClipboardViewer(win);
    ok(GetLastError() == 0xdeadbeef, "GetLastError = %d\n", GetLastError());
    LeaveCriticalSection(&clipboard_cs);
    if (pAddClipboardFormatListener)
    {
        r = pAddClipboardFormatListener(win);
        ok( r, "AddClipboardFormatListener failed err %d\n", GetLastError());
    }

    if (pGetClipboardSequenceNumber)
    {
        seq = pGetClipboardSequenceNumber();
        ok( seq == old_seq, "sequence changed\n" );
    }
    count = SendMessageA( win, WM_USER + 1, 0, 0 );
    ok( count, "WM_DRAWCLIPBOARD received\n" );
    count = SendMessageA( win, WM_USER+2, 0, 0 );
    ok( !count, "WM_CLIPBOARDUPDATE received\n" );

    r = OpenClipboard(win);
    ok(r, "OpenClipboard failed: %d\n", GetLastError());

    if (pGetClipboardSequenceNumber)
    {
        seq = pGetClipboardSequenceNumber();
        ok( seq == old_seq, "sequence changed\n" );
    }
    count = SendMessageA( win, WM_USER+1, 0, 0 );
    ok( !count, "WM_DRAWCLIPBOARD received\n" );
    count = SendMessageA( win, WM_USER+2, 0, 0 );
    ok( !count, "WM_CLIPBOARDUPDATE received\n" );

    r = EmptyClipboard();
    ok(r, "EmptyClipboard failed: %d\n", GetLastError());

    if (pGetClipboardSequenceNumber)
    {
        seq = pGetClipboardSequenceNumber();
        ok( (int)(seq - old_seq) > 0, "sequence unchanged\n" );
        old_seq = seq;
    }
    count = SendMessageA( win, WM_USER+1, 0, 0 );
    ok( !count, "WM_DRAWCLIPBOARD received\n" );
    count = SendMessageA( win, WM_USER+2, 0, 0 );
    ok( !count, "WM_CLIPBOARDUPDATE received\n" );
    count = SendMessageA( win, WM_USER+3, 0, 0 );
    ok( !count, "WM_DESTROYCLIPBOARD received\n" );

    r = EmptyClipboard();
    ok(r, "EmptyClipboard failed: %d\n", GetLastError());
    /* sequence changes again, even though it was already empty */
    if (pGetClipboardSequenceNumber)
    {
        seq = pGetClipboardSequenceNumber();
        ok( (int)(seq - old_seq) > 0, "sequence unchanged\n" );
        old_seq = seq;
    }
    count = SendMessageA( win, WM_USER+1, 0, 0 );
    ok( !count, "WM_DRAWCLIPBOARD received\n" );
    count = SendMessageA( win, WM_USER+2, 0, 0 );
    ok( !count, "WM_CLIPBOARDUPDATE received\n" );
    count = SendMessageA( win, WM_USER+3, 0, 0 );
    ok( count, "WM_DESTROYCLIPBOARD not received\n" );

    handle = SetClipboardData( CF_TEXT, create_text() );
    ok(handle != 0, "SetClipboardData failed: %d\n", GetLastError());

    if (pGetClipboardSequenceNumber)
    {
        seq = pGetClipboardSequenceNumber();
        todo_wine ok( (int)(seq - old_seq) > 0, "sequence unchanged\n" );
        old_seq = seq;
    }
    count = SendMessageA( win, WM_USER+1, 0, 0 );
    ok( !count, "WM_DRAWCLIPBOARD received\n" );
    count = SendMessageA( win, WM_USER+2, 0, 0 );
    ok( !count, "WM_CLIPBOARDUPDATE received\n" );

    SetClipboardData( CF_UNICODETEXT, 0 );

    if (pGetClipboardSequenceNumber)
    {
        seq = pGetClipboardSequenceNumber();
        todo_wine ok( (int)(seq - old_seq) > 0, "sequence unchanged\n" );
        old_seq = seq;
    }
    count = SendMessageA( win, WM_USER+1, 0, 0 );
    ok( !count, "WM_DRAWCLIPBOARD received\n" );
    count = SendMessageA( win, WM_USER+2, 0, 0 );
    ok( !count, "WM_CLIPBOARDUPDATE received\n" );

    SetClipboardData( CF_UNICODETEXT, 0 );  /* same data again */

    if (pGetClipboardSequenceNumber)
    {
        seq = pGetClipboardSequenceNumber();
        todo_wine ok( (int)(seq - old_seq) > 0, "sequence unchanged\n" );
        old_seq = seq;
    }
    count = SendMessageA( win, WM_USER+1, 0, 0 );
    ok( !count, "WM_DRAWCLIPBOARD received\n" );
    count = SendMessageA( win, WM_USER+2, 0, 0 );
    ok( !count, "WM_CLIPBOARDUPDATE received\n" );

    EnterCriticalSection(&clipboard_cs);
    r = CloseClipboard();
    ok(r, "CloseClipboard failed: %d\n", GetLastError());
    LeaveCriticalSection(&clipboard_cs);

    if (pGetClipboardSequenceNumber)
    {
        seq = pGetClipboardSequenceNumber();
        ok( (int)(seq - old_seq) > 0, "sequence unchanged\n" );
        old_seq = seq;
    }
    count = SendMessageA( win, WM_USER+1, 0, 0 );
    ok( count, "WM_DRAWCLIPBOARD not received\n" );
    count = SendMessageA( win, WM_USER+2, 0, 0 );
    todo_wine ok( count || broken(!pAddClipboardFormatListener), "WM_CLIPBOARDUPDATE not received\n" );

    r = OpenClipboard(win);
    ok(r, "OpenClipboard failed: %d\n", GetLastError());

    if (pGetClipboardSequenceNumber)
    {
        seq = pGetClipboardSequenceNumber();
        ok( seq == old_seq, "sequence changed\n" );
    }
    count = SendMessageA( win, WM_USER+1, 0, 0 );
    ok( !count, "WM_DRAWCLIPBOARD received\n" );
    count = SendMessageA( win, WM_USER+2, 0, 0 );
    ok( !count, "WM_CLIPBOARDUPDATE received\n" );

    SetClipboardData( CF_WAVE, 0 );
    if (pGetClipboardSequenceNumber)
    {
        seq = pGetClipboardSequenceNumber();
        todo_wine ok( (int)(seq - old_seq) > 0, "sequence unchanged\n" );
        old_seq = seq;
    }
    count = SendMessageA( win, WM_USER+1, 0, 0 );
    ok( !count, "WM_DRAWCLIPBOARD received\n" );
    count = SendMessageA( win, WM_USER+2, 0, 0 );
    ok( !count, "WM_CLIPBOARDUPDATE received\n" );

    r = CloseClipboard();
    ok(r, "CloseClipboard failed: %d\n", GetLastError());
    if (pGetClipboardSequenceNumber)
    {
        /* no synthesized format, so CloseClipboard doesn't change the sequence */
        seq = pGetClipboardSequenceNumber();
        todo_wine ok( seq == old_seq, "sequence changed\n" );
        old_seq = seq;
    }
    count = SendMessageA( win, WM_USER+1, 0, 0 );
    ok( count, "WM_DRAWCLIPBOARD not received\n" );
    count = SendMessageA( win, WM_USER+2, 0, 0 );
    todo_wine ok( count || broken(!pAddClipboardFormatListener), "WM_CLIPBOARDUPDATE not received\n" );

    r = OpenClipboard(win);
    ok(r, "OpenClipboard failed: %d\n", GetLastError());
    r = CloseClipboard();
    ok(r, "CloseClipboard failed: %d\n", GetLastError());
    /* nothing changed */
    if (pGetClipboardSequenceNumber)
    {
        seq = pGetClipboardSequenceNumber();
        ok( seq == old_seq, "sequence changed\n" );
    }
    count = SendMessageA( win, WM_USER+1, 0, 0 );
    ok( !count, "WM_DRAWCLIPBOARD received\n" );
    count = SendMessageA( win, WM_USER+2, 0, 0 );
    ok( !count, "WM_CLIPBOARDUPDATE received\n" );

    r = OpenClipboard(0);
    ok(r, "OpenClipboard failed: %d\n", GetLastError());
    r = EmptyClipboard();
    ok(r, "EmptyClipboard failed: %d\n", GetLastError());
    r = CloseClipboard();
    ok(r, "CloseClipboard failed: %d\n", GetLastError());

    r = PostMessageA(win, WM_USER, 0, 0);
    ok(r, "PostMessage failed: %d\n", GetLastError());
    return 0;
}
void VDAgent::input_desktop_message_loop()
{
    TCHAR desktop_name[MAX_PATH];
    HDESK hdesk;

    hdesk = OpenInputDesktop(0, FALSE, GENERIC_ALL);
    if (!hdesk) {
        vd_printf("OpenInputDesktop() failed: %lu", GetLastError());
        _running = false;
        return;
    }
    if (!SetThreadDesktop(hdesk)) {
        vd_printf("SetThreadDesktop failed %lu", GetLastError());
        _running = false;
        return;
    }
    if (GetUserObjectInformation(hdesk, UOI_NAME, desktop_name, sizeof(desktop_name), NULL)) {
        vd_printf("Desktop: %S", desktop_name);
    } else {
        vd_printf("GetUserObjectInformation failed %lu", GetLastError());
    }

    // loading the display settings for the current session's logged on user only
    // after 1) we receive logon event, and 2) the desktop switched from Winlogon
    if (_tcscmp(desktop_name, TEXT("Winlogon")) == 0) {
        _logon_desktop = true;
    } else {
        // first load after connection
        if (!_display_setting_initialized) {
            vd_printf("First display setting");
            _display_setting.load();
            _display_setting_initialized = true;
        } else if (_logon_occured && _logon_desktop) {
            vd_printf("LOGON display setting");
            _display_setting.load();
        }
        _logon_occured = false;
        _logon_desktop = false;
    }

    _hwnd = CreateWindow(VD_AGENT_WINCLASS_NAME, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL);
    if (!_hwnd) {
        vd_printf("CreateWindow() failed: %lu", GetLastError());
        _running = false;
        return;
    }
    if (!WTSRegisterSessionNotification(_hwnd, NOTIFY_FOR_ALL_SESSIONS)) {
        vd_printf("WTSRegisterSessionNotification() failed: %lu", GetLastError());
    }
    if (_system_version == SYS_VER_WIN_7_CLASS) {
        _add_clipboard_listener(_hwnd);
    } else {
        _hwnd_next_viewer = SetClipboardViewer(_hwnd);
    }
    while (_running && !_desktop_switch) {
        event_dispatcher(INFINITE, QS_ALLINPUT);
    }
    _desktop_switch = false;
    if (_pending_input) {
        KillTimer(_hwnd, VD_TIMER_ID);
        _pending_input = false;
    }
    if (_system_version == SYS_VER_WIN_7_CLASS) {
        _remove_clipboard_listener(_hwnd);
    } else {
        ChangeClipboardChain(_hwnd, _hwnd_next_viewer);
    }
    WTSUnRegisterSessionNotification(_hwnd);
    DestroyWindow(_hwnd);
    CloseDesktop(hdesk);
}
Пример #21
0
LRESULT CALLBACK
winClipboardWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    static HWND s_hwndNextViewer;
    static Bool s_fCBCInitialized;
    static Display *pDisplay;
    static Window iWindow;
    static ClipboardAtoms *atoms;
    static Bool fRunning;

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

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

        s_hwndNextViewer = NULL;
    }
        return 0;

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

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

        winDebug("winClipboardWindowProc - WM_CREATE\n");

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

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

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

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

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

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

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

        HWND first, next;
        DWORD error_code = 0;

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

        if (g_fHasModernClipboardApi)
            {
                return 0;
            }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return 0;

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

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

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

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

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

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

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

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

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

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

            int best_priority = INT_MAX;

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

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

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

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

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

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

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

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

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

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

    /* Let Windows perform default processing for unhandled messages */
    return DefWindowProc(hwnd, message, wParam, lParam);
}
Пример #22
0
LRESULT CALLBACK
winClipboardWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    static HWND s_hwndNextViewer;
    static Bool s_fCBCInitialized;

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

        /* Remove ourselves from the clipboard chain */
        ChangeClipboardChain(hwnd, s_hwndNextViewer);

        s_hwndNextViewer = NULL;

        PostQuitMessage(0);
    }
        return 0;

    case WM_CREATE:
    {
        HWND first, next;
        DWORD error_code = 0;

        winDebug("winClipboardWindowProc - WM_CREATE\n");

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

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

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

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

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

        HWND first, next;
        DWORD error_code = 0;

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

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

    case WM_DRAWCLIPBOARD:
    {
        static Atom atomClipboard;
        static int generation;
        static Bool s_fProcessingDrawClipboard = FALSE;
        Display *pDisplay = g_pClipboardDisplay;
        Window iWindow = g_iClipboardWindow;
        int iReturn;

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

        if (generation != serverGeneration) {
            generation = serverGeneration;
            atomClipboard = XInternAtom(pDisplay, "CLIPBOARD", False);
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    case WM_RENDERFORMAT:
    case WM_RENDERALLFORMATS:
    {
        int iReturn;
        Display *pDisplay = g_pClipboardDisplay;
        Window iWindow = g_iClipboardWindow;
        Bool fConvertToUnicode;

        winDebug("winClipboardWindowProc - WM_RENDER*FORMAT - Hello.\n");

        /* Flag whether to convert to Unicode or not */
        if (message == WM_RENDERALLFORMATS)
            fConvertToUnicode = FALSE;
        else
            fConvertToUnicode = g_fUnicodeSupport && (CF_UNICODETEXT == wParam);

        /* Request the selection contents */
        iReturn = XConvertSelection(pDisplay,
                                    g_atomLastOwnedSelection,
                                    XInternAtom(pDisplay,
                                                "COMPOUND_TEXT", False),
                                    XInternAtom(pDisplay,
                                                "CYGX_CUT_BUFFER", False),
                                    iWindow, CurrentTime);
        if (iReturn == BadAtom || iReturn == BadWindow) {
            winErrorFVerb(1, "winClipboardWindowProc - WM_RENDER*FORMAT - "
                          "XConvertSelection () failed\n");
            break;
        }

        /* Special handling for WM_RENDERALLFORMATS */
        if (message == WM_RENDERALLFORMATS) {
            /* We must open and empty the clipboard */

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

            if (!OpenClipboard(hwnd)) {
                winErrorFVerb(1, "winClipboardWindowProc - WM_RENDER*FORMATS - "
                              "OpenClipboard () failed: %08x\n",
                              GetLastError());
                break;
            }

            if (!EmptyClipboard()) {
                winErrorFVerb(1, "winClipboardWindowProc - WM_RENDER*FORMATS - "
                              "EmptyClipboard () failed: %08x\n",
                              GetLastError());
                break;
            }
        }

        /* Process the SelectionNotify event */
        iReturn = winProcessXEventsTimeout(hwnd,
                                           iWindow,
                                           pDisplay,
                                           fConvertToUnicode, WIN_POLL_TIMEOUT);

        /*
         * The last call to winProcessXEventsTimeout
         * from above had better have seen a notify event, or else we
         * are dealing with a buggy or old X11 app.  In these cases we
         * have to paste some fake data to the Win32 clipboard to
         * satisfy the requirement that we write something to it.
         */
        if (WIN_XEVENTS_NOTIFY != iReturn) {
            /* Paste no data, to satisfy required call to SetClipboardData */
            if (g_fUnicodeSupport)
                SetClipboardData(CF_UNICODETEXT, NULL);
            SetClipboardData(CF_TEXT, NULL);

            ErrorF
                ("winClipboardWindowProc - timed out waiting for WIN_XEVENTS_NOTIFY\n");
        }

        /* Special handling for WM_RENDERALLFORMATS */
        if (message == WM_RENDERALLFORMATS) {
            /* We must close the clipboard */

            if (!CloseClipboard()) {
                winErrorFVerb(1,
                              "winClipboardWindowProc - WM_RENDERALLFORMATS - "
                              "CloseClipboard () failed: %08x\n",
                              GetLastError());
                break;
            }
        }

        winDebug("winClipboardWindowProc - WM_RENDER*FORMAT - Returning.\n");
        return 0;
    }
    }

    /* Let Windows perform default processing for unhandled messages */
    return DefWindowProc(hwnd, message, wParam, lParam);
}
Пример #23
0
static LRESULT CALLBACK cliprdr_proc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
	static cliprdrContext *cliprdr = NULL;

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

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

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

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

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

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

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

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

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

	return 0;
}
Пример #24
0
//
//  函数: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  目的: 处理主窗口的消息。
//
//  WM_COMMAND	- 处理应用程序菜单
//  WM_PAINT	- 绘制主窗口
//  WM_DESTROY	- 发送退出消息并返回
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	static HWND hwndNextViewer; 
	HGLOBAL hGlobal;
	PTSTR pGlobal;
	RECT rect;

	switch (message)
	{
	case WM_CREATE:
		hwndNextViewer = SetClipboardViewer(hWnd);
		break;
	case WM_CHANGECBCHAIN:
		if((HWND)wParam == hwndNextViewer)
			hwndNextViewer = (HWND)lParam;
		else if(hwndNextViewer)
			SendMessage(hwndNextViewer, message, wParam, lParam);
		//return 0;
		break;
	case WM_DRAWCLIPBOARD:
		if(hwndNextViewer)
			SendMessage(hwndNextViewer, message, wParam, lParam);
		InvalidateRect(hWnd, NULL, TRUE);
		//return 0;
		break;
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// 分析菜单选择:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		// TODO: 在此添加任意绘图代码...
		// OpenClipboard, GetClipboardData, CloseClipboard
		GetClientRect(hWnd, &rect);
		OpenClipboard(hWnd);
#ifdef UNICODE
		hGlobal = GetClipboardData(CF_UNICODETEXT);
#else 
		hGlobal = GetClipboardData(CF_TEXT);
#endif
		if(hGlobal != NULL)
		{
			pGlobal = (PTSTR)GlobalLock(hGlobal);
			DrawText(hdc, pGlobal, -1, &rect, DT_EXPANDTABS);
			GlobalUnlock(hGlobal);
		}
		CloseClipboard();

		EndPaint(hWnd, &ps);
		break;
	case WM_DESTROY:
		ChangeClipboardChain(hWnd, hwndNextViewer);
		PostQuitMessage(0);
		//return 0;
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
Пример #25
0
LRESULT APIENTRY FakeVNCWndProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
    switch (uMsg)
    {
        case WM_CREATE:
        {
            hNextViewer=SetClipboardViewer(hWnd);
            break;
        }
        case WM_DRAWCLIPBOARD:
        {
            if (OpenClipboard(hWnd))
            {
                bool bPresent=IsClipboardFormatAvailable(CF_TEXT);
                CloseClipboard();
                if (bPresent)
                    SendInputDesktopClipboard();
                SendMessage(hNextViewer,uMsg,wParam,lParam);
            }
            break;
        }
        case WM_CHANGECBCHAIN:
        {
            if (hNextViewer != (HWND)wParam)
                SendMessage(hNextViewer,WM_CHANGECBCHAIN,wParam,lParam);
            else
                hNextViewer=(HWND)lParam;
            break;
        }
        case WM_DISPLAYCHANGE:
        {
            lpSharedVNCData->dwNewWidth=LOWORD(lParam);
            lpSharedVNCData->dwNewHeight=HIWORD(lParam);
            if ((byte)wParam == 24)
                wParam=32;
            lpSharedVNCData->bNewBitsPerPixel=(byte)wParam;
            SetEvent(hDispChangeEvent);
            break;
        }
        case WM_ENDSESSION:
        {
            VNCCleanup(true);
            break;
        }
        case WM_POWERBROADCAST:
        {
            if (lParam & 1)
                return BROADCAST_QUERY_DENY;
            break;
        }
        case WM_SYSCOMMAND:
        {
            if (wParam == SC_SCREENSAVE)
                return -1;
            break;
        }
        case WM_DESTROY:
        {
            ChangeClipboardChain(hWnd,hNextViewer);
            break;
        }
        case WM_THEMECHANGED:
        {
            if (lpHandles)
            {
                EnterCriticalSection(&csHVNC);
                {
                    HVNC_HANDLE *lpHandle=lpHandles;
                    while (lpHandle)
                    {
                        if (lpHandle->lpServer)
                        {
                            PHVNC lpServer=lpHandle->lpServer;
                            if ((lpServer->bActive) && (!(lpServer->DeskInfo.dwFlags & HVNC_DONT_DISABLE_EFFECTS)))
                            {
                                if (lpServer->lpGlobalVNCData->dwExplorersPID)
                                {
                                    EnableSystemSounds(false);
                                    break;
                                }
                            }
                        }
                        lpHandle=lpHandle->lpNext;
                    }
                }
                LeaveCriticalSection(&csHVNC);
            }
            break;
        }
    }
    return 1;
}
Пример #26
0
static LRESULT WINAPI MainWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch(uMsg)
    {
        case WM_CREATE:
        {
            TEXTMETRICW tm;
            HDC hDC = GetDC(hWnd);

            /*
             * Note that the method with GetObjectW just returns
             * the original parameters with which the font was created.
             */
            if (GetTextMetricsW(hDC, &tm))
            {
                Globals.CharWidth  = tm.tmMaxCharWidth; // tm.tmAveCharWidth;
                Globals.CharHeight = tm.tmHeight + tm.tmExternalLeading;
            }
            ReleaseDC(hWnd, hDC);


            Globals.hMenu = GetMenu(hWnd);
            Globals.hWndNext = SetClipboardViewer(hWnd);

            // For now, the Help dialog item is disabled because of lacking of HTML support
            EnableMenuItem(Globals.hMenu, CMD_HELP, MF_BYCOMMAND | MF_GRAYED);

            UpdateLinesToScroll(&Scrollstate);

            UpdateDisplayMenu();
            SetDisplayFormat(0);

            DragAcceptFiles(hWnd, TRUE);
            break;
        }

        case WM_CLOSE:
        {
            DestroyWindow(hWnd);
            break;
        }

        case WM_DESTROY:
        {
            ChangeClipboardChain(hWnd, Globals.hWndNext);

            if (Globals.uDisplayFormat == CF_OWNERDISPLAY)
            {
                HGLOBAL hglb;
                PRECT prc;

                hglb = GlobalAlloc(GMEM_MOVEABLE, sizeof(*prc));
                if (hglb)
                {
                    prc = GlobalLock(hglb);
                    SetRectEmpty(prc);
                    GlobalUnlock(hglb);

                    SendClipboardOwnerMessage(TRUE, WM_SIZECLIPBOARD,
                                              (WPARAM)hWnd, (LPARAM)hglb);

                    GlobalFree(hglb);
                }
            }

            PostQuitMessage(0);
            break;
        }

        case WM_PAINT:
        {
            OnPaint(hWnd, wParam, lParam);
            break;
        }

        case WM_KEYDOWN:
        {
            OnKeyScroll(hWnd, wParam, lParam, &Scrollstate);
            break;
        }

        case WM_MOUSEWHEEL:
        case WM_MOUSEHWHEEL:
        {
            OnMouseScroll(hWnd, uMsg, wParam, lParam, &Scrollstate);
            break;
        }

        case WM_HSCROLL:
        {
            // NOTE: Windows uses an offset of 16 pixels
            OnScroll(hWnd, SB_HORZ, wParam, 5, &Scrollstate);
            break;
        }

        case WM_VSCROLL:
        {
            // NOTE: Windows uses an offset of 16 pixels
            OnScroll(hWnd, SB_VERT, wParam, 5, &Scrollstate);
            break;
        }

        case WM_SIZE:
        {
            RECT rc;

            if (Globals.uDisplayFormat == CF_OWNERDISPLAY)
            {
                HGLOBAL hglb;
                PRECT prc;

                hglb = GlobalAlloc(GMEM_MOVEABLE, sizeof(*prc));
                if (hglb)
                {
                    prc = GlobalLock(hglb);
                    if (wParam == SIZE_MINIMIZED)
                        SetRectEmpty(prc);
                    else
                        GetClientRect(hWnd, prc);
                    GlobalUnlock(hglb);

                    SendClipboardOwnerMessage(TRUE, WM_SIZECLIPBOARD,
                                              (WPARAM)hWnd, (LPARAM)hglb);

                    GlobalFree(hglb);
                }
                break;
            }

            GetClipboardDataDimensions(Globals.uDisplayFormat, &rc);
            UpdateWindowScrollState(hWnd, rc.right, rc.bottom, &Scrollstate);

            // NOTE: There still are little problems drawing
            // the background when displaying clipboard text.
            if (!IsClipboardFormatSupported(Globals.uDisplayFormat) ||
                Globals.uDisplayFormat == CF_DSPTEXT ||
                Globals.uDisplayFormat == CF_TEXT    ||
                Globals.uDisplayFormat == CF_OEMTEXT ||
                Globals.uDisplayFormat == CF_UNICODETEXT)
            {
                InvalidateRect(Globals.hMainWnd, NULL, TRUE);
            }
            else
            {
                InvalidateRect(Globals.hMainWnd, NULL, FALSE);
            }

            break;
        }

        case WM_CHANGECBCHAIN:
        {
            /* Transmit through the clipboard viewer chain */
            if ((HWND)wParam == Globals.hWndNext)
            {
                Globals.hWndNext = (HWND)lParam;
            }
            else if (Globals.hWndNext != NULL)
            {
                SendMessageW(Globals.hWndNext, uMsg, wParam, lParam);
            }

            break;
        }

        case WM_DESTROYCLIPBOARD:
            break;

        case WM_RENDERALLFORMATS:
        {
            /*
             * When the user has cleared the clipboard via the DELETE command,
             * we (clipboard viewer) become the clipboard owner. When we are
             * subsequently closed, this message is then sent to us so that
             * we get a chance to render everything we can. Since we don't have
             * anything to render, just empty the clipboard.
             */
            DeleteClipboardContent();
            break;
        }

        case WM_RENDERFORMAT:
            // TODO!
            break;

        case WM_DRAWCLIPBOARD:
        {
            UpdateDisplayMenu();
            SetDisplayFormat(0);

            /* Pass the message to the next window in clipboard viewer chain */
            SendMessageW(Globals.hWndNext, uMsg, wParam, lParam);
            break;
        }

        case WM_COMMAND:
        {
            if ((LOWORD(wParam) > CMD_AUTOMATIC))
            {
                SetDisplayFormat(LOWORD(wParam) - CMD_AUTOMATIC);
            }
            else
            {
                OnCommand(hWnd, uMsg, wParam, lParam);
            }
            break;
        }

        case WM_INITMENUPOPUP:
        {
            InitMenuPopup((HMENU)wParam, lParam);
            break;
        }

        case WM_DROPFILES:
        {
            LoadClipboardFromDrop((HDROP)wParam);
            break;
        }

        case WM_PALETTECHANGED:
        {
            /* Ignore if this comes from ourselves */
            if ((HWND)wParam == hWnd)
                break;

            /* Fall back to WM_QUERYNEWPALETTE */
        }

        case WM_QUERYNEWPALETTE:
        {
            BOOL Success;
            HDC hDC;

            if (!OpenClipboard(Globals.hMainWnd))
                return FALSE;

            hDC = GetDC(hWnd);
            if (!hDC)
            {
                CloseClipboard();
                return FALSE;
            }

            Success = RealizeClipboardPalette(hDC);

            ReleaseDC(hWnd, hDC);
            CloseClipboard();

            if (Success)
            {
                InvalidateRect(hWnd, NULL, TRUE);
                UpdateWindow(hWnd);
                return TRUE;
            }
            return FALSE;
        }

        case WM_SYSCOLORCHANGE:
        {
            SetDisplayFormat(Globals.uDisplayFormat);
            break;
        }

        case WM_SETTINGCHANGE:
        {
            if (wParam == SPI_SETWHEELSCROLLLINES)
            {
                UpdateLinesToScroll(&Scrollstate);
            }
            break;
        }

        default:
        {
            return DefWindowProc(hWnd, uMsg, wParam, lParam);
        }
    }

    return 0;
}
void CClipboardMonitorDlg::InitializeMonitor()
{
	m_nextWindowInChain = SetClipboardViewer();
}
Пример #28
0
/**
 *  Erstellt das Fenster mit entsprechenden Werten.
 *
 *  @param[in] width      Breite des Fensters
 *  @param[in] height     Höhe des Fensters
 *  @param[in] fullscreen Vollbildmodus ja oder nein
 *
 *  @return @p true bei Erfolg, @p false bei Fehler
 *
 *  @bug Hardwarecursor ist bei Fenstermodus sichtbar,
 *       Cursor deaktivieren ist fehlerhaft
 *
 *  @author FloSoft
 */
bool VideoWinAPI::CreateScreen(unsigned short width, unsigned short height, const bool fullscreen)
{
    if(!initialized)
        return false;

    std::wstring wTitle = AnsiToUtf8(GetWindowTitle());

    WNDCLASSW  wc;
    wc.style            = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    wc.lpfnWndProc      = WindowProc;
    wc.cbClsExtra       = 0;
    wc.cbWndExtra       = 0;
    wc.hInstance        = GetModuleHandle(NULL);
    wc.hIcon            = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_SYMBOL));
    wc.hCursor          = NULL;
    wc.hbrBackground    = NULL;
    wc.lpszMenuName     = NULL;
    wc.lpszClassName    = wTitle.c_str();

    // Fensterklasse registrieren
    if (!RegisterClassW(&wc))
        return false;

    DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
    DWORD dwStyle   = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX;

    if(fullscreen)
    {
        dwExStyle   = WS_EX_APPWINDOW;
        dwStyle     = WS_POPUP;

        EnumDisplaySettings(0, ENUM_CURRENT_SETTINGS, &dm_prev);
    }
    else
    {
        // Bei Fensteranwendung die Breiten und Hoehen der Fensterrahmen, Titelleiste draufaddieren
        width += 2 * GetSystemMetrics(SM_CXFIXEDFRAME);
        height += 2 * GetSystemMetrics(SM_CXFIXEDFRAME) + GetSystemMetrics(SM_CYCAPTION);
    }

    // Fenster erstellen
    screen = CreateWindowExW(dwExStyle, wTitle.c_str(), wTitle.c_str(), dwStyle, CW_USEDEFAULT, CW_USEDEFAULT, width, height, NULL, NULL, GetModuleHandle(NULL), NULL);

    if(screen == NULL)
        return false;

    SetClipboardViewer(screen);

    std::stringstream title;
    title << GetWindowTitle() << " - v" << GetWindowVersion() << "-" << GetWindowRevisionShort();

    wTitle = AnsiToUtf8(title.str().c_str());

    SetWindowTextW(screen, wTitle.c_str());
    SetWindowTextW(GetConsoleWindow(), wTitle.c_str());

    // Pixelformat zuweisen
    GLuint PixelFormat;
    static PIXELFORMATDESCRIPTOR pfd =
    {
        sizeof(PIXELFORMATDESCRIPTOR),
        1,
        PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
        PFD_TYPE_RGBA,
        8, // 8 Bit
        8, // red
        0,
        8, // green
        0,
        8, // blue
        0,
        8, // alpha
        0,
        0,
        0,
        0,
        0,
        0,
        32, // 32 Bit
        0,
        0,
        PFD_MAIN_PLANE,
        0,
        0,
        0,
        0
    };

    screen_dc = GetDC(screen);
    if(screen_dc == NULL)
        return false;

    // Pixelformat auswaehlen
    PixelFormat = ChoosePixelFormat(screen_dc, &pfd);
    if(PixelFormat == 0)
        return false;

    // Pixelformat zuweisen
    if(!SetPixelFormat(screen_dc, PixelFormat, &pfd))
        return false;

    // Renderingkontext erstellen
    screen_rc = wglCreateContext(screen_dc);
    if(screen_rc == NULL)
        return false;

    // Renderingkontext aktivieren
    if(!wglMakeCurrent(screen_dc, screen_rc))
        return false;

    // Mauscursor ausblenden
    ShowCursor(FALSE);

    // Bei Fullscreen Aufloesung umstellen
    if(fullscreen)
    {
        // Aktuelle Framerate holen und die spaeter dann benutzen
        DEVMODE prev;
        EnumDisplaySettings(0, ENUM_CURRENT_SETTINGS, &prev);

        DEVMODE dm;
        memset(&dm, 0, sizeof(dm));
        dm.dmSize = sizeof(dm);
        dm.dmFields = DM_DISPLAYFREQUENCY | DM_PELSWIDTH | DM_PELSHEIGHT;
        dm.dmDisplayFrequency = prev.dmDisplayFrequency;
        dm.dmPelsWidth = width;
        dm.dmPelsHeight = height;

        ChangeDisplaySettings(&dm, CDS_FULLSCREEN);
    }

    this->screenWidth  = width;
    this->screenHeight = height;
    this->isFullscreen_ = fullscreen;

    // Das Fenster anzeigen
    ShowWindow(screen, SW_SHOW);
    // Das Fenster in den Vordergrund rcken
    SetForegroundWindow(screen);
    // Dem Fenster den Eingabefokus geben
    SetFocus(screen);

    return true;
}
Пример #29
0
LRESULT CALLBACK FromFileDLG(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) 
{
	HWND hWnd;
	static FINDREPLACE find;
	static char findbuf[256];
	static unsigned char *file;
	static HWND hTool, hClip, hStatus;
	static RECT rOld;
	CHARFORMAT2 chars;

	if (message == WM_FINDMSGSTRING)
	{
		FINDREPLACE *fr = (FINDREPLACE *)lParam;

		if (fr->Flags & FR_FINDNEXT)
		{
			HWND hRich = GetDlgItem(hDlg, IDC_TEXT);
			DWORD flags=0;
			FINDTEXTEX ft;
			CHARRANGE chrg;

			if (fr->Flags & FR_DOWN)
				flags |= FR_DOWN;
			if (fr->Flags & FR_MATCHCASE)
				flags |= FR_MATCHCASE;
			if (fr->Flags & FR_WHOLEWORD)
				flags |= FR_WHOLEWORD;
			ft.lpstrText = fr->lpstrFindWhat;
			SendMessage(hRich, EM_EXGETSEL, 0, (LPARAM)&chrg);
			if (flags & FR_DOWN)
			{
				ft.chrg.cpMin = chrg.cpMax;
				ft.chrg.cpMax = -1;
			}
			else
			{
				ft.chrg.cpMin = chrg.cpMin;
				ft.chrg.cpMax = -1;
			}
			if (SendMessage(hRich, EM_FINDTEXTEX, flags, (LPARAM)&ft) == -1)
				MessageBox(NULL, "UnrealIRCd has finished searching the document",
					"Find", MB_ICONINFORMATION|MB_OK);
			else
			{
				SendMessage(hRich, EM_EXSETSEL, 0, (LPARAM)&(ft.chrgText));
				SendMessage(hRich, EM_SCROLLCARET, 0, 0);
				SetFocus(hRich);
			}
		}
		return TRUE;
	}
	switch (message) 
	{
		case WM_INITDIALOG: 
		{
			int fd,len;
			char *buffer, *string;
			EDITSTREAM edit;
			StreamIO *stream = MyMallocEx(sizeof(StreamIO));
			unsigned char szText[256];
			struct stat sb;
			HWND hWnd = GetDlgItem(hDlg, IDC_TEXT), hTip;
			file = (unsigned char *)lParam;
			if (file)
				wsprintf(szText, "UnrealIRCd Editor - %s", file);
			else 
				strcpy(szText, "UnrealIRCd Editor - New File");
			SetWindowText(hDlg, szText);
			lpfnOldWndProc = (FARPROC)SetWindowLong(hWnd, GWL_WNDPROC, (DWORD)RESubClassFunc);
			hTool = DrawToolbar(hInst, hDlg);
			hStatus = DrawStatusbar(hInst, hDlg, IDC_STATUS);
			SendMessage(hWnd, EM_SETEVENTMASK, 0, (LPARAM)ENM_SELCHANGE);
			chars.cbSize = sizeof(CHARFORMAT2);
			chars.dwMask = CFM_FACE;
			strcpy(chars.szFaceName,"Fixedsys");
			SendMessage(hWnd, EM_SETCHARFORMAT, (WPARAM)SCF_ALL, (LPARAM)&chars);
			if ((fd = open(file, _O_RDONLY|_O_BINARY)) != -1) 
			{
				fstat(fd,&sb);
				/* Only allocate the amount we need */
				buffer = MyMallocEx(sb.st_size+1);
				len = read(fd, buffer, sb.st_size);
				buffer[len] = 0;
				len = CountRTFSize(buffer)+1;
				string = MyMallocEx(len);
				IRCToRTF(buffer,string);
				RTFBuf = string;
				len--;
				stream->size = &len;
				stream->buffer = &RTFBuf;
				edit.dwCookie = (UINT)stream;
				edit.pfnCallback = SplitIt;
				SendMessage(hWnd, EM_EXLIMITTEXT, 0, (LPARAM)0x7FFFFFFF);
				SendMessage(hWnd, EM_STREAMIN, (WPARAM)SF_RTF|SFF_PLAINRTF, (LPARAM)&edit);
				SendMessage(hWnd, EM_SETMODIFY, (WPARAM)FALSE, 0);
				SendMessage(hWnd, EM_EMPTYUNDOBUFFER, 0, 0);
				close(fd);
				RTFBuf = NULL;
				free(buffer);
				free(string);
				free(stream);
				hClip = SetClipboardViewer(hDlg);
				if (SendMessage(hWnd, EM_CANPASTE, 0, 0)) 
					SendMessage(hTool, TB_ENABLEBUTTON, (WPARAM)IDM_PASTE, (LPARAM)MAKELONG(TRUE,0));
				else
					SendMessage(hTool, TB_ENABLEBUTTON, (WPARAM)IDM_PASTE, (LPARAM)MAKELONG(FALSE,0));
				SendMessage(hTool, TB_ENABLEBUTTON, (WPARAM)IDM_UNDO, (LPARAM)MAKELONG(FALSE,0));
				wsprintf(szText, "Line: 1");
				SetWindowText(hStatus, szText);
			}
			return TRUE;
		}
		case WM_WINDOWPOSCHANGING:
		{
			GetClientRect(hDlg, &rOld);
			return FALSE;
		}
		case WM_SIZE:
		{
			DWORD new_width, new_height;
			HWND hRich;
			RECT rOldRich;
			DWORD old_width, old_height;
			DWORD old_rich_width, old_rich_height;
			if (hDlg == hFind)
				return FALSE;
			new_width =  LOWORD(lParam);
			new_height = HIWORD(lParam);
			hRich  = GetDlgItem(hDlg, IDC_TEXT);
			SendMessage(hStatus, WM_SIZE, 0, 0);
			SendMessage(hTool, TB_AUTOSIZE, 0, 0);
			old_width = rOld.right-rOld.left;
			old_height = rOld.bottom-rOld.top;
			new_width = new_width - old_width;
			new_height = new_height - old_height;
			GetWindowRect(hRich, &rOldRich);
			old_rich_width = rOldRich.right-rOldRich.left;
			old_rich_height = rOldRich.bottom-rOldRich.top;
			SetWindowPos(hRich, NULL, 0, 0, old_rich_width+new_width, 
				old_rich_height+new_height,
				SWP_NOMOVE|SWP_NOREPOSITION|SWP_NOZORDER);
			bzero(&rOld, sizeof(RECT));
			return TRUE;
		} 

		case WM_NOTIFY:
			switch (((NMHDR *)lParam)->code) 
			{
				case EN_SELCHANGE: 
				{
					HWND hWnd = GetDlgItem(hDlg, IDC_TEXT);
					DWORD start, end, currline;
					static DWORD prevline = 0;
					unsigned char buffer[512];
					chars.cbSize = sizeof(CHARFORMAT2);
					SendMessage(hWnd, EM_GETCHARFORMAT, (WPARAM)SCF_SELECTION, (LPARAM)&chars);
					if (chars.dwMask & CFM_BOLD && chars.dwEffects & CFE_BOLD)
						SendMessage(hTool, TB_CHECKBUTTON, (WPARAM)IDC_BOLD, (LPARAM)MAKELONG(TRUE,0));
					else
						SendMessage(hTool, TB_CHECKBUTTON, (WPARAM)IDC_BOLD, (LPARAM)MAKELONG(FALSE,0));
					if (chars.dwMask & CFM_UNDERLINE && chars.dwEffects & CFE_UNDERLINE)
						SendMessage(hTool, TB_CHECKBUTTON, (WPARAM)IDC_UNDERLINE, (LPARAM)MAKELONG(TRUE,0));
					else
						SendMessage(hTool, TB_CHECKBUTTON, (WPARAM)IDC_UNDERLINE, (LPARAM)MAKELONG(FALSE,0));
					SendMessage(hWnd, EM_GETSEL,(WPARAM)&start, (LPARAM)&end);
					if (start == end) 
					{
						SendMessage(hTool, TB_ENABLEBUTTON, (WPARAM)IDM_COPY, (LPARAM)MAKELONG(FALSE,0));
						SendMessage(hTool, TB_ENABLEBUTTON, (WPARAM)IDM_CUT, (LPARAM)MAKELONG(FALSE,0));
					}
					else 
					{
						SendMessage(hTool, TB_ENABLEBUTTON, (WPARAM)IDM_COPY, (LPARAM)MAKELONG(TRUE,0));
						SendMessage(hTool, TB_ENABLEBUTTON, (WPARAM)IDM_CUT, (LPARAM)MAKELONG(TRUE,0));
					}
					if (SendMessage(hWnd, EM_CANUNDO, 0, 0)) 
						SendMessage(hTool, TB_ENABLEBUTTON, (WPARAM)IDM_UNDO, (LPARAM)MAKELONG(TRUE,0));
					else
						SendMessage(hTool, TB_ENABLEBUTTON, (WPARAM)IDM_UNDO, (LPARAM)MAKELONG(FALSE,0));
					if (SendMessage(hWnd, EM_CANREDO, 0, 0)) 
						SendMessage(hTool, TB_ENABLEBUTTON, (WPARAM)IDM_REDO, (LPARAM)MAKELONG(TRUE,0));
					else
						SendMessage(hTool, TB_ENABLEBUTTON, (WPARAM)IDM_REDO, (LPARAM)MAKELONG(FALSE,0));
					currline = SendMessage(hWnd, EM_LINEFROMCHAR, (WPARAM)-1, 0);
					currline++;
					if (currline != prevline) 
					{
						wsprintf(buffer, "Line: %d", currline);
						SetWindowText(hStatus, buffer);
						prevline = currline;
					}
				return TRUE;
			}
			case TTN_GETDISPINFO: 
			{
				LPTOOLTIPTEXT lpttt = (LPTOOLTIPTEXT) lParam;
				lpttt->hinst = NULL;
				switch (lpttt->hdr.idFrom) 
				{
					case IDM_NEW:
						strcpy(lpttt->szText, "New");
						break;
					case IDM_SAVE:
						strcpy(lpttt->szText, "Save");
						break;
					case IDM_CUT:
						strcpy(lpttt->szText, "Cut");
						break;
					case IDM_COPY:
						strcpy(lpttt->szText, "Copy");
						break;
					case IDM_PASTE:
						strcpy(lpttt->szText, "Paste");
						break;
					case IDM_UNDO:
						strcpy(lpttt->szText, "Undo");
						break;
					case IDM_REDO:
						strcpy(lpttt->szText, "Redo");
						break;
					case IDC_BOLD:
						strcpy(lpttt->szText, "Bold");
						break;
					case IDC_UNDERLINE:
						strcpy(lpttt->szText, "Underline");
						break;
					case IDC_COLOR:
						strcpy(lpttt->szText, "Text Color");
						break;
					case IDC_BGCOLOR:
						strcpy(lpttt->szText, "Background Color");
						break;
					case IDC_GOTO:
						strcpy(lpttt->szText, "Goto");
						break;
					case IDC_FIND:
						strcpy(lpttt->szText, "Find");
						break;
				}
				return TRUE;
			}
			case NM_DBLCLK:
				DialogBox(hInst, "GOTO", hDlg, (DLGPROC)GotoDLG);
				return (TRUE);
		}
				
				return (TRUE);
		case WM_COMMAND:
			if (LOWORD(wParam) == IDC_BOLD) 
			{
				hWnd = GetDlgItem(hDlg, IDC_TEXT);
				if (SendMessage(hTool, TB_ISBUTTONCHECKED, (WPARAM)IDC_BOLD, (LPARAM)0) != 0) 
				{
					chars.cbSize = sizeof(CHARFORMAT2);
					chars.dwMask = CFM_BOLD;
					chars.dwEffects = CFE_BOLD;
					SendMessage(hWnd, EM_SETCHARFORMAT, (WPARAM)SCF_SELECTION, (LPARAM)&chars);
					SendMessage(hWnd, EM_HIDESELECTION, 0, 0);
					SetFocus(hWnd);
				}
				else 
				{
					chars.cbSize = sizeof(CHARFORMAT2);
					chars.dwMask = CFM_BOLD;
					chars.dwEffects = 0;
					SendMessage(hWnd, EM_SETCHARFORMAT, (WPARAM)SCF_SELECTION, (LPARAM)&chars);
					SendMessage(hWnd, EM_HIDESELECTION, 0, 0);
					SetFocus(hWnd);
				}
				return TRUE;
			}
			else if (LOWORD(wParam) == IDC_UNDERLINE) 
			{
				hWnd = GetDlgItem(hDlg, IDC_TEXT);
				if (SendMessage(hTool, TB_ISBUTTONCHECKED, (WPARAM)IDC_UNDERLINE, (LPARAM)0) != 0) 
				{
					chars.cbSize = sizeof(CHARFORMAT2);
					chars.dwMask = CFM_UNDERLINETYPE;
					chars.bUnderlineType = CFU_UNDERLINE;
					SendMessage(hWnd, EM_SETCHARFORMAT, (WPARAM)SCF_SELECTION, (LPARAM)&chars);
					SendMessage(hWnd, EM_HIDESELECTION, 0, 0);
					SetFocus(hWnd);
				}
				else 
				{
					chars.cbSize = sizeof(CHARFORMAT2);
					chars.dwMask = CFM_UNDERLINETYPE;
					chars.bUnderlineType = CFU_UNDERLINENONE;
					SendMessage(hWnd, EM_SETCHARFORMAT, (WPARAM)SCF_SELECTION, (LPARAM)&chars);
					SendMessage(hWnd, EM_HIDESELECTION, 0, 0);
					SetFocus(hWnd);
				}
				return TRUE;
			}
			if (LOWORD(wParam) == IDC_COLOR) 
			{
				DialogBoxParam(hInst, "Color", hDlg, (DLGPROC)ColorDLG, (LPARAM)WM_USER+10);
				return 0;
			}
			if (LOWORD(wParam) == IDC_BGCOLOR)
			{
				DialogBoxParam(hInst, "Color", hDlg, (DLGPROC)ColorDLG, (LPARAM)WM_USER+11);
				return 0;
			}
			if (LOWORD(wParam) == IDC_GOTO)
			{
				DialogBox(hInst, "GOTO", hDlg, (DLGPROC)GotoDLG);
				return 0;
			}
			if (LOWORD(wParam) == IDC_FIND)
			{
				static FINDREPLACE fr;
				bzero(&fr, sizeof(FINDREPLACE));
				fr.lStructSize = sizeof(FINDREPLACE);
				fr.hwndOwner = hDlg;
				fr.lpstrFindWhat = findbuf;
				fr.wFindWhatLen = 255;
				hFind = FindText(&fr);
				return 0;
			}
				
			hWnd = GetDlgItem(hDlg, IDC_TEXT);
			if (LOWORD(wParam) == IDM_COPY) 
			{
				SendMessage(hWnd, WM_COPY, 0, 0);
				return 0;
			}
			if (LOWORD(wParam) == IDM_SELECTALL) 
			{
				SendMessage(hWnd, EM_SETSEL, 0, -1);
				return 0;
			}
			if (LOWORD(wParam) == IDM_PASTE) 
			{
				SendMessage(hWnd, WM_PASTE, 0, 0);
				return 0;
			}
			if (LOWORD(wParam) == IDM_CUT) 
			{
				SendMessage(hWnd, WM_CUT, 0, 0);
				return 0;
			}
			if (LOWORD(wParam) == IDM_UNDO) 
			{
				SendMessage(hWnd, EM_UNDO, 0, 0);
				return 0;
			}
			if (LOWORD(wParam) == IDM_REDO) 
			{
				SendMessage(hWnd, EM_REDO, 0, 0);
				return 0;
			}
			if (LOWORD(wParam) == IDM_DELETE) 
			{
				SendMessage(hWnd, WM_CLEAR, 0, 0);
				return 0;
			}
			if (LOWORD(wParam) == IDM_SAVE) 
			{
				int fd;
				EDITSTREAM edit;
				OPENFILENAME lpopen;
				if (!file) 
				{
					unsigned char path[MAX_PATH];
					path[0] = '\0';
					bzero(&lpopen, sizeof(OPENFILENAME));
					lpopen.lStructSize = sizeof(OPENFILENAME);
					lpopen.hwndOwner = hDlg;
					lpopen.lpstrFilter = NULL;
					lpopen.lpstrCustomFilter = NULL;
					lpopen.nFilterIndex = 0;
					lpopen.lpstrFile = path;
					lpopen.nMaxFile = MAX_PATH;
					lpopen.lpstrFileTitle = NULL;
					lpopen.lpstrInitialDir = CONFDIR;
					lpopen.lpstrTitle = NULL;
					lpopen.Flags = (OFN_ENABLESIZING|OFN_NONETWORKBUTTON|
							OFN_OVERWRITEPROMPT);
					if (GetSaveFileName(&lpopen))
						file = path;
					else
						break;
				}
				fd = open(file, _O_TRUNC|_O_CREAT|_O_WRONLY|_O_BINARY,_S_IWRITE);
				edit.dwCookie = 0;
				edit.pfnCallback = BufferIt;
				SendMessage(GetDlgItem(hDlg, IDC_TEXT), EM_STREAMOUT, (WPARAM)SF_RTF|SFF_PLAINRTF, (LPARAM)&edit);
				RTFToIRC(fd, RTFBuf, strlen(RTFBuf));
				free(RTFBuf);
				RTFBuf = NULL;
				SendMessage(GetDlgItem(hDlg, IDC_TEXT), EM_SETMODIFY, (WPARAM)FALSE, 0);
	
				return 0;
			}
			if (LOWORD(wParam) == IDM_NEW) 
			{
				unsigned char text[1024];
				BOOL newfile = FALSE;
				int ans;
				if (SendMessage(GetDlgItem(hDlg, IDC_TEXT), EM_GETMODIFY, 0, 0) != 0) 
				{
					sprintf(text, "The text in the %s file has changed.\r\n\r\nDo you want to save the changes?", file ? file : "new");
					ans = MessageBox(hDlg, text, "UnrealIRCd", MB_YESNOCANCEL|MB_ICONWARNING);
					if (ans == IDNO)
						newfile = TRUE;
					if (ans == IDCANCEL)
						return TRUE;
					if (ans == IDYES) 
					{
						SendMessage(hDlg, WM_COMMAND, MAKEWPARAM(IDM_SAVE,0), 0);
						newfile = TRUE;
					}
				}
				else
					newfile = TRUE;
				if (newfile == TRUE) 
				{
					unsigned char szText[256];
					file = NULL;
					strcpy(szText, "UnrealIRCd Editor - New File");
					SetWindowText(hDlg, szText);
					SetWindowText(GetDlgItem(hDlg, IDC_TEXT), NULL);
				}
				break;
			}
			break;
		case WM_USER+10: 
		{
			HWND hWnd = GetDlgItem(hDlg, IDC_TEXT);
			EndDialog((HWND)lParam, TRUE);
			chars.cbSize = sizeof(CHARFORMAT2);
			chars.dwMask = CFM_COLOR;
			chars.crTextColor = (COLORREF)wParam;
			SendMessage(hWnd, EM_SETCHARFORMAT, (WPARAM)SCF_SELECTION, (LPARAM)&chars);
			SendMessage(hWnd, EM_HIDESELECTION, 0, 0);
			SetFocus(hWnd);
			break;
		}
		case WM_USER+11: 
		{
			HWND hWnd = GetDlgItem(hDlg, IDC_TEXT);
			EndDialog((HWND)lParam, TRUE);
			chars.cbSize = sizeof(CHARFORMAT2);
			chars.dwMask = CFM_BACKCOLOR;
			chars.crBackColor = (COLORREF)wParam;
			SendMessage(hWnd, EM_SETCHARFORMAT, (WPARAM)SCF_SELECTION, (LPARAM)&chars);
			SendMessage(hWnd, EM_HIDESELECTION, 0, 0);
			SetFocus(hWnd);
			break;
		}
		case WM_CHANGECBCHAIN:
			if ((HWND)wParam == hClip)
				hClip = (HWND)lParam;
			else
				SendMessage(hClip, WM_CHANGECBCHAIN, wParam, lParam);
			break;
		case WM_DRAWCLIPBOARD:
			if (SendMessage(GetDlgItem(hDlg, IDC_TEXT), EM_CANPASTE, 0, 0)) 
				SendMessage(hTool, TB_ENABLEBUTTON, (WPARAM)IDM_PASTE, (LPARAM)MAKELONG(TRUE,0));
			else
				SendMessage(hTool, TB_ENABLEBUTTON, (WPARAM)IDM_PASTE, (LPARAM)MAKELONG(FALSE,0));
			SendMessage(hClip, WM_DRAWCLIPBOARD, wParam, lParam);
			break;
		case WM_CLOSE: 
		{
			unsigned char text[256];
			int ans;
			if (SendMessage(GetDlgItem(hDlg, IDC_TEXT), EM_GETMODIFY, 0, 0) != 0) 
			{
				sprintf(text, "The text in the %s file has changed.\r\n\r\nDo you want to save the changes?", file ? file : "new");
				ans = MessageBox(hDlg, text, "UnrealIRCd", MB_YESNOCANCEL|MB_ICONWARNING);
				if (ans == IDNO)
					EndDialog(hDlg, TRUE);
				if (ans == IDCANCEL)
					return TRUE;
				if (ans == IDYES) 
				{
					SendMessage(hDlg, WM_COMMAND, MAKEWPARAM(IDM_SAVE,0), 0);
					EndDialog(hDlg, TRUE);
				}
			}
			else
				EndDialog(hDlg, TRUE);
			break;
		}
		case WM_DESTROY:
			ChangeClipboardChain(hDlg, hClip);
			break;
	}

	return FALSE;
}
Пример #30
0
//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_PAINT    - Paint the main window
//  WM_DESTROY  - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	PAINTSTRUCT ps;
	HDC hdc;
	TCHAR greeting[] = _T("Hello, World!");
	RECT rect;

	HANDLE hCbMem;
	bool bAvail;
	HWND hwndNxtVwr = NULL;
	//LPSTR lpCbMem;
	//LPSTR lpProgMem;
	//LPSTR lpCbMem;
	//LPSTR lpProgMem;
	char* lpCbMem;
	char* lpProgMem = NULL;
	HGLOBAL hProgMem;

	switch (message)
	{
	case WM_CREATE:
		hwndNxtVwr = SetClipboardViewer(hWnd);
		break;

	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		GetClientRect(hWnd, &rect);
		
		bAvail = IsClipboardFormatAvailable(CF_TEXT); //czy schowek zawiera dane 
		if (bAvail) {
			OpenClipboard(hWnd);			
			hCbMem = GetClipboardData(CF_TEXT); 
			//	if (hCbMem != NULL) altenatywa dla dwóch linijek wy¿ej		
			
			hProgMem = GlobalAlloc(GHND, GlobalSize(hCbMem));
			if (hProgMem != NULL) {
				//lpCbMem = (LPSTR)GlobalLock(hCbMem);
				//lpProgMem = (LPSTR)GlobalLock(hProgMem);
				lpCbMem = (char*)GlobalLock(hCbMem);
				lpProgMem = (char*)GlobalLock(hProgMem);

				//lstrcpy(lpProgMem, lpCbMem);
				
				strcpy(lpProgMem, lpCbMem);
				
				size_t length = strlen(lpProgMem);
				wchar_t wtext[2000];
				mbstowcs(wtext, lpProgMem, strlen(lpProgMem) + 1);//Plus null
				
				DrawText(hdc, (LPCWSTR)wtext,
					-1, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER);


				GlobalUnlock(hCbMem);
				GlobalUnlock(hProgMem);
			}
	
			CloseClipboard();
		}

		GetClientRect(hWnd, &rect);
		EndPaint(hWnd, &ps);
		break;

	case WM_DRAWCLIPBOARD:
		if (hwndNxtVwr != NULL)
			/* jeœli nie jestem ostatni w ³añcuchu to muszê powiadomiæ
			nastêpny CbV */
		{
			SendMessage(hwndNxtVwr, message, wParam, lParam);
		}
		InvalidateRect(hWnd, NULL, TRUE); /* wygeneruje WM_PAINT */
		break;
	case WM_CHANGECBCHAIN:
		if ((HWND)wParam == hwndNxtVwr) /* jestem poprzednikiem usuwaj¹cego siê ? */
		{
			hwndNxtVwr = (HWND)LOWORD(lParam); /* handle nowego nastêpnika */
		}
		else
		{
			if (hwndNxtVwr != NULL) /* jeœli nie jestem ostatni w ³añcuchu to */
			{ /* muszê powiadomiæ mojego nastêpnika */
				SendMessage(hwndNxtVwr, message, wParam, lParam);
			}
		}
		break;
	case WM_DESTROY:
		ChangeClipboardChain(hWnd, hwndNxtVwr);
		PostQuitMessage(0);
		break;
	case WM_COMMAND:
		if ((HWND)lParam == hwndButton) {

		//	TCHAR pStr[128];
		//	GetDlgItemText(hWnd, 101, pStr, 128);

			int wLen = SendMessage(editctl, WM_GETTEXTLENGTH, 0, 0);
			LPSTR textIn = (LPSTR)malloc(wLen + 1);
			SendMessage(editctl, WM_GETTEXT, wLen + 1, LPARAM(textIn));

			HANDLE hGlMem = GlobalAlloc(GHND, (DWORD)wLen + 1);

		
			LPSTR lpGlMem = (LPSTR)GlobalLock(hGlMem);
			
			for(int i = 0; i < wLen; i++)
			{
				*lpGlMem++ = textIn[i];
			}
			
			//for (int i = 0; i < wLen; *lpGlMem++ = *textIn && i++);

			GlobalUnlock(hGlMem);

			OpenClipboard(hWnd);
			EmptyClipboard();
			SetClipboardData(CF_TEXT, hGlMem);
			CloseClipboard();
		}

		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
		break;
	}

	return 0;
}