int winClipboardFlushXEvents(HWND hwnd, int iWindow, Display * pDisplay, Bool fUseUnicode) { static Atom atomLocalProperty; static Atom atomCompoundText; static Atom atomUTF8String; static Atom atomTargets; static int generation; if (generation != serverGeneration) { generation = serverGeneration; atomLocalProperty = XInternAtom(pDisplay, WIN_LOCAL_PROPERTY, False); atomUTF8String = XInternAtom(pDisplay, "UTF8_STRING", False); atomCompoundText = XInternAtom(pDisplay, "COMPOUND_TEXT", False); atomTargets = XInternAtom(pDisplay, "TARGETS", False); } /* Process all pending events */ while (XPending(pDisplay)) { XTextProperty xtpText = { 0 }; XEvent event; XSelectionEvent eventSelection; unsigned long ulReturnBytesLeft; char *pszReturnData = NULL; char *pszGlobalData = NULL; int iReturn; HGLOBAL hGlobal = NULL; XICCEncodingStyle xiccesStyle; int iConvertDataLen = 0; char *pszConvertData = NULL; char *pszTextList[2] = { NULL }; int iCount; char **ppszTextList = NULL; wchar_t *pwszUnicodeStr = NULL; int iUnicodeLen = 0; int iReturnDataLen = 0; int i; Bool fAbort = FALSE; Bool fCloseClipboard = FALSE; Bool fSetClipboardData = TRUE; /* Get the next event - will not block because one is ready */ XNextEvent(pDisplay, &event); /* Branch on the event type */ switch (event.type) { /* * SelectionRequest */ case SelectionRequest: { char *pszAtomName = NULL; winDebug("SelectionRequest - target %d\n", event.xselectionrequest.target); pszAtomName = XGetAtomName(pDisplay, event.xselectionrequest.target); winDebug("SelectionRequest - Target atom name %s\n", pszAtomName); XFree(pszAtomName); pszAtomName = NULL; } /* Abort if invalid target type */ if (event.xselectionrequest.target != XA_STRING && event.xselectionrequest.target != atomUTF8String && event.xselectionrequest.target != atomCompoundText && event.xselectionrequest.target != atomTargets) { /* Abort */ fAbort = TRUE; goto winClipboardFlushXEvents_SelectionRequest_Done; } /* Handle targets type of request */ if (event.xselectionrequest.target == atomTargets) { Atom atomTargetArr[] = { atomTargets, atomCompoundText, atomUTF8String, XA_STRING }; /* Try to change the property */ iReturn = XChangeProperty(pDisplay, event.xselectionrequest.requestor, event.xselectionrequest.property, XA_ATOM, 32, PropModeReplace, (unsigned char *) atomTargetArr, (sizeof(atomTargetArr) / sizeof(atomTargetArr[0]))); if (iReturn == BadAlloc || iReturn == BadAtom || iReturn == BadMatch || iReturn == BadValue || iReturn == BadWindow) { ErrorF("winClipboardFlushXEvents - SelectionRequest - " "XChangeProperty failed: %d\n", iReturn); } /* Setup selection notify xevent */ eventSelection.type = SelectionNotify; eventSelection.send_event = True; eventSelection.display = pDisplay; eventSelection.requestor = event.xselectionrequest.requestor; eventSelection.selection = event.xselectionrequest.selection; eventSelection.target = event.xselectionrequest.target; eventSelection.property = event.xselectionrequest.property; eventSelection.time = event.xselectionrequest.time; /* * Notify the requesting window that * the operation has completed */ iReturn = XSendEvent(pDisplay, eventSelection.requestor, False, 0L, (XEvent *) &eventSelection); if (iReturn == BadValue || iReturn == BadWindow) { ErrorF("winClipboardFlushXEvents - SelectionRequest - " "XSendEvent () failed\n"); } break; } /* Close clipboard if we have it open already */ if (GetOpenClipboardWindow() == hwnd) { CloseClipboard(); } /* Access the clipboard */ if (!OpenClipboard(hwnd)) { ErrorF("winClipboardFlushXEvents - SelectionRequest - " "OpenClipboard () failed: %08lx\n", GetLastError()); /* Abort */ fAbort = TRUE; goto winClipboardFlushXEvents_SelectionRequest_Done; } /* Indicate that clipboard was opened */ fCloseClipboard = TRUE; /* Check that clipboard format is available */ if (fUseUnicode && !IsClipboardFormatAvailable(CF_UNICODETEXT)) { static int count; /* Hack to stop acroread spamming the log */ static HWND lasthwnd; /* I've not seen any other client get here repeatedly? */ if (hwnd != lasthwnd) count = 0; count++; if (count < 6) ErrorF("winClipboardFlushXEvents - CF_UNICODETEXT is not " "available from Win32 clipboard. Aborting %d.\n", count); lasthwnd = hwnd; /* Abort */ fAbort = TRUE; goto winClipboardFlushXEvents_SelectionRequest_Done; } else if (!fUseUnicode && !IsClipboardFormatAvailable(CF_TEXT)) { ErrorF("winClipboardFlushXEvents - CF_TEXT is not " "available from Win32 clipboard. Aborting.\n"); /* Abort */ fAbort = TRUE; goto winClipboardFlushXEvents_SelectionRequest_Done; } /* Setup the string style */ if (event.xselectionrequest.target == XA_STRING) xiccesStyle = XStringStyle; #ifdef X_HAVE_UTF8_STRING else if (event.xselectionrequest.target == atomUTF8String) xiccesStyle = XUTF8StringStyle; #endif else if (event.xselectionrequest.target == atomCompoundText) xiccesStyle = XCompoundTextStyle; else xiccesStyle = XStringStyle; /* Get a pointer to the clipboard text, in desired format */ if (fUseUnicode) { /* Retrieve clipboard data */ hGlobal = GetClipboardData(CF_UNICODETEXT); } else { /* Retrieve clipboard data */ hGlobal = GetClipboardData(CF_TEXT); } if (!hGlobal) { ErrorF("winClipboardFlushXEvents - SelectionRequest - " "GetClipboardData () failed: %08lx\n", GetLastError()); /* Abort */ fAbort = TRUE; goto winClipboardFlushXEvents_SelectionRequest_Done; } pszGlobalData = (char *) GlobalLock(hGlobal); /* Convert the Unicode string to UTF8 (MBCS) */ if (fUseUnicode) { iConvertDataLen = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR) pszGlobalData, -1, NULL, 0, NULL, NULL); /* NOTE: iConvertDataLen includes space for null terminator */ pszConvertData = (char *) malloc(iConvertDataLen); WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR) pszGlobalData, -1, pszConvertData, iConvertDataLen, NULL, NULL); } else { pszConvertData = strdup(pszGlobalData); iConvertDataLen = strlen(pszConvertData) + 1; } /* Convert DOS string to UNIX string */ winClipboardDOStoUNIX(pszConvertData, strlen(pszConvertData)); /* Setup our text list */ pszTextList[0] = pszConvertData; pszTextList[1] = NULL; /* Initialize the text property */ xtpText.value = NULL; xtpText.nitems = 0; /* Create the text property from the text list */ if (fUseUnicode) { #ifdef X_HAVE_UTF8_STRING iReturn = Xutf8TextListToTextProperty(pDisplay, pszTextList, 1, xiccesStyle, &xtpText); #endif } else { iReturn = XmbTextListToTextProperty(pDisplay, pszTextList, 1, xiccesStyle, &xtpText); } if (iReturn == XNoMemory || iReturn == XLocaleNotSupported) { ErrorF("winClipboardFlushXEvents - SelectionRequest - " "X*TextListToTextProperty failed: %d\n", iReturn); /* Abort */ fAbort = TRUE; goto winClipboardFlushXEvents_SelectionRequest_Done; } /* Free the converted string */ free(pszConvertData); pszConvertData = NULL; /* Copy the clipboard text to the requesting window */ iReturn = XChangeProperty(pDisplay, event.xselectionrequest.requestor, event.xselectionrequest.property, event.xselectionrequest.target, 8, PropModeReplace, xtpText.value, xtpText.nitems); if (iReturn == BadAlloc || iReturn == BadAtom || iReturn == BadMatch || iReturn == BadValue || iReturn == BadWindow) { ErrorF("winClipboardFlushXEvents - SelectionRequest - " "XChangeProperty failed: %d\n", iReturn); /* Abort */ fAbort = TRUE; goto winClipboardFlushXEvents_SelectionRequest_Done; } /* Release the clipboard data */ GlobalUnlock(hGlobal); pszGlobalData = NULL; fCloseClipboard = FALSE; CloseClipboard(); /* Clean up */ XFree(xtpText.value); xtpText.value = NULL; xtpText.nitems = 0; /* Setup selection notify event */ eventSelection.type = SelectionNotify; eventSelection.send_event = True; eventSelection.display = pDisplay; eventSelection.requestor = event.xselectionrequest.requestor; eventSelection.selection = event.xselectionrequest.selection; eventSelection.target = event.xselectionrequest.target; eventSelection.property = event.xselectionrequest.property; eventSelection.time = event.xselectionrequest.time; /* Notify the requesting window that the operation has completed */ iReturn = XSendEvent(pDisplay, eventSelection.requestor, False, 0L, (XEvent *) &eventSelection); if (iReturn == BadValue || iReturn == BadWindow) { ErrorF("winClipboardFlushXEvents - SelectionRequest - " "XSendEvent () failed\n"); /* Abort */ fAbort = TRUE; goto winClipboardFlushXEvents_SelectionRequest_Done; } winClipboardFlushXEvents_SelectionRequest_Done: /* Free allocated resources */ if (xtpText.value) { XFree(xtpText.value); xtpText.value = NULL; xtpText.nitems = 0; } free(pszConvertData); if (hGlobal && pszGlobalData) GlobalUnlock(hGlobal); /* * Send a SelectionNotify event to the requesting * client when we abort. */ if (fAbort) { /* Setup selection notify event */ eventSelection.type = SelectionNotify; eventSelection.send_event = True; eventSelection.display = pDisplay; eventSelection.requestor = event.xselectionrequest.requestor; eventSelection.selection = event.xselectionrequest.selection; eventSelection.target = event.xselectionrequest.target; eventSelection.property = None; eventSelection.time = event.xselectionrequest.time; /* Notify the requesting window that the operation is complete */ iReturn = XSendEvent(pDisplay, eventSelection.requestor, False, 0L, (XEvent *) &eventSelection); if (iReturn == BadValue || iReturn == BadWindow) { /* * Should not be a problem if XSendEvent fails because * the client may simply have exited. */ ErrorF("winClipboardFlushXEvents - SelectionRequest - " "XSendEvent () failed for abort event.\n"); } } /* Close clipboard if it was opened */ if (fCloseClipboard) { fCloseClipboard = FALSE; CloseClipboard(); } break; /* * SelectionNotify */ case SelectionNotify: winDebug("winClipboardFlushXEvents - SelectionNotify\n"); { char *pszAtomName; pszAtomName = XGetAtomName(pDisplay, event.xselection.selection); winDebug ("winClipboardFlushXEvents - SelectionNotify - ATOM: %s\n", pszAtomName); XFree(pszAtomName); } /* * Request conversion of UTF8 and CompoundText targets. */ if (event.xselection.property == None) { if (event.xselection.target == XA_STRING) { winDebug("winClipboardFlushXEvents - SelectionNotify - " "XA_STRING\n"); return WIN_XEVENTS_CONVERT; } else if (event.xselection.target == atomUTF8String) { winDebug("winClipboardFlushXEvents - SelectionNotify - " "Requesting conversion of UTF8 target.\n"); XConvertSelection(pDisplay, event.xselection.selection, XA_STRING, atomLocalProperty, iWindow, CurrentTime); /* Process the ConvertSelection event */ XFlush(pDisplay); return WIN_XEVENTS_CONVERT; } #ifdef X_HAVE_UTF8_STRING else if (event.xselection.target == atomCompoundText) { winDebug("winClipboardFlushXEvents - SelectionNotify - " "Requesting conversion of CompoundText target.\n"); XConvertSelection(pDisplay, event.xselection.selection, atomUTF8String, atomLocalProperty, iWindow, CurrentTime); /* Process the ConvertSelection event */ XFlush(pDisplay); return WIN_XEVENTS_CONVERT; } #endif else { ErrorF("winClipboardFlushXEvents - SelectionNotify - " "Unknown format. Cannot request conversion, " "aborting.\n"); break; } } /* Retrieve the size of the stored data */ iReturn = XGetWindowProperty(pDisplay, iWindow, atomLocalProperty, 0, 0, /* Don't get data, just size */ False, AnyPropertyType, &xtpText.encoding, &xtpText.format, &xtpText.nitems, &ulReturnBytesLeft, &xtpText.value); if (iReturn != Success) { ErrorF("winClipboardFlushXEvents - SelectionNotify - " "XGetWindowProperty () failed, aborting: %d\n", iReturn); break; } winDebug("SelectionNotify - returned data %d left %d\n", xtpText.nitems, ulReturnBytesLeft); /* Request the selection data */ iReturn = XGetWindowProperty(pDisplay, iWindow, atomLocalProperty, 0, ulReturnBytesLeft, False, AnyPropertyType, &xtpText.encoding, &xtpText.format, &xtpText.nitems, &ulReturnBytesLeft, &xtpText.value); if (iReturn != Success) { ErrorF("winClipboardFlushXEvents - SelectionNotify - " "XGetWindowProperty () failed, aborting: %d\n", iReturn); break; } { char *pszAtomName = NULL; winDebug("SelectionNotify - returned data %d left %d\n", xtpText.nitems, ulReturnBytesLeft); pszAtomName = XGetAtomName(pDisplay, xtpText.encoding); winDebug("Notify atom name %s\n", pszAtomName); XFree(pszAtomName); pszAtomName = NULL; } if (fUseUnicode) { #ifdef X_HAVE_UTF8_STRING /* Convert the text property to a text list */ iReturn = Xutf8TextPropertyToTextList(pDisplay, &xtpText, &ppszTextList, &iCount); #endif } else { iReturn = XmbTextPropertyToTextList(pDisplay, &xtpText, &ppszTextList, &iCount); } if (iReturn == Success || iReturn > 0) { /* Conversion succeeded or some unconvertible characters */ if (ppszTextList != NULL) { iReturnDataLen = 0; for (i = 0; i < iCount; i++) { iReturnDataLen += strlen(ppszTextList[i]); } pszReturnData = malloc(iReturnDataLen + 1); pszReturnData[0] = '\0'; for (i = 0; i < iCount; i++) { strcat(pszReturnData, ppszTextList[i]); } } else { ErrorF("winClipboardFlushXEvents - SelectionNotify - " "X*TextPropertyToTextList list_return is NULL.\n"); pszReturnData = malloc(1); pszReturnData[0] = '\0'; } } else { ErrorF("winClipboardFlushXEvents - SelectionNotify - " "X*TextPropertyToTextList returned: "); switch (iReturn) { case XNoMemory: ErrorF("XNoMemory\n"); break; case XLocaleNotSupported: ErrorF("XLocaleNotSupported\n"); break; case XConverterNotFound: ErrorF("XConverterNotFound\n"); break; default: ErrorF("%d\n", iReturn); break; } pszReturnData = malloc(1); pszReturnData[0] = '\0'; } /* Free the data returned from XGetWindowProperty */ if (ppszTextList) XFreeStringList(ppszTextList); ppszTextList = NULL; XFree(xtpText.value); xtpText.value = NULL; xtpText.nitems = 0; /* Convert the X clipboard string to DOS format */ winClipboardUNIXtoDOS(&pszReturnData, strlen(pszReturnData)); if (fUseUnicode) { /* Find out how much space needed to convert MBCS to Unicode */ iUnicodeLen = MultiByteToWideChar(CP_UTF8, 0, pszReturnData, -1, NULL, 0); /* Allocate memory for the Unicode string */ pwszUnicodeStr = (wchar_t *) malloc(sizeof(wchar_t) * (iUnicodeLen + 1)); if (!pwszUnicodeStr) { ErrorF("winClipboardFlushXEvents - SelectionNotify " "malloc failed for pwszUnicodeStr, aborting.\n"); /* Abort */ fAbort = TRUE; goto winClipboardFlushXEvents_SelectionNotify_Done; } /* Do the actual conversion */ MultiByteToWideChar(CP_UTF8, 0, pszReturnData, -1, pwszUnicodeStr, iUnicodeLen); /* Allocate global memory for the X clipboard data */ hGlobal = GlobalAlloc(GMEM_MOVEABLE, sizeof(wchar_t) * (iUnicodeLen + 1)); } else { pszConvertData = strdup(pszReturnData); iConvertDataLen = strlen(pszConvertData) + 1; /* Allocate global memory for the X clipboard data */ hGlobal = GlobalAlloc(GMEM_MOVEABLE, iConvertDataLen); } free(pszReturnData); /* Check that global memory was allocated */ if (!hGlobal) { ErrorF("winClipboardFlushXEvents - SelectionNotify " "GlobalAlloc failed, aborting: %ld\n", GetLastError()); /* Abort */ fAbort = TRUE; goto winClipboardFlushXEvents_SelectionNotify_Done; } /* Obtain a pointer to the global memory */ pszGlobalData = GlobalLock(hGlobal); if (pszGlobalData == NULL) { ErrorF("winClipboardFlushXEvents - Could not lock global " "memory for clipboard transfer\n"); /* Abort */ fAbort = TRUE; goto winClipboardFlushXEvents_SelectionNotify_Done; } /* Copy the returned string into the global memory */ if (fUseUnicode) { memcpy(pszGlobalData, pwszUnicodeStr, sizeof(wchar_t) * (iUnicodeLen + 1)); free(pwszUnicodeStr); pwszUnicodeStr = NULL; } else { strcpy(pszGlobalData, pszConvertData); free(pszConvertData); pszConvertData = NULL; } /* Release the pointer to the global memory */ GlobalUnlock(hGlobal); pszGlobalData = NULL; /* Push the selection data to the Windows clipboard */ if (fUseUnicode) SetClipboardData(CF_UNICODETEXT, hGlobal); else SetClipboardData(CF_TEXT, hGlobal); /* Flag that SetClipboardData has been called */ fSetClipboardData = FALSE; /* * NOTE: Do not try to free pszGlobalData, it is owned by * Windows after the call to SetClipboardData (). */ winClipboardFlushXEvents_SelectionNotify_Done: /* Free allocated resources */ if (ppszTextList) XFreeStringList(ppszTextList); if (xtpText.value) { XFree(xtpText.value); xtpText.value = NULL; xtpText.nitems = 0; } free(pszConvertData); free(pwszUnicodeStr); if (hGlobal && pszGlobalData) GlobalUnlock(hGlobal); if (fSetClipboardData) { SetClipboardData(CF_UNICODETEXT, NULL); SetClipboardData(CF_TEXT, NULL); } return WIN_XEVENTS_NOTIFY; case SelectionClear: winDebug("SelectionClear - doing nothing\n"); break; case PropertyNotify: break; case MappingNotify: break; default: ErrorF("winClipboardFlushXEvents - unexpected event type %d\n", event.type); break; } } return WIN_XEVENTS_SUCCESS; }
//--------------------------------------------------------------------------- bool TVPClipboardGetText(ttstr & text) { if(!OpenClipboard(Application->Handle)) return false; bool result = false; try { // select CF_UNICODETEXT or CF_TEXT UINT formats[2] = { CF_UNICODETEXT, CF_TEXT}; int format = GetPriorityClipboardFormat(formats, 2); if(format == CF_UNICODETEXT) { // try to read unicode text HGLOBAL hglb = (HGLOBAL)GetClipboardData(CF_UNICODETEXT); if(hglb != NULL) { const tjs_char *p = (const tjs_char *)GlobalLock(hglb); if(p) { try { text = ttstr(p); result = true; } catch(...) { GlobalUnlock(hglb); throw; } GlobalUnlock(hglb); } } } else if(format == CF_TEXT) { // try to read ansi text HGLOBAL hglb = (HGLOBAL)GetClipboardData(CF_TEXT); if(hglb != NULL) { const char *p = (const char *)GlobalLock(hglb); if(p) { try { text = ttstr(p); result = true; } catch(...) { GlobalUnlock(hglb); throw; } GlobalUnlock(hglb); } } } } catch(...) { CloseClipboard(); throw; } CloseClipboard(); return result; }
BOOL CHexEdit::PreTranslateMessage(MSG* pMsg) { // TODO: Add your specialized code here and/or call the base class int start,end; GetSel(start,end); CString text; this->GetWindowText(text); char head=0,second=0; if(text.GetLength()>0) head=text.GetAt(0); if(text.GetLength()>1) second=text.GetAt(1); bool bCut=true; if (pMsg->message == WM_KEYDOWN) { if (pMsg->wParam=='X') { if(::GetKeyState(VK_CONTROL) < 0) { //Cut if(second=='X'||second=='x'){ //does not allow cut first char if(start==0&&end==1) bCut=false; } if(bCut) return CEdit::PreTranslateMessage(pMsg); else return TRUE; } else return CEdit::PreTranslateMessage(pMsg); } else if(pMsg->wParam=='V') { if(::GetKeyState(VK_CONTROL)<0) { //Paste bool bPaste=true; if(!IsClipboardFormatAvailable(CF_TEXT)) bPaste=false; if(!this->OpenClipboard()) ::AfxMessageBox("Cannot open clipboard!"); HGLOBAL hglb; LPTSTR lptstr; hglb=GetClipboardData(CF_TEXT); if (hglb != NULL) { lptstr =(LPTSTR) GlobalLock(hglb); //Check invalid hex string if(!this->IsHexConvertableText(lptstr)) { bPaste=false; } } CloseClipboard(); if(!bPaste) return TRUE; else return CEdit::PreTranslateMessage(pMsg); } else return CEdit::PreTranslateMessage(pMsg); } else if(pMsg->wParam==VK_DELETE) { if(second=='X'||second=='x'){ //does not allow delete first char if(start==0&&end<=1) bCut=false; } if(bCut) return CEdit::PreTranslateMessage(pMsg); else return TRUE; } else return CEdit::PreTranslateMessage(pMsg); } else if (pMsg->message == WM_CHAR) { int c=(int)pMsg->wParam; if(pMsg->wParam<32) { if(pMsg->wParam==8&&(second=='x'||second=='X')&&head=='0'&&end==1) //does not allow to delete '0' before x return TRUE; else return CEdit::PreTranslateMessage(pMsg);//Control code } if(second=='x'||second=='X') { //does not allow to change head except select includes first and second if(start<=1&&end<=1) return TRUE; } if(start==1&&(c=='X'||c=='x')&&head=='0') {pMsg->wParam='x';return CEdit::PreTranslateMessage(pMsg);} else if(c>=48&&c<=57||c>='A'&&c<='F') return CEdit::PreTranslateMessage(pMsg); else if(c>='a'&&c<='f') {pMsg->wParam-=32; return CEdit::PreTranslateMessage(pMsg);} else return TRUE; } else return CEdit::PreTranslateMessage(pMsg); }
PyObject* PyImaging_GrabClipboardWin32(PyObject* self, PyObject* args) { int clip; HANDLE handle; int size; void* data; PyObject* result; int verbose = 0; /* debugging; will be removed in future versions */ if (!PyArg_ParseTuple(args, "|i", &verbose)) return NULL; clip = OpenClipboard(NULL); /* FIXME: check error status */ if (verbose) { UINT format = EnumClipboardFormats(0); char buffer[200]; char* result; while (format != 0) { if (GetClipboardFormatName(format, buffer, sizeof buffer) > 0) result = buffer; else switch (format) { case CF_BITMAP: result = "CF_BITMAP"; break; case CF_DIB: result = "CF_DIB"; break; case CF_DIF: result = "CF_DIF"; break; case CF_ENHMETAFILE: result = "CF_ENHMETAFILE"; break; case CF_HDROP: result = "CF_HDROP"; break; case CF_LOCALE: result = "CF_LOCALE"; break; case CF_METAFILEPICT: result = "CF_METAFILEPICT"; break; case CF_OEMTEXT: result = "CF_OEMTEXT"; break; case CF_OWNERDISPLAY: result = "CF_OWNERDISPLAY"; break; case CF_PALETTE: result = "CF_PALETTE"; break; case CF_PENDATA: result = "CF_PENDATA"; break; case CF_RIFF: result = "CF_RIFF"; break; case CF_SYLK: result = "CF_SYLK"; break; case CF_TEXT: result = "CF_TEXT"; break; case CF_WAVE: result = "CF_WAVE"; break; case CF_TIFF: result = "CF_TIFF"; break; case CF_UNICODETEXT: result = "CF_UNICODETEXT"; break; default: sprintf(buffer, "[%d]", format); result = buffer; break; } printf("%s (%d)\n", result, format); format = EnumClipboardFormats(format); } } handle = GetClipboardData(CF_DIB); if (!handle) { /* FIXME: add CF_HDROP support to allow cut-and-paste from the explorer */ CloseClipboard(); Py_INCREF(Py_None); return Py_None; } size = GlobalSize(handle); data = GlobalLock(handle); #if 0 /* calculate proper size for string formats */ if (format == CF_TEXT || format == CF_OEMTEXT) size = strlen(data); else if (format == CF_UNICODETEXT) size = wcslen(data) * 2; #endif result = PyBytes_FromStringAndSize(data, size); GlobalUnlock(handle); CloseClipboard(); return result; }
/* * maybe this should be integrated with the default message loop - or maybe not ;-) */ static LRESULT CALLBACK inner_clipboard_window_procedure (HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { switch (message) { case WM_DESTROY: /* remove us from chain */ { ChangeClipboardChain (hwnd, _hwnd_next_viewer); PostQuitMessage (0); return 0; } case WM_CHANGECBCHAIN: { HWND hwndRemove = (HWND) wparam; /* handle of window being removed */ HWND hwndNext = (HWND) lparam; /* handle of next window in chain */ if (hwndRemove == _hwnd_next_viewer) _hwnd_next_viewer = hwndNext == hwnd ? NULL : hwndNext; else if (_hwnd_next_viewer != NULL) return SendMessage (_hwnd_next_viewer, message, wparam, lparam); return 0; } case WM_CLIPBOARDUPDATE: case WM_DRAWCLIPBOARD: { int success; HWND hwndOwner; #ifdef G_ENABLE_DEBUG UINT nFormat = 0; #endif GdkEvent *event; GdkWindow *owner; success = OpenClipboard (hwnd); if (!success) { g_warning ("Failed to OpenClipboard on window handle %p", hwnd); return 0; } hwndOwner = GetClipboardOwner (); owner = gdk_win32_window_lookup_for_display (_gdk_display, hwndOwner); if (owner == NULL) owner = gdk_win32_window_foreign_new_for_display (_gdk_display, hwndOwner); GDK_NOTE (DND, g_print (" drawclipboard owner: %p", hwndOwner)); #ifdef G_ENABLE_DEBUG if (_gdk_debug_flags & GDK_DEBUG_DND) { while ((nFormat = EnumClipboardFormats (nFormat)) != 0) g_print ("%s ", _gdk_win32_cf_to_string (nFormat)); } #endif GDK_NOTE (DND, g_print (" \n")); event = gdk_event_new (GDK_OWNER_CHANGE); event->owner_change.window = gdk_get_default_root_window (); event->owner_change.owner = owner; event->owner_change.reason = GDK_OWNER_CHANGE_NEW_OWNER; event->owner_change.selection = GDK_SELECTION_CLIPBOARD; event->owner_change.time = _gdk_win32_get_next_tick (0); event->owner_change.selection_time = GDK_CURRENT_TIME; _gdk_win32_append_event (event); CloseClipboard (); if (_hwnd_next_viewer != NULL) return SendMessage (_hwnd_next_viewer, message, wparam, lparam); /* clear error to avoid confusing SetClipboardViewer() return */ SetLastError (0); return 0; } default: /* Otherwise call DefWindowProcW(). */ GDK_NOTE (EVENTS, g_print (" DefWindowProcW")); return DefWindowProc (hwnd, message, wparam, lparam); } }
static LRESULT CALLBACK cliprdr_proc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { static cliprdrContext *cliprdr = NULL; switch (Msg) { case WM_CREATE: cliprdr = (cliprdrContext *)((CREATESTRUCT *)lParam)->lpCreateParams; cliprdr->hwndNextViewer = SetClipboardViewer(hWnd); if (cliprdr->hwndNextViewer == NULL && GetLastError() != 0) { DEBUG_CLIPRDR("error: SetClipboardViewer failed with 0x%0x.", GetLastError()); } cliprdr->hwndClipboard = hWnd; break; case WM_CLOSE: ChangeClipboardChain(hWnd, cliprdr->hwndNextViewer); break; case WM_CHANGECBCHAIN: if (cliprdr->hwndNextViewer == (HWND)wParam) { cliprdr->hwndNextViewer = (HWND)lParam; } else if (cliprdr->hwndNextViewer != NULL) { SendMessage(cliprdr->hwndNextViewer, Msg, wParam, lParam); } break; case WM_DRAWCLIPBOARD: if (cliprdr->channel_initialized) { if ((GetClipboardOwner() != cliprdr->hwndClipboard) && (S_FALSE == OleIsCurrentClipboard(cliprdr->data_obj))) { if (!cliprdr->hmem) { cliprdr->hmem = GlobalFree(cliprdr->hmem); } cliprdr_send_format_list(cliprdr); } } if (cliprdr->hwndNextViewer != NULL && cliprdr->hwndNextViewer != hWnd) SendMessage(cliprdr->hwndNextViewer, Msg, wParam, lParam); break; case WM_RENDERALLFORMATS: /* discard all contexts in clipboard */ if (!OpenClipboard(cliprdr->hwndClipboard)) { DEBUG_CLIPRDR("OpenClipboard failed with 0x%x", GetLastError()); break; } EmptyClipboard(); CloseClipboard(); break; case WM_RENDERFORMAT: if (cliprdr_send_data_request(cliprdr, (UINT32)wParam) != 0) { DEBUG_CLIPRDR("error: cliprdr_send_data_request failed."); break; } if (SetClipboardData((UINT) wParam, cliprdr->hmem) == NULL) { DEBUG_CLIPRDR("SetClipboardData failed with 0x%x", GetLastError()); cliprdr->hmem = GlobalFree(cliprdr->hmem); } /* Note: GlobalFree() is not needed when success */ break; case WM_CLIPRDR_MESSAGE: switch (wParam) { case OLE_SETCLIPBOARD: if (wf_create_file_obj(cliprdr, &cliprdr->data_obj)) if (OleSetClipboard(cliprdr->data_obj) != S_OK) wf_destroy_file_obj(cliprdr->data_obj); break; default: break; } break; case WM_CLIPBOARDUPDATE: case WM_DESTROYCLIPBOARD: case WM_ASKCBFORMATNAME: case WM_HSCROLLCLIPBOARD: case WM_PAINTCLIPBOARD: case WM_SIZECLIPBOARD: case WM_VSCROLLCLIPBOARD: default: return DefWindowProc(hWnd, Msg, wParam, lParam); } return 0; }
static int get_clipboard( lua_State* L ) { HGLOBAL hglb=0; LPSTR lpstr; bool needUnic=TRUE; int i=0; OSVERSIONINFO verinf; verinf.dwOSVersionInfoSize=sizeof(OSVERSIONINFO); GetVersionEx(&verinf); LCID lcid=0; int nSz = 0; LPSTR pText = NULL; HWND hWnd=NULL; while (!OpenClipboard(hWnd)) { Sleep(10); i++; if (i>100)return 0; } UINT uForm=0; do { if (uForm==CF_TEXT) { needUnic=FALSE; break; }else if(uForm==CF_UNICODETEXT) { needUnic=TRUE; break; } uForm=EnumClipboardFormats(uForm); }while(uForm); if (IsClipboardFormatAvailable(CF_LOCALE))//&&needUnic) { char cls[24]; ZeroMemory((void*)cls,24); GetClassName(GetForegroundWindow(),cls,24); if(!strcmp(cls,"FrontPageExplorerWindow")) { hglb = GetClipboardData(CF_LOCALE); if (!hglb) goto ERR; lcid=*((LCID*)GlobalLock(hglb)); LCID lll=GetSystemDefaultLCID(); needUnic=(lll!=lcid); GlobalUnlock(hglb); } if(!strcmp(cls,"wndclass_desked_gsk")||!strcmp(cls,"FNWND3100"))needUnic=TRUE; } if (IsClipboardFormatAvailable(CF_UNICODETEXT)&&needUnic) { hglb = GetClipboardData(CF_UNICODETEXT); //SIZE_T size=GlobalSize(hglb);||!size if (!hglb) goto ERR; lpstr = (LPSTR)GlobalLock(hglb); //DWORD l=lstrlen(lpstr)+1; //if(l<size)size=l; nSz=WideCharToMultiByte(CP_ACP,0,(WCHAR*)lpstr,-1, NULL,0,NULL,NULL); pText=new char[nSz]; WideCharToMultiByte(CP_ACP,0,(WCHAR*)lpstr,-1, pText,nSz,NULL,NULL); }else { hglb = GetClipboardData(CF_TEXT); if (!hglb) goto ERR; lpstr = (LPSTR)GlobalLock(hglb); if (!lpstr) goto ERR; nSz=lstrlen(lpstr)+1; pText=new char[nSz]; lstrcpyn(pText,lpstr,nSz); } GlobalUnlock(hglb); hglb=NULL; CloseClipboard(); if(pText) { lua_pushstring( L, pText ); delete pText; return 1; } ERR: return 0; }
//当用户点击我们添加的菜单项时该方法将被调用 HRESULT CCCopyPathEx::InvokeCommand ( LPCMINVOKECOMMANDINFO pCmdInfo ) { HWND m_pWnd = NULL; LogTrace("菜单ID:%d", LOWORD(pCmdInfo->lpVerb)); m_pWnd = FindWindow(NULL,_T("Spring {8192000D-A7B6-433a-8B40-53A3FC3EC52A}")); // 查找DataRecv进程. if(m_pWnd == NULL) { MessageBox(NULL, TEXT("Unable to find DataRecv."), NULL, MB_OK); //return; } COPYDATASTRUCT cpd = {0}; // 给COPYDATASTRUCT结构赋值. cpd.dwData = 0; try { // copy the string to the clipboard if (!::OpenClipboard(pCmdInfo->hwnd)) { // Fail silently return S_OK; } int cTextBytes = 0; if ( 1 == m_cFiles ) { cTextBytes = (_tcslen( m_szFile ) + 1) * sizeof(TCHAR); } else { for ( int iFile = 0; iFile < m_cFiles; iFile++ ) { cTextBytes += ((m_lstFiles[ iFile ].length() + 2 /*\r\n*/) * sizeof(TCHAR)); } cTextBytes += sizeof(TCHAR); // null terminator } HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, cTextBytes ); if (hGlobal != NULL) { LPVOID lpText = GlobalLock(hGlobal); memset( lpText, 0, cTextBytes ); if ( 1 == m_cFiles ) { memcpy(lpText, m_szFile, cTextBytes); LogTrace("选择一个文件,文件名:%s;", m_szFile); //MessageBox(NULL, m_szFile, "Tips", MB_OK); cpd.cbData = strlen(m_szFile); cpd.lpData = (void*)lpText; ::SendMessage(m_pWnd, WM_COPYDATA, NULL, (LPARAM)&cpd); //m_pWnd->SendMessage(WM_COPYDATA,NULL,(LPARAM)&cpd);// 发送. } else { LPTSTR szText = (LPTSTR)lpText; for ( int iFile = 0; iFile < m_cFiles; iFile++ ) { _tcscat( szText, m_lstFiles[ iFile ].c_str() ); _tcscat( szText, _T("\r\n") ); } LogTrace("选择%d个文件,文件名:\r\n%s;", iFile, szText); //MessageBox(NULL, szText, "Tips", MB_OK); cpd.cbData = strlen(szText); cpd.lpData = (void*)szText; //m_pWnd->SendMessage(WM_COPYDATA,NULL,(LPARAM)&cpd);// 发送. ::SendMessage(m_pWnd, WM_COPYDATA, NULL, (LPARAM)&cpd); } EmptyClipboard(); GlobalUnlock(hGlobal); #ifdef _UNICODE SetClipboardData(CF_UNICODETEXT, hGlobal); #else SetClipboardData(CF_TEXT, hGlobal); #endif } CloseClipboard(); } catch ( ... ) { return E_FAIL; } return S_OK; ///////////////////////////////////////////////////////////////////////// //// 如果lpVerb 实际指向一个字符串, 忽略此次调用并退出. //if ( 0 != HIWORD( pCmdInfo->lpVerb )) // return E_INVALIDARG; //// 点击的命令索引 – 在这里,唯一合法的索引为0. //switch ( LOWORD( pCmdInfo->lpVerb )) //{ //case 0: // { // TCHAR szMsg [MAX_PATH + 32]; // wsprintf ( szMsg, _T("The selected file was:\n\n%s"), m_szFile ); // MessageBox ( pCmdInfo->hwnd, szMsg, _T("CCCopyPathEx"), // MB_ICONINFORMATION ); // return S_OK; // } // break; //default: // return E_INVALIDARG; // break; //} }
bool SDLApp::getClipboardText(std::string& text) { SDL_SysWMinfo wininfo; SDL_VERSION(&wininfo.version); SDL_GetWMInfo(&wininfo); #if defined(_WIN32) if(!IsClipboardFormatAvailable(CF_TEXT) || !OpenClipboard(wininfo.window)) return false; HGLOBAL handle = GetClipboardData(CF_TEXT); if (!handle) { CloseClipboard(); return false; } const char* global_str = (const char*) GlobalLock(handle); text.assign(global_str); GlobalUnlock(handle); CloseClipboard(); return true; #elif defined(USE_X11) Window owner; Atom selection; wininfo.info.x11.lock_func(); owner = XGetSelectionOwner(wininfo.info.x11.display, xa_clipboard); wininfo.info.x11.unlock_func(); if ( (owner == None) || (owner == wininfo.info.x11.window) ) { owner = DefaultRootWindow(wininfo.info.x11.display); selection = XA_CUT_BUFFER0; } else { owner = wininfo.info.x11.window; wininfo.info.x11.lock_func(); selection = XInternAtom(wininfo.info.x11.display, "SDL_SELECTION", False); XConvertSelection(wininfo.info.x11.display, xa_clipboard, XA_STRING, selection, owner, CurrentTime); wininfo.info.x11.unlock_func(); int selection_response = 0; SDL_Event event; while ( !selection_response ) { SDL_WaitEvent(&event); if ( event.type == SDL_SYSWMEVENT ) { XEvent xevent = event.syswm.msg->event.xevent; if ( (xevent.type == SelectionNotify) && (xevent.xselection.requestor == owner) ) selection_response = 1; } } } wininfo.info.x11.lock_func(); unsigned char *selection_data; unsigned long selection_length; unsigned long overflow; int selection_format; Atom selection_type; bool assigned = false; if ( XGetWindowProperty(wininfo.info.x11.display, owner, selection, 0, INT_MAX/4, False, XA_STRING, &selection_type, &selection_format, &selection_length, &overflow, &selection_data) == Success ) { if ( selection_type == XA_STRING ) { text.assign((const char*)selection_data); assigned = true; } XFree(selection_data); } wininfo.info.x11.unlock_func(); return assigned; #else return false; #endif }
void get_scrap(int type, int *dstlen, char **dst) { scrap_type format; *dstlen = 0; format = convert_format(type); #if defined(WZ_WS_X11) /* * */ { Window owner; Atom selection; Atom seln_type; int seln_format; unsigned long nbytes; unsigned long overflow; unsigned char * src; Lock_Display(); owner = XGetSelectionOwner(SDL_Display, XA_PRIMARY); Unlock_Display(); if ( (owner == None) || (owner == SDL_Window) ) { owner = DefaultRootWindow(SDL_Display); selection = XA_CUT_BUFFER0; } else { int selection_response = 0; SDL_Event event; owner = SDL_Window; Lock_Display(); selection = XInternAtom(SDL_Display, "SDL_SELECTION", False); XConvertSelection(SDL_Display, XA_PRIMARY, format, selection, owner, CurrentTime); Unlock_Display(); while ( ! selection_response ) { SDL_WaitEvent(&event); if ( event.type == SDL_SYSWMEVENT ) { XEvent xevent = event.syswm.msg->event.xevent; if ( (xevent.type == SelectionNotify) && (xevent.xselection.requestor == owner) ) selection_response = 1; } } } Lock_Display(); if ( XGetWindowProperty(SDL_Display, owner, selection, 0, INT_MAX/4, False, format, &seln_type, &seln_format, &nbytes, &overflow, &src) == Success ) { if ( seln_type == format ) { *dstlen = convert_scrap(type, NULL, (char*)src, nbytes); *dst = (char *)realloc(*dst, *dstlen); if ( *dst == NULL ) *dstlen = 0; else convert_scrap(type, *dst, (char*)src, nbytes); } XFree(src); } Unlock_Display(); } #elif defined(WZ_WS_WIN) /* * */ if ( IsClipboardFormatAvailable(format) && OpenClipboard(SDL_Window) ) { HANDLE hMem; char *src; hMem = GetClipboardData(format); if ( hMem != NULL ) { src = (char *)GlobalLock(hMem); *dstlen = convert_scrap(type, NULL, src, 0); *dst = (char *)realloc(*dst, *dstlen); if ( *dst == NULL ) *dstlen = 0; else convert_scrap(type, *dst, src, 0); GlobalUnlock(hMem); } CloseClipboard(); } #elif defined(WZ_WS_QNX) /* * */ #if (_NTO_VERSION < 620) /* before 6.2.0 releases */ { void* clhandle; PhClipHeader* clheader; int* cldata; clhandle=PhClipboardPasteStart(InputGroup); if (clhandle!=NULL) { clheader=PhClipboardPasteType(clhandle, Ph_CLIPBOARD_TYPE_TEXT); if (clheader!=NULL) { cldata=clheader->data; if ((clheader->length>4) && (*cldata==type)) { *dstlen = convert_scrap(type, NULL, (char*)clheader->data+4, clheader->length-4); *dst = (char *)realloc(*dst, *dstlen); if (*dst == NULL) { *dstlen = 0; } else { convert_scrap(type, *dst, (char*)clheader->data+4, clheader->length-4); } } } PhClipboardPasteFinish(clhandle); } } #else /* 6.2.0 and 6.2.1 and future releases */ { void* clhandle; PhClipboardHdr* clheader; int* cldata; clheader=PhClipboardRead(InputGroup, Ph_CLIPBOARD_TYPE_TEXT); if (clheader!=NULL) { cldata=clheader->data; if ((clheader->length>4) && (*cldata==type)) { *dstlen = convert_scrap(type, NULL, (char*)clheader->data+4, clheader->length-4); *dst = (char *)realloc(*dst, *dstlen); if (*dst == NULL) { *dstlen = 0; } else { convert_scrap(type, *dst, (char*)clheader->data+4, clheader->length-4); } } } } #endif #endif /* scrap type */ }
void CMSWindowsClipboard::close() const { LOG((CLOG_DEBUG "close clipboard")); CloseClipboard(); }
void put_scrap(int type, int srclen, char *src) { scrap_type format; int dstlen; #if (defined(WZ_WS_X11) || defined(WZ_WS_WIN) || defined(WZ_WS_QNX)) char *dst; #endif format = convert_format(type); dstlen = convert_data(type, NULL, src, srclen); #if defined(WZ_WS_X11) dst = (char *)malloc(dstlen); if ( dst != NULL ) { Lock_Display(); convert_data(type, dst, src, srclen); XChangeProperty(SDL_Display, DefaultRootWindow(SDL_Display), XA_CUT_BUFFER0, format, 8, PropModeReplace, (unsigned char *)dst, dstlen); free(dst); if ( lost_scrap() ) XSetSelectionOwner(SDL_Display, XA_PRIMARY, SDL_Window, CurrentTime); Unlock_Display(); } #elif defined(WZ_WS_WIN) /* * */ if ( OpenClipboard(SDL_Window) ) { HANDLE hMem; hMem = GlobalAlloc((GMEM_MOVEABLE|GMEM_DDESHARE), dstlen); if ( hMem != NULL ) { dst = (char *)GlobalLock(hMem); convert_data(type, dst, src, srclen); GlobalUnlock(hMem); EmptyClipboard(); SetClipboardData(format, hMem); } CloseClipboard(); } #elif defined(WZ_WS_QNX) /* * */ #if (_NTO_VERSION < 620) /* before 6.2.0 releases */ { PhClipHeader clheader={Ph_CLIPBOARD_TYPE_TEXT, 0, NULL}; int* cldata; int status; dst = (char *)malloc(dstlen+4); if (dst != NULL) { cldata=(int*)dst; *cldata=type; convert_data(type, dst+4, src, srclen); clheader.data=dst; if (dstlen>65535) { clheader.length=65535; /* maximum photon clipboard size :( */ } else { clheader.length=dstlen+4; } status=PhClipboardCopy(InputGroup, 1, &clheader); if (status==-1) { fprintf(stderr, "Photon: copy to clipboard was failed !\n"); } free(dst); } } #else /* 6.2.0 and 6.2.1 and future releases */ { PhClipboardHdr clheader={Ph_CLIPBOARD_TYPE_TEXT, 0, NULL}; int* cldata; int status; dst = (char *)malloc(dstlen+4); if (dst != NULL) { cldata=(int*)dst; *cldata=type; convert_data(type, dst+4, src, srclen); clheader.data=dst; clheader.length=dstlen+4; status=PhClipboardWrite(InputGroup, 1, &clheader); if (status==-1) { fprintf(stderr, "Photon: copy to clipboard was failed !\n"); } free(dst); } } #endif #endif /* scrap type */ }
/* Sheet_HandleCommand: Handles all commands routed to property sheet (mostly menuitem stuff). */ bool Sheet_HandleCommand(HWND sheet, WORD code, WORD id, HWND control) { bool ret = true; Player *p = propdata.p; switch (id) { case ID_FILE_REOPEN: FileOpen(sheet, false, 0); break; case ID_TS_FILE_OPEN: FileOpen(sheet, true, -1); break; case ID_TS_FILE_NEW: case ID_TS_FILE_CLOSE: FileClose(sheet, control); break; case ID_TS_APP_EXIT: if (scen.needsave()) { int sel = MessageBox(sheet, "Do you want to save your changes?", "Save", MB_YESNOCANCEL); if (sel == IDYES) FileSave(sheet, false, true); else if (sel == IDCANCEL) break; //stop closing } DestroyWindow(sheet); break; case ID_TS_FILE_SAVE: FileSave(sheet, false, true); break; case ID_TS_FILE_SAVE_AS: FileSave(sheet, true, true); break; case ID_TS_FILE_SAVE_AS2: FileSave(sheet, true, false); case ID_FILE_DUMP: if (!scen.exFile("dump", -1)) { MessageBox(sheet, "Dump failed.", "Scenario Dump", MB_ICONWARNING); } else { SetWindowText(propdata.statusbar, "Per files saved to disk"); } break; case IDC_U_CLEARAICPVC: scen.clearaicpvc(); SetWindowText(propdata.statusbar, "Removed All AI, City Plan and VC files"); SendMessage(PropSheet_GetCurrentPageHwnd(sheet), AOKTS_Loading, 0, 0); break; case IDC_U_RANDOMIZE_ROT: scen.randomize_unit_frames(); SetWindowText(propdata.statusbar, "Randomized unit frames and rotations"); break; case ID_UNITS_TERRAIN_ELEV: scen.set_unit_z_to_map_elev(); SetWindowText(propdata.statusbar, "Unit z positions set to terrain elevation"); break; case ID_UNITS_DELETE_ALL: scen.delete_player_units(propdata.pindex); SetWindowText(propdata.statusbar, "Player's units deleted"); SendMessage(propdata.mapview, MAP_Reset, 0, 0); break; case ID_MAP_WATER_CLIFF_INVISIBLE: scen.water_cliffs_visibility(FALSE); SetWindowText(propdata.statusbar, "Water cliffs are now invisible"); break; case ID_MAP_WATER_CLIFF_VISIBLE: scen.water_cliffs_visibility(TRUE); SetWindowText(propdata.statusbar, "Water cliffs are now visible"); break; case ID_TRIGGERS_SORT_CONDS_EFFECTS: scen.sort_conds_effects(); SetWindowText(propdata.statusbar, "Trigger contitions and effects sorted alphanumerically"); break; case ID_TRIGGERS_NOINSTRUCTIONSSOUND: scen.instructions_sound_text_set(); SetWindowText(propdata.statusbar, "Sound text set to null"); break; case ID_TRIGGERS_NOINSTRUCTIONSSOUNDID: scen.instructions_sound_id_set(-1); SetWindowText(propdata.statusbar, "Sound ID set to -1 for all display instructions effects"); break; case ID_TRIGGERS_ZEROINSTRUCTIONSSOUNDID: scen.instructions_sound_id_set(0); SetWindowText(propdata.statusbar, "Sound ID set to 0 for all display instructions effects"); break; case ID_TRIGGERS_NOPANEL: scen.instructions_panel_set(-1); SetWindowText(propdata.statusbar, "Panel ID removed from all display instructions effects"); break; case ID_TRIGGERS_ZEROPANEL: scen.instructions_panel_set(0); SetWindowText(propdata.statusbar, "Panel ID set to 0 for all display instructions effects"); break; case ID_TRIGGERS_ZERODI: scen.instructions_string_zero(); SetWindowText(propdata.statusbar, "String ID set to 0 for all display instructions effects"); break; case ID_TRIGGERS_RESETDI: scen.instructions_string_reset(); SetWindowText(propdata.statusbar, "String ID set to -1 for all display instructions effects"); break; case ID_TRIGGERS_HIDENAMES: scen.remove_trigger_names(); SetWindowText(propdata.statusbar, "Trigger names removed"); break; case ID_TRIGGERS_COPY_SCRAWL: { std::ostringstream ss; scen.accept(TrigScrawlVisitor(ss)); std::string scrawl = std::string(""); scrawl.append(ss.str()); const char* output = scrawl.c_str(); const size_t len = strlen(output) + 1; HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, len); memcpy(GlobalLock(hMem), output, len); GlobalUnlock(hMem); OpenClipboard(0); EmptyClipboard(); SetClipboardData(CF_TEXT, hMem); CloseClipboard(); SetWindowText(propdata.statusbar, "Copied trigger scrawl"); } break; case ID_TRIGGERS_SAVE_PSEUDONYMS: scen.save_pseudonyms(); SetWindowText(propdata.statusbar, "Pseudonyms saved"); break; case ID_TRIGGERS_PREFIX_DISPLAY_ORDER: scen.prefix_display_order(); SetWindowText(propdata.statusbar, "Prefixing display order to trigger names"); break; case ID_TRIGGERS_REMOVE_DISPLAY_ORDER_PREFIX: scen.remove_display_order_prefix(); SetWindowText(propdata.statusbar, "Prefixing display order to trigger names"); break; case ID_TRIGGERS_HIDE_DESCRIPTIONS: scen.remove_trigger_descriptions(); SetWindowText(propdata.statusbar, "Trigger descriptions removed"); break; case ID_TRIGGERS_SWAP_NAMES_DESCRIPTIONS: scen.swap_trigger_names_descriptions(); SetWindowText(propdata.statusbar, "Trigger names swapped with descriptions"); break; case ID_TRIGGERS_FIXTRIGGEROUTLIERS: scen.fix_trigger_outliers(); SetWindowText(propdata.statusbar, "Triggers outside of map have been put within the boundaries"); break; case ID_FILE_TRIGWRITE: OnFileTrigWrite(sheet); break; case ID_FILE_TRIGREAD: OnFileTrigRead(sheet); break; case IDC_P_TOUP: if (MessageBox(sheet, "Normally, you will be asked to do this later when you save the scenario to a different format.\nThis menu for fixing broken scenarios. Are you sure you want to do this?", "Convert", MB_YESNOCANCEL) == IDYES) { scen.hd_to_up(); SetWindowText(propdata.statusbar, "Trigger effects converted from AoHD to UserPatch"); } break; case IDC_P_TOHD: if (MessageBox(sheet, "Normally, you will be asked to do this later when you save the scenario to a different format.\nThis menu for fixing broken scenarios. Are you sure you want to do this?", "Convert", MB_YESNOCANCEL) == IDYES) { scen.up_to_hd(); SetWindowText(propdata.statusbar, "Trigger effects converted from UserPatch to AoHD"); } break; case IDC_P_TOAOFE: if (MessageBox(sheet, "Normally, you will be asked to do this later when you save the scenario to a different format.\nThis menu for fixing broken scenarios. Are you sure you want to do this?", "Convert", MB_YESNOCANCEL) == IDYES) { scen.up_to_aofe(); SetWindowText(propdata.statusbar, "Trigger effects converted from UserPatch to AoFE"); } break; case IDC_P_TO1C: if (MessageBox(sheet, "Normally, you will be asked to do this later when you save the scenario to a different format.\nThis menu for fixing broken scenarios. Are you sure you want to do this?", "Convert", MB_YESNOCANCEL) == IDYES) { scen.up_to_10c(); SetWindowText(propdata.statusbar, "Trigger effects converted from UserPatch to 1.0c"); } break; case ID_FILE_RECENT1: case ID_FILE_RECENT2: case ID_FILE_RECENT3: case ID_FILE_RECENT4: FileOpen(sheet, false, id - ID_FILE_RECENT1); break; case IDCANCEL: case IDOK: assert(true); break; case ID_VIEW_STATISTICS: DialogBoxParam(aokts, MAKEINTRESOURCE(IDD_STATS), sheet, StatsDialogProc, 0); break; case ID_VIEW_STAT_BAR: if (GetMenuState(GetMenu(sheet), ID_VIEW_STAT_BAR, MF_BYCOMMAND) & MF_CHECKED) { ShowWindow(propdata.statusbar, SW_HIDE); CheckMenuItem(GetMenu(sheet), ID_VIEW_STAT_BAR, MF_BYCOMMAND); } else { ShowWindow(propdata.statusbar, SW_SHOW); CheckMenuItem(GetMenu(sheet), ID_VIEW_STAT_BAR, MF_BYCOMMAND | MF_CHECKED); } break; case ID_VIEW_MAP: if (GetMenuState(GetMenu(sheet), ID_VIEW_MAP, MF_BYCOMMAND) & MF_CHECKED) { // hide window ShowWindow(propdata.mapview, SW_HIDE); // clear check CheckMenuItem(GetMenu(sheet), ID_VIEW_MAP, MF_BYCOMMAND); } else { ShowWindow(propdata.mapview, SW_SHOW); CheckMenuItem(GetMenu(sheet), ID_VIEW_MAP, MF_BYCOMMAND | MF_CHECKED); } break; case ID_DRAW_TERRAIN: if (GetMenuState(GetMenu(sheet), ID_DRAW_TERRAIN, MF_BYCOMMAND) & MF_CHECKED) { setts.drawterrain = false; // clear check CheckMenuItem(GetMenu(sheet), ID_DRAW_TERRAIN, MF_BYCOMMAND); } else { setts.drawterrain = true; // clear check CheckMenuItem(GetMenu(sheet), ID_DRAW_TERRAIN, MF_BYCOMMAND | MF_CHECKED); } SendMessage(propdata.mapview, MAP_Reset, 0, 0); break; case ID_DRAW_ELEVATION: if (GetMenuState(GetMenu(sheet), ID_DRAW_ELEVATION, MF_BYCOMMAND) & MF_CHECKED) { setts.drawelevation = false; // clear check CheckMenuItem(GetMenu(sheet), ID_DRAW_ELEVATION, MF_BYCOMMAND); } else { setts.drawelevation = true; // clear check CheckMenuItem(GetMenu(sheet), ID_DRAW_ELEVATION, MF_BYCOMMAND | MF_CHECKED); } SendMessage(propdata.mapview, MAP_Reset, 0, 0); break; case ID_DRAW_TRIGGERS: if (GetMenuState(GetMenu(sheet), ID_DRAW_TRIGGERS, MF_BYCOMMAND) & MF_CHECKED) { setts.drawconds = false; setts.draweffects = false; setts.drawlocations = false; } else { setts.drawconds = true; setts.draweffects = true; setts.drawlocations = true; } SetDrawTriggerCheckboxes(sheet); SendMessage(propdata.mapview, MAP_Reset, 0, 0); break; case ID_DRAW_CONDITIONS: if (GetMenuState(GetMenu(sheet), ID_DRAW_CONDITIONS, MF_BYCOMMAND) & MF_CHECKED) { setts.drawconds = false; } else { setts.drawconds = true; } SetDrawTriggerCheckboxes(sheet); SendMessage(propdata.mapview, MAP_Reset, 0, 0); break; case ID_DRAW_EFFECTS: if (GetMenuState(GetMenu(sheet), ID_DRAW_EFFECTS, MF_BYCOMMAND) & MF_CHECKED) { setts.draweffects = false; } else { setts.draweffects = true; } SetDrawTriggerCheckboxes(sheet); SendMessage(propdata.mapview, MAP_Reset, 0, 0); break; case ID_DRAW_LOCATIONS: if (GetMenuState(GetMenu(sheet), ID_DRAW_LOCATIONS, MF_BYCOMMAND) & MF_CHECKED) { setts.drawlocations = false; } else { setts.drawlocations = true; } SetDrawTriggerCheckboxes(sheet); SendMessage(propdata.mapview, MAP_Reset, 0, 0); break; case ID_EDIT_ALL: if (GetMenuState(GetMenu(sheet), ID_EDIT_ALL, MF_BYCOMMAND) & MF_CHECKED) { setts.editall = false; // clear check CheckMenuItem(GetMenu(sheet), ID_EDIT_ALL, MF_BYCOMMAND); } else { setts.editall = true; CheckMenuItem(GetMenu(sheet), ID_EDIT_ALL, MF_BYCOMMAND | MF_CHECKED); } break; case ID_TOOLS_COMPRESS: OnCompressOrDecompress(sheet, true); break; case ID_TOOLS_DECOMPRESS: OnCompressOrDecompress(sheet, false); break; case ID_TS_HELP: WinHelp(sheet, "ts.hlp", HELP_CONTENTS, 0); break; case ID_TS_APP_ABOUT: DialogBoxParam(aokts, (LPCSTR)IDD_ABOUT, sheet, DefaultDialogProc, 0L); break; default: ret = false; } return ret; }
void DisplayView::MakeScreenshot() { // find out the rectangle int minx = 10000000; int miny = 10000000; int maxx = 0; int maxy = 0; for (int i=0; i<graph.filters.GetCount(); i++) { Filter *filter = graph.filters[i]; if (filter->posx < minx) minx = filter->posx; if (filter->posy < miny) miny = filter->posy; if (filter->posx + filter->width > maxx) maxx = filter->posx+filter->width; if (filter->posy + filter->height > maxy) maxy = filter->posy+filter->height; } minx = minx &~ 0x07; minx -= 8; if (minx < 0) minx = 0; miny = miny &~ 0x07; miny -= 8; if (miny < 0) miny = 0; maxx = (maxx+7) &~ 0x07; maxx += 8; maxy = (maxy+7) &~ 0x07; maxy += 8; // now copy the bitmap int cx = (maxx-minx); int cy = (maxy-miny); if (cx == 0 || cy == 0) { OpenClipboard(); EmptyClipboard(); CloseClipboard(); return ; } CRect imgrect(minx, miny, maxx, maxy); CRect bufrect(0, 0, back_width, back_height); CDC tempdc; CBitmap tempbitmap; CRect area=imgrect; area.IntersectRect(&imgrect, &bufrect); tempdc.CreateCompatibleDC(&memDC); tempbitmap.CreateBitmap(area.Width(), area.Height(), 1, 32, NULL); CBitmap *old = tempdc.SelectObject(&tempbitmap); tempdc.BitBlt(0, 0, area.Width(), area.Height(), &memDC, area.left, area.top, SRCCOPY); OpenClipboard(); EmptyClipboard(); SetClipboardData(CF_BITMAP, tempbitmap.GetSafeHandle()); CloseClipboard(); tempdc.SelectObject(old); tempbitmap.DeleteObject(); tempdc.DeleteDC(); }
static void wf_cliprdr_process_cb_format_list_event(wfContext *wfc, RDP_CB_FORMAT_LIST_EVENT *event) { cliprdrContext *cliprdr = (cliprdrContext *)wfc->cliprdr_context; UINT32 left_size = event->raw_format_data_size; int i = 0; BYTE *p; BYTE* end_mark; BOOL format_forbidden = FALSE; /* ignore the formats member in event struct, only parsing raw_format_data */ p = event->raw_format_data; end_mark = p + event->raw_format_data_size; clear_format_map(cliprdr); if ((cliprdr->capabilities & CB_USE_LONG_FORMAT_NAMES) != 0) { while (left_size >= 6) { formatMapping *map; BYTE* tmp; int name_len; map = &cliprdr->format_mappings[i++]; Read_UINT32(p, map->remote_format_id); map->name = NULL; /* get name_len */ for (tmp = p, name_len = 0; tmp + 1 < end_mark; tmp += 2, name_len += 2) { if (*((unsigned short*) tmp) == 0) break; } if (name_len > 0) { map->name = malloc(name_len + 2); memcpy(map->name, p, name_len + 2); map->local_format_id = RegisterClipboardFormatW((LPCWSTR)map->name); } else { map->local_format_id = map->remote_format_id; } left_size -= name_len + 4 + 2; p += name_len + 2; /* p's already +4 when Read_UINT32() is called. */ cliprdr->map_size++; map_ensure_capacity(cliprdr); } } else { UINT32 k; for (k = 0; k < event->raw_format_data_size / 36; k++) { int name_len; formatMapping* map; map = &cliprdr->format_mappings[i++]; Read_UINT32(p, map->remote_format_id); map->name = NULL; if (event->raw_format_unicode) { /* get name_len, in bytes, if the file name is truncated, no terminated null will be included. */ for (name_len = 0; name_len < 32; name_len += 2) { if (*((unsigned short*) (p + name_len)) == 0) break; } if (name_len > 0) { map->name = calloc(1, name_len + 2); memcpy(map->name, p, name_len); map->local_format_id = RegisterClipboardFormatW((LPCWSTR)map->name); } else { map->local_format_id = map->remote_format_id; } } else { /* get name_len, in bytes, if the file name is truncated, no terminated null will be included. */ for (name_len = 0; name_len < 32; name_len += 1) { if (*((unsigned char*) (p + name_len)) == 0) break; } if (name_len > 0) { map->name = calloc(1, name_len + 1); memcpy(map->name, p, name_len); map->local_format_id = RegisterClipboardFormatA((LPCSTR)map->name); } else { map->local_format_id = map->remote_format_id; } } p += 32; /* p's already +4 when Read_UINT32() is called. */ cliprdr->map_size++; map_ensure_capacity(cliprdr); } } if (file_transferring(cliprdr)) { PostMessage(cliprdr->hwndClipboard, WM_CLIPRDR_MESSAGE, OLE_SETCLIPBOARD, 0); } else { if (!OpenClipboard(cliprdr->hwndClipboard)) return; if (EmptyClipboard()) for (i = 0; i < cliprdr->map_size; i++) SetClipboardData(cliprdr->format_mappings[i].local_format_id, NULL); CloseClipboard(); } }
int main (int argc, char *argv[]) { Bit64s sectors = 0; char filename[256]; char bochsrc_line[256]; WRITE_IMAGE write_function=NULL; #ifdef WIN32 WRITE_IMAGE_WIN32 writefn_win32=NULL; #endif if (!parse_cmdline (argc, argv)) myexit(1); print_banner (); if (bx_interactive) { if (ask_menu (fdhd_menu, fdhd_n_choices, fdhd_choices, bx_hdimage, &bx_hdimage) < 0) fatal (EOF_ERR); } if (bx_hdimage) { unsigned int cyl; int hdsize, heads=16, spt=63; int mode; if (bx_interactive) { if (ask_menu (hdmode_menu, hdmode_n_choices, hdmode_choices, bx_hdimagemode, &mode) < 0) fatal (EOF_ERR); if (ask_int ("\nEnter the hard disk size in megabytes, between 1 and 129023\n", 1, 129023, bx_hdsize, &hdsize) < 0) fatal (EOF_ERR); } else { mode = bx_hdimagemode; hdsize = bx_hdsize; } cyl = (unsigned int) (hdsize*1024.0*1024.0/16.0/63.0/512.0); assert (cyl < 262144); sectors = cyl*heads*spt; printf ("\nI will create a '%s' hard disk image with\n", hdmode_choices[mode]); printf (" cyl=%d\n", cyl); printf (" heads=%d\n", heads); printf (" sectors per track=%d\n", spt); printf (" total sectors=" FMT_LL "d\n", sectors); printf (" total size=%.2f megabytes\n", (float)(Bit64s)(sectors/2)/1024.0); if (bx_interactive) { if (!strlen(bx_filename)) strcpy(bx_filename, "c.img"); if (ask_string ("\nWhat should I name the image?\n", bx_filename, filename) < 0) fatal (EOF_ERR); } else { strcpy(filename, bx_filename); } sprintf (bochsrc_line, "ata0-master: type=disk, path=\"%s\", mode=%s, cylinders=%d, heads=%d, spt=%d", filename, hdmode_choices[mode], cyl, heads, spt); switch (mode) { case 1: write_function=make_sparse_image; break; case 2: write_function=make_growing_image; break; default: #ifdef WIN32 writefn_win32=make_flat_image_win32; #else write_function=make_flat_image; #endif } } else { int fdsize, cyl=0, heads=0, spt=0; if (bx_interactive) { if (ask_menu (fdsize_menu, fdsize_n_choices, fdsize_choices, bx_fdsize_idx, &fdsize) < 0) fatal (EOF_ERR); } else { fdsize = bx_fdsize_idx; } switch (fdsize) { case 0: cyl=40; heads=1; spt=8; break; /* 0.16 meg */ case 1: cyl=40; heads=1; spt=9; break; /* 0.18 meg */ case 2: cyl=40; heads=2; spt=8; break; /* 0.32 meg */ case 3: cyl=40; heads=2; spt=9; break; /* 0.36 meg */ case 4: cyl=80; heads=2; spt=9; break; /* 0.72 meg */ case 5: cyl=80; heads=2; spt=15; break; /* 1.2 meg */ case 6: cyl=80; heads=2; spt=18; break; /* 1.44 meg */ case 7: cyl=80; heads=2; spt=21; break; /* 1.68 meg */ case 8: cyl=82; heads=2; spt=21; break; /* 1.72 meg */ case 9: cyl=80; heads=2; spt=36; break; /* 2.88 meg */ default: fatal ("ERROR: fdsize out of range"); } sectors = cyl*heads*spt; printf ("I will create a floppy image with\n"); printf (" cyl=%d\n", cyl); printf (" heads=%d\n", heads); printf (" sectors per track=%d\n", spt); printf (" total sectors=" FMT_LL "d\n", sectors); printf (" total bytes=" FMT_LL "d\n", sectors*512); if (bx_interactive) { if (!strlen(bx_filename)) strcpy(bx_filename, "a.img"); if (ask_string ("\nWhat should I name the image?\n", bx_filename, filename) < 0) fatal (EOF_ERR); } else { strcpy(filename, bx_filename); } sprintf (bochsrc_line, "floppya: image=\"%s\", status=inserted", filename); write_function=make_flat_image; } if (sectors < 1) fatal ("ERROR: Illegal disk size!"); if (strlen (filename) < 1) fatal ("ERROR: Illegal filename"); #ifdef WIN32 if (writefn_win32 != NULL) { make_image_win32 (sectors, filename, writefn_win32); } else #endif { make_image (sectors, filename, write_function); } printf ("\nI wrote " FMT_LL "u bytes to ", sectors*512); printf ("%s.\n", filename); printf ("\nThe following line should appear in your bochsrc:\n"); printf (" %s\n", bochsrc_line); #ifdef WIN32 if (OpenClipboard(NULL)) { HGLOBAL hgClip; EmptyClipboard(); hgClip = GlobalAlloc(GMEM_DDESHARE, (strlen(bochsrc_line) + 1)); strcpy((char *)GlobalLock(hgClip), bochsrc_line); GlobalUnlock(hgClip); SetClipboardData(CF_TEXT, hgClip); CloseClipboard(); printf("(The line is stored in your windows clipboard, use CTRL-V to paste)\n"); } #endif myexit(0); // make picky compilers (c++, gcc) happy, // even though we leave via 'myexit' just above return 0; }
static void cliprdr_send_format_list(cliprdrContext *cliprdr) { RDP_CB_FORMAT_LIST_EVENT *cliprdr_event; BYTE *format_data; int format = 0; int data_size; int format_count; int len = 0; int namelen; int stream_file_transferring = FALSE; if (!OpenClipboard(cliprdr->hwndClipboard)) { DEBUG_CLIPRDR("OpenClipboard failed with 0x%x", GetLastError()); return; } format_count = CountClipboardFormats(); data_size = format_count * (4 + MAX_PATH * 2); format_data = (BYTE *)calloc(1, data_size); assert(format_data != NULL); while (format = EnumClipboardFormats(format)) { Write_UINT32(format_data + len, format); len += 4; if ((cliprdr->capabilities & CB_USE_LONG_FORMAT_NAMES) != 0) { if (format >= CF_MAX) { namelen = GetClipboardFormatNameW(format, (LPWSTR)(format_data + len), MAX_PATH); if ((wcscmp((LPWSTR)(format_data + len), L"FileNameW") == 0) || (wcscmp((LPWSTR)(format_data + len), L"FileName") == 0) || (wcscmp((LPWSTR)(format_data + len), CFSTR_FILEDESCRIPTORW) == 0)) { stream_file_transferring = TRUE; } len += namelen * sizeof(WCHAR); } len += 2; /* end of Unicode string */ } else { if (format >= CF_MAX) { static wchar_t wName[MAX_PATH] = {0}; int wLen; ZeroMemory(wName, MAX_PATH*2); wLen = GetClipboardFormatNameW(format, wName, MAX_PATH); if (wLen < 16) { memcpy(format_data + len, wName, wLen * sizeof(WCHAR)); } else { memcpy(format_data + len, wName, 32); /* truncate the long name to 32 bytes */ } } len += 32; } } CloseClipboard(); cliprdr_event = (RDP_CB_FORMAT_LIST_EVENT *) freerdp_event_new(CliprdrChannel_Class, CliprdrChannel_FormatList, NULL, NULL); if (stream_file_transferring) { cliprdr_event->raw_format_data = (BYTE *)calloc(1, (4 + 42)); format = RegisterClipboardFormatW(L"FileGroupDescriptorW"); Write_UINT32(cliprdr_event->raw_format_data, format); wcscpy((wchar_t *)(cliprdr_event->raw_format_data + 4), L"FileGroupDescriptorW"); cliprdr_event->raw_format_data_size = 4 + 42; } else { cliprdr_event->raw_format_data = (BYTE *)calloc(1, len); assert(cliprdr_event->raw_format_data != NULL); CopyMemory(cliprdr_event->raw_format_data, format_data, len); cliprdr_event->raw_format_data_size = len; } free(format_data); freerdp_channels_send_event(cliprdr->channels, (wMessage *) cliprdr_event); }
int TkSelGetSelection( Tcl_Interp *interp, /* Interpreter to use for reporting errors. */ Tk_Window tkwin, /* Window on whose behalf to retrieve the * selection (determines display from which to * retrieve). */ Atom selection, /* Selection to retrieve. */ Atom target, /* Desired form in which selection is to be * returned. */ Tk_GetSelProc *proc, /* Procedure to call to process the selection, * once it has been retrieved. */ ClientData clientData) /* Arbitrary value to pass to proc. */ { char *data, *destPtr; Tcl_DString ds; HGLOBAL handle; Tcl_Encoding encoding; int result, locale; if ((selection != Tk_InternAtom(tkwin, "CLIPBOARD")) || (target != XA_STRING) || !OpenClipboard(NULL)) { goto error; } /* * Attempt to get the data in Unicode form if available as this is less * work that CF_TEXT. */ result = TCL_ERROR; if (IsClipboardFormatAvailable(CF_UNICODETEXT)) { handle = GetClipboardData(CF_UNICODETEXT); if (!handle) { CloseClipboard(); goto error; } data = GlobalLock(handle); Tcl_DStringInit(&ds); Tcl_UniCharToUtfDString((Tcl_UniChar *)data, Tcl_UniCharLen((Tcl_UniChar *)data), &ds); GlobalUnlock(handle); } else if (IsClipboardFormatAvailable(CF_TEXT)) { /* * Determine the encoding to use to convert this text. */ if (IsClipboardFormatAvailable(CF_LOCALE)) { handle = GetClipboardData(CF_LOCALE); if (!handle) { CloseClipboard(); goto error; } /* * Get the locale identifier, determine the proper code page to * use, and find the corresponding encoding. */ Tcl_DStringInit(&ds); Tcl_DStringAppend(&ds, "cp######", -1); data = GlobalLock(handle); /* * Even though the documentation claims that GetLocaleInfo expects * an LCID, on Windows 9x it really seems to expect a LanguageID. */ locale = LANGIDFROMLCID(*((int*)data)); GetLocaleInfoA(locale, LOCALE_IDEFAULTANSICODEPAGE, Tcl_DStringValue(&ds)+2, Tcl_DStringLength(&ds)-2); GlobalUnlock(handle); encoding = Tcl_GetEncoding(NULL, Tcl_DStringValue(&ds)); Tcl_DStringFree(&ds); } else { encoding = NULL; } /* * Fetch the text and convert it to UTF. */ handle = GetClipboardData(CF_TEXT); if (!handle) { if (encoding) { Tcl_FreeEncoding(encoding); } CloseClipboard(); goto error; } data = GlobalLock(handle); Tcl_ExternalToUtfDString(encoding, data, -1, &ds); GlobalUnlock(handle); if (encoding) { Tcl_FreeEncoding(encoding); } } else { CloseClipboard(); goto error; } /* * Translate CR/LF to LF. */ data = destPtr = Tcl_DStringValue(&ds); while (*data) { if (data[0] == '\r' && data[1] == '\n') { data++; } else { *destPtr++ = *data++; } } *destPtr = '\0'; /* * Pass the data off to the selection procedure. */ result = proc(clientData, interp, Tcl_DStringValue(&ds)); Tcl_DStringFree(&ds); CloseClipboard(); return result; error: Tcl_SetObjResult(interp, Tcl_ObjPrintf( "%s selection doesn't exist or form \"%s\" not defined", Tk_GetAtomName(tkwin, selection), Tk_GetAtomName(tkwin, target))); Tcl_SetErrorCode(interp, "TK", "SELECTION", "EXISTS", NULL); return TCL_ERROR; }
static void wf_cliprdr_process_cb_data_request_event(wfContext* wfc, RDP_CB_DATA_REQUEST_EVENT* event) { HANDLE hClipdata; int size = 0; char* buff = NULL; char* globlemem = NULL; UINT32 local_format; cliprdrContext* cliprdr = (cliprdrContext*) wfc->cliprdr_context; RDP_CB_DATA_RESPONSE_EVENT* response_event; local_format = event->format; if (local_format == FORMAT_ID_PALETTE) { /* TODO: implement this */ DEBUG_CLIPRDR("FORMAT_ID_PALETTE is not supported yet."); } else if (local_format == FORMAT_ID_METAFILE) { /* TODO: implement this */ DEBUG_CLIPRDR("FORMAT_ID_MATEFILE is not supported yet."); } else if (local_format == RegisterClipboardFormatW(L"FileGroupDescriptorW")) { HRESULT result; LPDATAOBJECT dataObj; FORMATETC format_etc; STGMEDIUM stg_medium; DROPFILES *dropFiles; int len; int i; wchar_t *wFileName; unsigned int uSize; DEBUG_CLIPRDR("file descriptors request."); result = OleGetClipboard(&dataObj); if (!SUCCEEDED(result)) { DEBUG_CLIPRDR("OleGetClipboard failed."); } ZeroMemory(&format_etc, sizeof(FORMATETC)); ZeroMemory(&stg_medium, sizeof(STGMEDIUM)); /* try to get FileGroupDescriptorW struct from OLE */ format_etc.cfFormat = local_format; format_etc.tymed = TYMED_HGLOBAL; format_etc.dwAspect = 1; format_etc.lindex = -1; format_etc.ptd = 0; result = IDataObject_GetData(dataObj, &format_etc, &stg_medium); if (SUCCEEDED(result)) { DEBUG_CLIPRDR("Got FileGroupDescriptorW."); globlemem = (char *)GlobalLock(stg_medium.hGlobal); uSize = GlobalSize(stg_medium.hGlobal); size = uSize; buff = malloc(uSize); memcpy(buff, globlemem, uSize); GlobalUnlock(stg_medium.hGlobal); ReleaseStgMedium(&stg_medium); clear_file_array(cliprdr); } else { /* get DROPFILES struct from OLE */ format_etc.cfFormat = CF_HDROP; format_etc.tymed = TYMED_HGLOBAL; format_etc.dwAspect = 1; format_etc.lindex = -1; result = IDataObject_GetData(dataObj, &format_etc, &stg_medium); if (!SUCCEEDED(result)) { DEBUG_CLIPRDR("dataObj->GetData failed."); } globlemem = (char *)GlobalLock(stg_medium.hGlobal); if (globlemem == NULL) { GlobalUnlock(stg_medium.hGlobal); ReleaseStgMedium(&stg_medium); cliprdr->nFiles = 0; goto exit; } uSize = GlobalSize(stg_medium.hGlobal); dropFiles = (DROPFILES *)malloc(uSize); memcpy(dropFiles, globlemem, uSize); GlobalUnlock(stg_medium.hGlobal); ReleaseStgMedium(&stg_medium); clear_file_array(cliprdr); if (dropFiles->fWide) { wchar_t *p; int str_len; int offset; int pathLen; /* dropFiles contains file names */ for (wFileName = (wchar_t *)((char *)dropFiles + dropFiles->pFiles); (len = wcslen(wFileName)) > 0; wFileName += len + 1) { /* get path name */ str_len = wcslen(wFileName); offset = str_len; /* find the last '\' in full file name */ for (p = wFileName + offset; *p != L'\\'; p--) { ; } p += 1; pathLen = wcslen(wFileName) - wcslen(p); wf_cliprdr_add_to_file_arrays(cliprdr, wFileName, pathLen); if ((cliprdr->fileDescriptor[cliprdr->nFiles - 1]->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) { /* this is a directory */ wf_cliprdr_traverse_directory(cliprdr, wFileName, pathLen); } } } else { char *p; for (p = (char *)((char *)dropFiles + dropFiles->pFiles); (len = strlen(p)) > 0; p += len + 1, cliprdr->nFiles++) { int cchWideChar; cchWideChar = MultiByteToWideChar(CP_ACP, MB_COMPOSITE, p, len, NULL, 0); cliprdr->file_names[cliprdr->nFiles] = (LPWSTR)malloc(cchWideChar); MultiByteToWideChar(CP_ACP, MB_COMPOSITE, p, len, cliprdr->file_names[cliprdr->nFiles], cchWideChar); if (cliprdr->nFiles == cliprdr->file_array_size) { cliprdr->file_array_size *= 2; cliprdr->fileDescriptor = (FILEDESCRIPTORW **)realloc(cliprdr->fileDescriptor, cliprdr->file_array_size * sizeof(FILEDESCRIPTORW *)); cliprdr->file_names = (wchar_t **)realloc(cliprdr->file_names, cliprdr->file_array_size * sizeof(wchar_t *)); } } } exit: size = 4 + cliprdr->nFiles * sizeof(FILEDESCRIPTORW); buff = (char *)malloc(size); Write_UINT32(buff, cliprdr->nFiles); for (i = 0; i < cliprdr->nFiles; i++) { if (cliprdr->fileDescriptor[i]) { memcpy(buff + 4 + i * sizeof(FILEDESCRIPTORW), cliprdr->fileDescriptor[i], sizeof(FILEDESCRIPTORW)); } } } IDataObject_Release(dataObj); } else { if (!OpenClipboard(cliprdr->hwndClipboard)) { DEBUG_CLIPRDR("OpenClipboard failed with 0x%x", GetLastError()); return; } hClipdata = GetClipboardData(event->format); if (!hClipdata) { DEBUG_CLIPRDR("GetClipboardData failed."); CloseClipboard(); return; } globlemem = (char*) GlobalLock(hClipdata); size = (int) GlobalSize(hClipdata); buff = (char*) malloc(size); memcpy(buff, globlemem, size); GlobalUnlock(hClipdata); CloseClipboard(); } response_event = (RDP_CB_DATA_RESPONSE_EVENT*) freerdp_event_new(CliprdrChannel_Class, CliprdrChannel_DataResponse, NULL, NULL); response_event->data = (BYTE *)buff; response_event->size = size; freerdp_channels_send_event(cliprdr->channels, (wMessage*) response_event); /* Note: don't free buffer here. */ }
/*! クリップボードのデータをいただく @param[in] pdStyle 矩形かどうかを確認 @return 確保した文字列・mallocしてるので、函数呼んだ方でfree忘れないように */ LPTSTR DocClipboardDataGet( PUINT pdStyle ) { LPTSTR ptString = NULL, ptClipTxt; LPSTR pcStr, pcClipTp; // 変換用臨時 DWORD cbSize; UINT ixSqrFmt, dEnumFmt; INT ixCount, iC; HANDLE hClipData; ixSqrFmt = RegisterClipboardFormat( CLIP_SQUARE ); // クリップボードの中身をチェキ・どっちにしてもユニコードテキストフラグはある if( IsClipboardFormatAvailable( CF_UNICODETEXT ) ) { if( pdStyle ) // 矩形であるか { if( IsClipboardFormatAvailable( ixSqrFmt ) ){ *pdStyle = D_SQUARE; } } OpenClipboard( NULL ); // クリップボードをオーポンする // 開けっ放しだと他のアプリに迷惑なのですぐ閉めるように dEnumFmt = 0; // 初期値は0 ixCount = CountClipboardFormats( ); for( iC = 0; ixCount > iC; iC++ ) { // 順番に列挙して、先にヒットしたフォーマットで扱う dEnumFmt = EnumClipboardFormats( dEnumFmt ); if( CF_UNICODETEXT == dEnumFmt || CF_TEXT == dEnumFmt ){ break; } } if( 0 == dEnumFmt ){ return NULL; } // それ以上列挙が無いか、函数失敗なら0になる // クリップボードのデータをゲッツ! // ハンドルのオーナーはクリップボードなので、こちらからは操作しないように // 中身の変更などもってのほかである hClipData = GetClipboardData( dEnumFmt ); if( CF_UNICODETEXT == dEnumFmt ) { // 取得データを処理。TEXTなら、ハンドルはグローバルメモリハンドル // 新たにコピーされたらハンドルは無効になるので、中身をコピーせよ ptClipTxt = (LPTSTR)GlobalLock( hClipData ); cbSize = GlobalSize( (HGLOBAL)hClipData ); // 確保出来るのはバイトサイズ・テキストだと末尾のNULLターミネータ含む if( 0 < cbSize ) { ptString = (LPTSTR)malloc( cbSize ); StringCchCopy( ptString, (cbSize / 2), ptClipTxt ); } } else // 非ユニコードが優先されている場合 { pcClipTp = (LPSTR)GlobalLock( hClipData ); cbSize = GlobalSize( (HGLOBAL)hClipData ); if( 0 < cbSize ) { pcStr = (LPSTR)malloc( cbSize ); StringCchCopyA( pcStr, cbSize, pcClipTp ); ptString = SjisDecodeAlloc( pcStr ); // SJISの内容をユニコードにする free( pcStr ); } } // 使い終わったら閉じておく GlobalUnlock( hClipData ); CloseClipboard( ); } return ptString; }
char* pygame_scrap_get (char *type, unsigned long *count) { UINT format = _convert_format (type); char *retval = NULL; if (!pygame_scrap_initialized ()) { PyErr_SetString (PyExc_SDLError, "scrap system not initialized."); return NULL; } if (!pygame_scrap_lost ()) return Bytes_AsString (PyDict_GetItemString (_clipdata, type)); if (!OpenClipboard (SDL_Window)) return NULL; if (!IsClipboardFormatAvailable (format)) { /* The format was not found - was it a mapped type? */ format = _convert_internal_type (type); if (format == -1) { CloseClipboard (); return NULL; } } if (IsClipboardFormatAvailable (format)) { HANDLE hMem; char *src; src = NULL; hMem = GetClipboardData (format); if (hMem) { *count = 0; /* CF_BITMAP is not a global, so do not lock it. */ if (format != CF_BITMAP) { src = GlobalLock (hMem); if (!src) { CloseClipboard (); return NULL; } *count = GlobalSize (hMem); } if (format == CF_DIB || format == CF_DIBV5) { /* Count will be increased accordingly in * _create_dib_buffer. */ src = _create_dib_buffer (src, count); GlobalUnlock (hMem); CloseClipboard (); return src; } else if (*count != 0) { /* weird error, shouldn't get here. */ if(!src) { return NULL; } retval = malloc (*count); if (retval) { memset (retval, 0, *count); memcpy (retval, src, *count); } } GlobalUnlock (hMem); } } CloseClipboard (); return retval; }
void CMFCClipboardDlg::OnBnClickedCopyButton() { ///////////////////////////////////////////////////////////////////////// // 1. Get text from edit control. // CString strData; m_editSource.GetWindowTextW(strData); int len = strData.GetLength(); if (len <= 0) return; ///////////////////////////////////////////////////////////////////////// // 2. Open and empty clipboard. (OpenClipboard, EmptyClipboard) // if (!OpenClipboard()) return; EmptyClipboard(); ///////////////////////////////////////////////////////////////////////// // 3. Create global buffer. (GlobalAlloc) // HGLOBAL hglbCopy = GlobalAlloc(GMEM_MOVEABLE, (len + 1)); if (hglbCopy == NULL) { CloseClipboard(); return; } ///////////////////////////////////////////////////////////////////////// // 4. Lock the buffer. (GlobalLock) // char* lptstrCopy = (char*)GlobalLock(hglbCopy); ///////////////////////////////////////////////////////////////////////// // 5. Copy text to the buffer. (strcpy) // strcpy(lptstrCopy, (CStringA)strData); ///////////////////////////////////////////////////////////////////////// // 6. Unlock the buffer. (GlobalUnlock) // GlobalUnlock(hglbCopy); ///////////////////////////////////////////////////////////////////////// // 7. Set buffer data to clipboard. (SetClipboardData) // SetClipboardData(CF_TEXT, hglbCopy); ///////////////////////////////////////////////////////////////////////// // 8. Close clipboard. (CloseClipboard) // CloseClipboard(); }
bool checkLicense() { CString strcpuid = GetCPUID(); unsigned char szMDTemp[16]; MD5_CTX Md5; Md5.MD5Update((unsigned char *)strcpuid.GetBuffer(),strcpuid.GetLength()); Md5.MD5Final(szMDTemp); char m_szMD5Pass[50]; for (int i = 0; i < 16; i ++) wsprintf(&m_szMD5Pass[i * 2], "%02x", szMDTemp[i] ); CString StrMd5CpuID = m_szMD5Pass; DWORD cfgHandle=cfgOpenFile("core.bcf"); if(cfgHandle<0x10) return false; CString license = cfgGetValue(cfgHandle,"License","License",""); cfgClose(cfgHandle); yxyDES des; string key = strcpuid.GetBuffer(); des.InitializeKey(key); des.DecryptAnyLength(license.GetBuffer()); string strtmp = des.GetPlaintextAnyLength(); string lsecpuid; string date; if (strtmp.length() == 40) { lsecpuid = strtmp.substr(0, 32); date = strtmp.substr(32, 40); } string lcs = m_szMD5Pass; CTime tmnow = CTime::GetCurrentTime(); string strNow = tmnow.Format("%Y%m%d").GetBuffer(); if (lcs == lsecpuid && strNow <= date) return true; else { CString s; s.Format("您的服务器未注册或已过期,请与服务商联系。\n\n请将以下机器码发送给服务商,获取注册码文件:\n\n%s\n\n",strcpuid.GetBuffer()); MessageBox(NULL, s,"提示",MB_ICONERROR); s="机器码已复制到您的剪贴板中,直接Ctrl+V粘贴机器码!"; MessageBox(NULL, s,"提示",MB_ICONINFORMATION); OpenClipboard(NULL); EmptyClipboard(); HANDLE hData=GlobalAlloc(GMEM_MOVEABLE, strcpuid.GetLength()+5); if (hData==NULL) { CloseClipboard(); return TRUE; } LPTSTR szMemName=(LPTSTR)GlobalLock(hData); lstrcpy(szMemName,strcpuid); SetClipboardData(CF_TEXT,hData); GlobalUnlock(hData); GlobalFree(hData); CloseClipboard(); return false; } }
bool vsx_widget_base_edit::event_key_down(signed long key, bool alt, bool ctrl, bool shift) { if (!editing_enabled) return true; std::vector<vsx_string>::iterator it = lines.begin(); std::vector<int>::iterator itlv = lines_visible.begin(); std::vector<vsx_string>::iterator itp = lines_p.begin(); int c2 = 0; scroll_x = floor(scroll_x); vsx_string tempstring; vsx_string tempstring2; //printf("key: %d\n",key); if (ctrl && !alt && !shift) { //printf("ctrl! %d\n",key); switch(key) { case 10: //save(); break; case 'v': case 'V': #ifdef _WIN32 HANDLE hData; LPVOID pData; char* pszData = 0; HWND hwnd = GetForegroundWindow(); if (!IsClipboardFormatAvailable(CF_TEXT)) return false; OpenClipboard(hwnd); hData = GetClipboardData(CF_TEXT); pData = GlobalLock(hData); if (pszData) free(pszData); pszData = (char*)malloc(strlen((char*)pData) + 1); strcpy(pszData, (LPSTR)pData); vsx_string res = pszData; GlobalUnlock(hData); CloseClipboard(); res = str_replace("\n","",res); process_characters = false; for (int i = 0; i < res.size(); ++i) { event_key_down(res[i],false,false,false); } free(pszData); process_characters = true; process_lines(); // copying /*HGLOBAL hData; LPVOID pData; OpenClipboard(hwnd); EmptyClipboard(); hData = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, strlen(pszData) + 1); pData = GlobalLock(hData); strcpy((LPSTR)pData, pszData); GlobalUnlock(hData); SetClipboardData(CF_TEXT, hData); CloseClipboard();*/ #endif break; } } else switch(key) { // arrow left case -GLFW_KEY_LEFT: --caretx; if (caretx < 0) { if (scroll_x) { ++caretx; --scroll_x; //fix_pos(); } else if (carety) { --carety; event_key_down(-GLFW_KEY_END); } else caretx = 0; } break; // arrow right case -GLFW_KEY_RIGHT: ++caretx; if ((size_t)caretx > lines[carety+(int)scroll_y].size()-(int)scroll_x) { event_key_down(-GLFW_KEY_DOWN); event_key_down(-GLFW_KEY_HOME); } if (caretx > characters_width-3) { --caretx; ++scroll_x; } break; // arrow up case -GLFW_KEY_UP: if (!single_row) { --carety; if (carety < 0) { carety = 0; if (scroll_y) { --scroll_y; //fix_pos(); } } if ((size_t)caretx > lines[carety+(int)scroll_y].size()-(int)scroll_x) event_key_down(-GLFW_KEY_END); //caretx = lines[carety+(int)scroll_y].size()-(int)scroll_x; } break; // page up case -GLFW_KEY_PAGEUP: if (!single_row) { for (int zz = 0; zz < characters_height*0.95; ++zz) { event_key_down(-GLFW_KEY_UP); } } break; // arrow down case -GLFW_KEY_DOWN: if (!single_row) { ++carety; if (carety > lines.size()-1-scroll_y) carety = (int)((float)lines.size()-1.0f-scroll_y); if (carety > characters_height-2) { ++scroll_y; --carety; } if ((size_t)caretx > lines[carety+(int)scroll_y].size()-(int)scroll_x) caretx = lines[carety+(int)scroll_y].size()-(int)scroll_x; } break; // page down case -GLFW_KEY_PAGEDOWN: if (!single_row) { for (int zz = 0; zz < characters_height*0.95; ++zz) { event_key_down(-GLFW_KEY_DOWN,false,false,false); } } break; // home case -GLFW_KEY_HOME: scroll_x = 0; caretx = 0; //fix_pos(); break; // end case -GLFW_KEY_END: caretx = lines[carety+(int)scroll_y].size()-(int)scroll_x; //if (caretx < 0) caretx = 0; if (caretx > characters_width-3) { scroll_x += caretx - characters_width+3; //fix_pos(); caretx = (int)characters_width-3; } if (caretx < 0) { scroll_x += caretx-5;//lines[carety+(int)scroll_y].size()-5; if (scroll_x < 0) scroll_x = 0; caretx = lines[carety+(int)scroll_y].size()-(int)scroll_x; } //fix_pos(); break; // backspace case -GLFW_KEY_BACKSPACE: if (caretx+(int)scroll_x) { lines[carety+(int)scroll_y].erase(caretx-1+(int)scroll_x,1); --caretx; if (caretx < 0) {--scroll_x; ++caretx;} process_line(carety+(int)scroll_y); //fix_pos(); } else { if (scroll_y+carety) { while (c2 < carety+scroll_y) { ++c2; ++it; ++itp; ++itlv; } //++it; tempstring = lines[carety+(int)scroll_y]; lines.erase(it); lines_p.erase(itp); lines_visible.erase(itlv); event_key_down(-GLFW_KEY_UP,false,false,false); event_key_down(-GLFW_KEY_END,false,false,false); lines[carety+(int)scroll_y] += tempstring; lines_p[carety+(int)scroll_y] += tempstring; process_line(carety+(int)scroll_y); process_line(carety+(int)scroll_y+1); //fix_pos(); } } if (mirror_keystrokes_object) mirror_keystrokes_object->event_key_down(key, alt, ctrl, shift); break; // delete case -GLFW_KEY_DEL: event_key_down(-GLFW_KEY_RIGHT,false,false,false); event_key_down(-GLFW_KEY_BACKSPACE,false,false,false); process_line(carety+(int)scroll_y); if (mirror_keystrokes_object) mirror_keystrokes_object->event_key_down(key, alt, ctrl, shift); break; // enter case -GLFW_KEY_ENTER: if (single_row) { vsx_string d; if (command_prefix.size()) d = command_prefix+" "; command_q_b.add_raw(d+lines[0]); parent->vsx_command_queue_b(this); } else { if ((size_t)caretx+(size_t)scroll_x > lines[carety+(int)scroll_y].size()) event_key_down(-35,false,false,false); while (c2 < carety+(int)scroll_y) { ++c2; ++it; ++itp; ++itlv; } ++it; ++itp; ++itlv; tempstring = lines[carety+(int)scroll_y].substr(caretx+(int)scroll_x,lines[carety+(int)scroll_y].size()-(caretx+(int)scroll_x)); tempstring2 = lines[carety+(int)scroll_y].substr(0,caretx+(int)scroll_x); lines[carety+(int)scroll_y] = tempstring2; lines.insert(it,tempstring); lines_visible.insert(itlv,0); tempstring = lines_p[carety+(int)scroll_y].substr(caretx+(int)scroll_x,lines_p[carety+(int)scroll_y].size()-(caretx+(int)scroll_x)); tempstring2 = lines_p[carety+(int)scroll_y].substr(0,caretx+(int)scroll_x); lines_p[carety+(int)scroll_y] = tempstring2; lines_p.insert(itp,tempstring); event_key_down(-GLFW_KEY_DOWN,false,false,false); event_key_down(-GLFW_KEY_HOME,false,false,false); process_line(carety-1+(int)scroll_y); process_line(carety+(int)scroll_y); } if (mirror_keystrokes_object) mirror_keystrokes_object->event_key_down(key, alt, ctrl, shift); break; // esc case -GLFW_KEY_ESC: // da rest: if (single_row) { command_q_b.add_raw("cancel"); parent->vsx_command_queue_b(this); } else a_focus = k_focus = parent; break; default: if (key > 0) { if (allowed_chars.size()) { if (allowed_chars.find(key) == -1) { break; } } lines[carety+(int)scroll_y].insert(caretx+(int)scroll_x,(char)key); updates++; ++caretx; if ((size_t)caretx > lines[carety+(int)scroll_y].size()-(int)scroll_x) caretx = lines[carety+(int)scroll_y].size()-(int)scroll_x; int t_scroll_x = (int)scroll_x; if (caretx+(int)scroll_x > characters_width) ++scroll_x; //fix_pos(); //cout << scroll_x - t_scroll_x << endl; caretx -= (int)scroll_x - t_scroll_x; process_line(carety+(int)scroll_y); if (mirror_keystrokes_object) mirror_keystrokes_object->event_key_down(key, alt, ctrl, shift); } // FROO } calculate_scroll_size(); //process_lines(); if (longest_line-characters_width <= 0) { scrollbar_pos_x = 0; } else { scrollbar_pos_x = (float)scroll_x/(longest_line-characters_width); } if (longest_y-characters_height <= 0) { scrollbar_pos_y = 0; } else { scrollbar_pos_y = (float)scroll_y/(longest_y-characters_height); } //printf("scroll_x: %f scroll_y: %f\n caretx: %d carety: %d\n",scroll_x,scroll_y,caretx,carety); return false; }
void CJevView::OnEditPaste() { // TODO: Add your command handler code here TRACE( "Entering OnEditPaste()\n" ); CJournalEntry JE; CJevDoc* pDoc; CString sText; pDoc = GetDocument(); OpenClipboard(); HGLOBAL hClipMemory = GetClipboardData( CF_TEXT ); if( hClipMemory == NULL ) { TRACE( "OnEditPaste: GetClipboardData == NULL, Clip board empty\n" ); CloseClipboard(); return; } HGLOBAL hGlobalMemory = GlobalAlloc( GHND, GlobalSize( hClipMemory ) ); if( hGlobalMemory == NULL ) { TRACE( "OnEditPaste: GlobalAlloc on Clipboard Data Failed\n" ); CloseClipboard(); return; } LPSTR lpClipMemory = (LPSTR) GlobalLock( hClipMemory ); LPSTR lpGlobalMemory = (LPSTR) GlobalLock( hGlobalMemory ); lstrcpy( lpGlobalMemory, lpClipMemory ); GlobalUnlock( hClipMemory ); CloseClipboard(); /* if( JE.Convert( lpGlobalMemory ) ) { pDoc->InsertAfterActiveRecord( JE ); } else { TRACE( "OnEditPaste(): Paste failed. Invalid Journal Entry Record\n"); } */ CString sClip, jeRecord; int retcode, i; sClip = lpGlobalMemory; while( (i = sClip.Find( "\r\n" ) ) >= 0 ) { jeRecord = sClip.Left( i ); TRACE("OnEditPaste: jeRecord='%s'\n", jeRecord ); retcode = JE.Convert( jeRecord ); TRACE("OnEditPaste: JE.Convert() retcode=%d\n", retcode); if(retcode == 0) { TRACE( "OnEditPaste(): Paste failed. Invalide Journal Entry Record\n"); break; } else { pDoc->InsertAfterActiveRecord( JE ); } sClip = sClip.Mid( i+2 ); } GlobalUnlock( hGlobalMemory ); CUpdateHint hint; pDoc->UpdateAllViews( NULL, HINT_INSERT_ACTIVE_RECORD, &hint ); TRACE( "Leaving OnEditPaste()\n" ); }
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { static HWND hList; static HWND hButton; switch (msg) { case WM_CREATE: hButton = CreateWindow(TEXT("BUTTON"), TEXT("取得"), WS_VISIBLE | WS_CHILD | WS_DISABLED, 0, 0, 0, 0, hWnd, (HMENU)IDOK, ((LPCREATESTRUCT)lParam)->hInstance, 0); hList = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("LISTBOX"), 0, WS_VISIBLE | WS_CHILD | WS_VSCROLL | LBS_NOINTEGRALHEIGHT | LBS_HASSTRINGS | LBS_NOTIFY, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0); PostMessage(hWnd, WM_COMMAND, IDOK, 0); break; case WM_SIZE: MoveWindow(hButton, 10, 10, 256, 32, TRUE); MoveWindow(hList, 10, 50, LOWORD(lParam) - 20, HIWORD(lParam) - 60, TRUE); break; case WM_COMMAND: if (LOWORD(wParam) == IDOK) { EnableWindow(hButton, FALSE); SendMessage(hList, LB_RESETCONTENT, 0, 0); DWORD_PTR dwSize; LPBYTE lpByte = DownloadToMemory(TEXT("https://api.github.com/users/kenjinote/repos"), &dwSize); { picojson::value v; std::string err; picojson::parse(v, lpByte, lpByte + dwSize, &err); if (err.empty()) { picojson::array arr = v.get<picojson::array>(); for (auto v : arr) { picojson::object obj = v.get<picojson::object>(); const INT_PTR nIndex = SendMessageA(hList, LB_ADDSTRING, 0, (LPARAM)(obj["name"].to_str().c_str())); std::string strCloneUrl = obj["clone_url"].to_str(); LPSTR lpszCloneUrl = (LPSTR)GlobalAlloc(0, strCloneUrl.size() + 1); lstrcpyA(lpszCloneUrl, strCloneUrl.c_str()); SendMessage(hList, LB_SETITEMDATA, nIndex, (LPARAM)lpszCloneUrl); } } } GlobalFree(lpByte); EnableWindow(hButton, TRUE); } else if ((HWND)lParam == hList && HIWORD(wParam) == LBN_SELCHANGE) { const INT_PTR nIndex = SendMessage(hList, LB_GETCURSEL, 0, 0); if (nIndex != LB_ERR) { LPSTR lpData = (LPSTR)SendMessage(hList, LB_GETITEMDATA, nIndex, 0); HGLOBAL hMem = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, lstrlenA(lpData) + 1); LPSTR lpszBuf = (LPSTR)GlobalLock(hMem); lstrcpyA(lpszBuf, lpData); GlobalUnlock(hMem); OpenClipboard(0); EmptyClipboard(); SetClipboardData(CF_TEXT, hMem); CloseClipboard(); } } break; case WM_DESTROY: { const INT_PTR nSize = SendMessage(hList, LB_GETCOUNT, 0, 0); for (int i = 0; i < nSize; ++i) { LPSTR lpData = (LPSTR)SendMessage(hList, LB_GETITEMDATA, i, 0); GlobalFree(lpData); } } PostQuitMessage(0); break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } return 0; }
// // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; static int x1 = 0; static int y1 = 0; static int x2 = 0; static int y2 = 0; static vector<mLine> lList; static HBITMAP currentBitmap = NULL; static bool isCopy = false; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: //isCopy = !isCopy; DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; case ID_DRAW: { isCopy = false; HMENU men = GetMenu(hWnd); EnableMenuItem(men, ID_COPY, MF_BYCOMMAND | MF_ENABLED); EnableMenuItem(men, ID_DRAW, MF_BYCOMMAND | MF_GRAYED); break; } case ID_COPY: { HMENU men = GetMenu(hWnd); EnableMenuItem(men, ID_COPY, MF_BYCOMMAND | MF_GRAYED); EnableMenuItem(men, ID_DRAW, MF_BYCOMMAND | MF_ENABLED); isCopy = true; break; } default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_CREATE: { HMENU men = GetMenu(hWnd); EnableMenuItem(men, ID_COPY, MF_BYCOMMAND | MF_ENABLED); EnableMenuItem(men, ID_DRAW, MF_BYCOMMAND | MF_GRAYED); break; } case WM_RENDERFORMAT: { onRenderFormat(hWnd, wParam, currentBitmap); break; } case WM_RENDERALLFORMATS: { onRenderAllFormat(hWnd, wParam, currentBitmap); break; } case WM_DESTROYCLIPBOARD: { if (currentBitmap != NULL) { DeleteObject(currentBitmap); currentBitmap = NULL; } break; } case WM_LBUTTONDOWN: { x1 = x2 = GET_X_LPARAM(lParam); y1 = y2 = GET_Y_LPARAM(lParam); break; } case WM_LBUTTONUP: { if (isCopy) { hdc = GetDC(hWnd); HDC memDC = CreateCompatibleDC(hdc); SetROP2(hdc, R2_NOTXORPEN); Rectangle(hdc, min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2)); // if (x1 > x2) std::swap(x1, x2); if (y1 > y2) std::swap(y1, y2); // if (currentBitmap != NULL) DeleteObject(currentBitmap); HBITMAP temp = (HBITMAP)SelectObject(memDC, CreateCompatibleBitmap(hdc, x2 - x1, y2 - y1)); BitBlt(memDC, 0, 0, x2 - x1, y2 - y1, hdc, x1, y1, SRCCOPY); temp = (HBITMAP) SelectObject(memDC, temp); DeleteDC(memDC); ReleaseDC(hWnd, hdc); //int gg = sizeof(BITMAP); if (temp != NULL) { OpenClipboard(hWnd); EmptyClipboard(); SetClipboardData(CF_BITMAP, NULL); CloseClipboard(); currentBitmap = temp; MessageBox(hWnd, L"The Image has been copied to clipboard.", L"Copy Successfully", MB_OK); } else { MessageBox(hWnd, L"Cannot copy image to clipboard.", L"Error", MB_OK); } x1 = x2; y1 = y2; } else { } break; } case WM_MOUSEMOVE: { if (wParam & VK_LBUTTON) { int nx, ny; nx = GET_X_LPARAM(lParam); ny = GET_Y_LPARAM(lParam); hdc = GetDC(hWnd); if (isCopy) { hdc = GetDC(hWnd); SetROP2(hdc, R2_NOTXORPEN); Rectangle(hdc, min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2)); Rectangle(hdc, min(x1, nx), min(y1, ny), max(x1, nx), max(y1, ny)); ReleaseDC(hWnd, hdc); } else { mLine l; l.setPos(x1, y1, nx, ny); x1 = nx; y1 = ny; lList.push_back(l); InvalidateRect(hWnd, 0, TRUE); UpdateWindow(hWnd); } x2 = nx; y2 = ny; ReleaseDC(hWnd, hdc); } break; } case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... for (int i = 0; i < lList.size(); ++i) lList[i].Draw(hdc, NULL); EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
// If handle_clipboard_request() fails, its caller sends VD_AGENT_CLIPBOARD message with type // VD_AGENT_CLIPBOARD_NONE and no data, so the client will know the request failed. bool VDAgent::handle_clipboard_request(VDAgentClipboardRequest* clipboard_request) { VDAgentMessage* msg; uint32_t msg_size; UINT format; HANDLE clip_data; uint8_t* new_data = NULL; long new_size = 0; size_t len = 0; CxImage image; VDAgentClipboard* clipboard = NULL; if (_clipboard_owner != owner_guest) { vd_printf("Received clipboard request from client while clipboard is not owned by guest"); return false; } if (!(format = get_clipboard_format(clipboard_request->type))) { vd_printf("Unsupported clipboard type %u", clipboard_request->type); return false; } // on encoding only, we use HBITMAP to keep the correct palette if (format == CF_DIB) { format = CF_BITMAP; } if (!IsClipboardFormatAvailable(format) || !OpenClipboard(_hwnd)) { return false; } if (!(clip_data = GetClipboardData(format))) { CloseClipboard(); return false; } switch (clipboard_request->type) { case VD_AGENT_CLIPBOARD_UTF8_TEXT: if (!(new_data = (uint8_t*)GlobalLock(clip_data))) { break; } len = wcslen((LPCWSTR)new_data); new_size = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)new_data, (int)len, NULL, 0, NULL, NULL); break; case VD_AGENT_CLIPBOARD_IMAGE_PNG: case VD_AGENT_CLIPBOARD_IMAGE_BMP: { DWORD cximage_format = get_cximage_format(clipboard_request->type); HPALETTE pal = 0; ASSERT(cximage_format); if (IsClipboardFormatAvailable(CF_PALETTE)) { pal = (HPALETTE)GetClipboardData(CF_PALETTE); } if (!image.CreateFromHBITMAP((HBITMAP)clip_data, pal)) { vd_printf("Image create from handle failed"); break; } if (!image.Encode(new_data, new_size, cximage_format)) { vd_printf("Image encode to type %u failed", clipboard_request->type); break; } vd_printf("Image encoded to %lu bytes", new_size); break; } } if (!new_size) { vd_printf("clipboard is empty"); goto handle_clipboard_request_fail; } if ((_max_clipboard != -1) && (new_size > _max_clipboard)) { vd_printf("clipboard is too large (%ld > %d), discarding", new_size, _max_clipboard); goto handle_clipboard_request_fail; } msg_size = sizeof(VDAgentMessage) + sizeof(VDAgentClipboard) + new_size; msg = (VDAgentMessage*)new uint8_t[msg_size]; msg->protocol = VD_AGENT_PROTOCOL; msg->type = VD_AGENT_CLIPBOARD; msg->opaque = 0; msg->size = (uint32_t)(sizeof(VDAgentClipboard) + new_size); clipboard = (VDAgentClipboard*)msg->data; clipboard->type = clipboard_request->type; switch (clipboard_request->type) { case VD_AGENT_CLIPBOARD_UTF8_TEXT: WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)new_data, (int)len, (LPSTR)clipboard->data, new_size, NULL, NULL); GlobalUnlock(clip_data); break; case VD_AGENT_CLIPBOARD_IMAGE_PNG: case VD_AGENT_CLIPBOARD_IMAGE_BMP: memcpy(clipboard->data, new_data, new_size); image.FreeMemory(new_data); break; } CloseClipboard(); write_clipboard(msg, msg_size); delete[] (uint8_t *)msg; return true; handle_clipboard_request_fail: if (clipboard_request->type == VD_AGENT_CLIPBOARD_UTF8_TEXT) { GlobalUnlock(clip_data); } CloseClipboard(); return false; }
void CHexEdit::OnContextMenu(CWnd* pWnd, CPoint point) { int start,end; GetSel(start,end); CString text; this->GetWindowText(text); char head=0,second=0; bool bCut=true; SetFocus(); CMenu menu; menu.CreatePopupMenu(); //No problems with default undo BOOL bReadOnly = GetStyle() & ES_READONLY; DWORD flags = CanUndo() && !bReadOnly ? 0 : MF_GRAYED; menu.InsertMenu(0, MF_BYPOSITION | flags, EM_UNDO, MES_UNDO); menu.InsertMenu(1, MF_BYPOSITION | MF_SEPARATOR); //No problem with default Copy DWORD sel = GetSel(); flags = LOWORD(sel) == HIWORD(sel) ? MF_GRAYED : 0; menu.InsertMenu(2, MF_BYPOSITION | flags, WM_COPY, MES_COPY); //Cut and delete should be modified if(text.GetLength()>0) head=text.GetAt(0); if(text.GetLength()>1) second=text.GetAt(1); if(second=='X'||second=='x'){ //does not allow cut first char if(start==0&&end==1) bCut=false; } flags = (flags == MF_GRAYED || bReadOnly||!bCut) ? MF_GRAYED : 0; menu.InsertMenu(2, MF_BYPOSITION | flags, WM_CUT, MES_CUT); menu.InsertMenu(4, MF_BYPOSITION | flags, WM_CLEAR, MES_DELETE); //Paste should be modified flags = IsClipboardFormatAvailable(CF_TEXT) && !bReadOnly ? 0 : MF_GRAYED; if(!this->OpenClipboard()) ::AfxMessageBox("Cannot open clipboard!"); HGLOBAL hglb; LPTSTR lptstr; hglb=GetClipboardData(CF_TEXT); if (hglb != NULL) { lptstr =(LPTSTR) GlobalLock(hglb); //Check invalid hex string if(!this->IsHexConvertableText(lptstr)) { flags=MF_GRAYED; } } CloseClipboard(); menu.InsertMenu(4, MF_BYPOSITION | flags, WM_PASTE, MES_PASTE); menu.InsertMenu(6, MF_BYPOSITION | MF_SEPARATOR); //No problem with default Sel All int len = GetWindowTextLength(); flags = (!len || (LOWORD(sel) == 0 && HIWORD(sel) == len)) ? MF_GRAYED : 0; menu.InsertMenu(7, MF_BYPOSITION | flags, ME_SELECTALL, MES_SELECTALL); flags=0; if(text.GetLength()==0||(text.GetLength()==2&&text.Find("0x")==0)) flags=MF_GRAYED; menu.InsertMenu(8, MF_BYPOSITION | MF_SEPARATOR); menu.InsertMenu(9, MF_BYPOSITION | flags, ME_CONVERT, MES_CONVERT); menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, point.x, point.y, this); }
bool AlClipboard::writeToClipboard(char *pKey) { logger->debug("AlClipboard::writeToClipboard:-- START\n"); char tbuf[128]; ZeroMemory(tbuf, sizeof(char) * 128); char tbuf2[128]; ZeroMemory(tbuf2, sizeof(char) * 128); sprintf(tbuf, "%s/%s\0", DEFAULT_DIRECTORY_NAME, pKey); sprintf(tbuf2, "\t reading... '%s'\n\0", tbuf); logger->debug(tbuf2); FILE *fle = fopen(tbuf, "rt"); if (!fle) { sprintf(tbuf2, "\t Opening file '%s' failed.\n\0", tbuf); logger->debug(tbuf2); return false; } fseek(fle, 0, SEEK_END); int maxSize = ftell(fle); fclose(fle); sprintf(tbuf2, "\t File size: '%i'.\n\0", maxSize); logger->debug(tbuf2); if (maxSize < 1) { sprintf(tbuf2, "\t file too small.\n\0", tbuf); logger->debug(tbuf2); return false; } char *pBuffer = NULL; pBuffer = new char[maxSize+1]; ZeroMemory(pBuffer, sizeof(char) * (maxSize+1)); if (!readFromDisk(pKey, pBuffer, maxSize)) { return false; } if (!OpenClipboard(NULL)) { logger->debug("\t OpenClipboard.. FAILED..\n"); return false; } EmptyClipboard(); HGLOBAL hClipboardData; hClipboardData = GlobalAlloc(GMEM_DDESHARE, maxSize+1); char * pchData; pchData = (char*)GlobalLock(hClipboardData); strcpy(pchData, pBuffer); GlobalUnlock(hClipboardData); SetClipboardData(CF_TEXT, hClipboardData); logger->debug("\t CloseClipboard()"); CloseClipboard(); SAFE_DEL(pBuffer); return true; }