/** ** Higher-level interface: Output Enhanced META File format (-m emf) **/ int to_emf(const GEN_PAR * pg, const OUT_PAR * po) { HANDLE outDC; int err = 0; if (!pg->quiet) Eprintf("\n\n- Writing emf code to \"%s\"\n", *po->outfile == '-' ? "stdout" : po->outfile); /* Init. */ if (*po->outfile != '-') { if ((outDC = CreateEnhMetaFile(NULL, po->outfile, NULL, "hp2xx\0\0")) == 0) { PError("hp2xx (emf)"); return ERROR; } } else { PError("hp2xx (Cant send metafile to stdout emf)"); return ERROR; } SetMapMode(outDC, MM_ANISOTROPIC); SetViewportExtEx(outDC, 10, -10, NULL); // size mult err = plotit(outDC, pg, po); CloseEnhMetaFile(outDC); if (!pg->quiet) { Eprintf("\nlines=%d moves=%d", lines, moves); Eprintf("\n"); } return err; }
bool EmfPaintEngine::end() { HENHMETAFILE metafile = CloseEnhMetaFile( metaDC ); DeleteEnhMetaFile( metafile ); DeleteDC( metaDC ); return true; }
void rectdraw0(long *w, long *x, long *y, long lw) { char tmppath[MAX_PATH], fname[MAX_PATH]; struct plot_eng plotWin32; HDC hEmf; int bg_r,bg_g,bg_b; GetTempPath(sizeof(tmppath), tmppath); sprintf(fname, "%s\\gp-ploth-%lx.emf", tmppath, time(NULL)/(24*60*60)*1000+GetTickCount()); hEmf = CreateEnhMetaFile(GetDC(NULL), fname, NULL, NULL); SetMapMode(hEmf, MM_TEXT); SelectObject(hEmf, GetStockObject(DEFAULT_GUI_FONT)); color_to_rgb(gel(GP_DATA->colormap,1), &bg_r, &bg_g, &bg_b); SetBkColor(hEmf, RGB(bg_r,bg_g,bg_b)); SetBkMode(hEmf, OPAQUE); plotWin32.sc=&SetForeground; plotWin32.pt=&DrawPoint; plotWin32.ln=&DrawLine; plotWin32.bx=&DrawRectangle; plotWin32.mp=&DrawPoints; plotWin32.ml=&DrawLines; plotWin32.st=&DrawString; plotWin32.pl=&pari_plot; plotWin32.data=(void*)hEmf; gen_rectdraw0(&plotWin32, w, x, y, lw, 1, 1); DeleteEnhMetaFile(CloseEnhMetaFile(hEmf)); ShellExecute(NULL,NULL,fname,NULL,NULL,SW_SHOWDEFAULT); }
VOID SaveMetafile(HWND hWnd) { HENHMETAFILE currentImage = RefreshMetafileDC(hWnd); TCHAR buffer[4 * MAX_LOADSTRING]; OPENFILENAME openFileName = InitializeOpenFileNameStructure(hWnd, OFN_SHOWHELP | OFN_OVERWRITEPROMPT, buffer); TCHAR szDescription[MAX_LOADSTRING]; LoadString(hInst, IDS_DESCRIPTIONSTRING, (LPWSTR)szDescription, sizeof(szDescription)); for (int i = 0; szDescription[i]!='\0'; i++) { if (szDescription[i] == '%') szDescription[i] = '\0'; } GetSaveFileName(&openFileName); GetClientRect(hWnd, &rect); HDC windowDC = GetDC(hWnd); RECT newRect = GetRect(windowDC); HDC newMetafileDC = CreateEnhMetaFile(windowDC, (LPTSTR) openFileName.lpstrFile, &newRect, (LPWSTR)szDescription); ReleaseDC(hWnd, windowDC); PlayEnhMetaFile(newMetafileDC, currentImage, &rect); currentImage = CloseEnhMetaFile(newMetafileDC); PlayEnhMetaFile(metafileDC, currentImage, &rect); ReleaseDC(hWnd, newMetafileDC); DeleteEnhMetaFile(currentImage); }
static HENHMETAFILE create_emf(void) { const RECT rect = {0, 0, 100, 100}; HDC hdc = CreateEnhMetaFileA(NULL, NULL, &rect, "HENHMETAFILE Marshaling Test\0Test\0\0"); ExtTextOutA(hdc, 0, 0, ETO_OPAQUE, &rect, "Test String", strlen("Test String"), NULL); return CloseEnhMetaFile(hdc); }
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { ENHMETAHEADER emh ; HDC hdc, hdcEMF ; HENHMETAFILE hemfOld, hemf ; PAINTSTRUCT ps ; RECT rect ; switch (message) { case WM_CREATE: // Retrieve existing metafile and header hemfOld = GetEnhMetaFile (TEXT ("..\\emf3\\emf3.emf")) ; GetEnhMetaFileHeader (hemfOld, sizeof (ENHMETAHEADER), &emh) ; // Create a new metafile DC hdcEMF = CreateEnhMetaFile (NULL, TEXT ("emf7.emf"), NULL, TEXT ("EMF7\0EMF Demo #7\0")) ; // Enumerate the existing metafile EnumEnhMetaFile (hdcEMF, hemfOld, EnhMetaFileProc, NULL, (RECT *) & emh.rclBounds) ; // Clean up hemf = CloseEnhMetaFile (hdcEMF) ; DeleteEnhMetaFile (hemfOld) ; DeleteEnhMetaFile (hemf) ; return 0 ; case WM_PAINT: hdc = BeginPaint (hwnd, &ps) ; GetClientRect (hwnd, &rect) ; rect.left = rect.right / 4 ; rect.right = 3 * rect.right / 4 ; rect.top = rect.bottom / 4 ; rect.bottom = 3 * rect.bottom / 4 ; hemf = GetEnhMetaFile (TEXT ("emf7.emf")) ; PlayEnhMetaFile (hdc, hemf, &rect) ; DeleteEnhMetaFile (hemf) ; EndPaint (hwnd, &ps) ; return 0 ; case WM_DESTROY: PostQuitMessage (0) ; return 0 ; } return DefWindowProc (hwnd, message, wParam, lParam) ; }
HENHMETAFILE CacheIconToEmf(HICON hIcon) { HENHMETAFILE result = 0; EnterCriticalSection(&csEmfCache); for (EMFCACHE *p = emfCache; p; p = p->next) if (p->hIcon == hIcon) { if (p->prev) { p->prev->next = p->next; if (p->next) p->next->prev = p->prev; p->prev = 0; emfCache->prev = p; p->next = emfCache; emfCache = p; result = CopyEnhMetaFile(emfCache->hEmf, 0); break; } } // cache new item if (!result) { EMFCACHE *newItem = new EMFCACHE; newItem->prev = 0; newItem->next = emfCache; if (emfCache) emfCache->prev = newItem; emfCache = newItem; emfCacheSize++; HDC emfdc = CreateEnhMetaFile(NULL, NULL, NULL, _T("icon")); DrawIconEx(emfdc, 0, 0, (HICON)hIcon, 16, 16, 0, NULL, DI_NORMAL); emfCache->hIcon = hIcon; emfCache->hEmf = CloseEnhMetaFile(emfdc); result = CopyEnhMetaFile(emfCache->hEmf, 0); } // tail cutoff if (emfCacheSize > 20) { int n = 0; EMFCACHE *p; for (p = emfCache; p; p = p->next) if (++n > 20) break; while (p->next) { EMFCACHE *tmp = p->next; p->next = p->next->next; delete tmp; } if (p->next) p->next->prev = p; emfCacheSize = 20; } LeaveCriticalSection(&csEmfCache); return result; }
HENHMETAFILE RefreshMetafileDC(HWND hWnd) { HDC windowDC = GetDC(hWnd); HENHMETAFILE metafileHandler = CloseEnhMetaFile(metafileDC); ReleaseDC (hWnd, metafileDC); metafileDC = InitialiseEnhMetafileDC(hWnd); return metafileHandler; }
/* width and height are in mm */ metafile newmetafile(const char *name, double width, double height) { metafile obj; HDC hDC; RECT wr; static double cppix=-1, ppix, cppiy, ppiy; /* * In theory, (cppix=ppix) and (cppiy=ppiy). However, we * use the ratio to adjust the 'reference dimension' * in case.... ("Importing graph in MsWord" thread) */ if (cppix < 0) { cppix = 25.40 * devicewidth(NULL) / devicewidthmm(NULL); ppix = 100 * devicepixelsx(NULL); cppiy = 25.40 * deviceheight(NULL) / deviceheightmm(NULL); ppiy = 100 * devicepixelsy(NULL); } /* This is all very peculiar. We would really like to create a metafile measured in some sensible units, but it seems we get it in units of 0.01mm *on the current screen* with horizontal and vertical resolution set for that screen. And of course Windows is famous for getting screen sizes wrong. */ wr.left = 0; wr.top = 0 ; wr.right = (ppix * width) / cppix ; wr.bottom = (ppiy * height) / cppiy ; /* Here the size is in 0.01mm units */ hDC = CreateEnhMetaFile(NULL, strlen(name) ? name : NULL, &wr, "GraphApp\0\0"); if ( !hDC ) { R_ShowMessage(_("Unable to create metafile")); return NULL; } obj = new_object(MetafileObject, (HANDLE) hDC, get_metafile_base()); if ( !obj ) { R_ShowMessage(_("Insufficient memory to create metafile")); DeleteEnhMetaFile(CloseEnhMetaFile(hDC)); return NULL; } /* In looks like Windows rounds up the width and height, so we do too. 1 out is common, but 2 out has been seen. This is needed to get complete painting of the background. */ obj->rect = rect(0, 0, 2+(ppix * width)/2540, 2+(ppiy * height)/2540); obj->depth = GetDeviceCaps(hDC, BITSPIXEL) * GetDeviceCaps(hDC, PLANES); obj->die = private_delmetafile; obj->drawstate = copydrawstate(); obj->drawstate->dest = obj; settext(obj, name ? name : ""); return obj; }
void COXMetaFile::CloseFile() { if(m_hDCMeta) m_hEMF=CloseEnhMetaFile(m_hDCMeta); if(m_hEMF) DeleteEnhMetaFile(m_hEMF); m_hDCMeta = NULL; m_hEMF = NULL; m_rectBounds.SetRectEmpty(); m_rectNormalized.SetRectEmpty(); m_metafileType=OXMETAFILE_NOTDEFINED; }
static void cdkillcanvas (cdCtxCanvas* ctxcanvas) { HENHMETAFILE hmf; cdwKillCanvas(ctxcanvas); hmf = CloseEnhMetaFile(ctxcanvas->hDC); DeleteEnhMetaFile(hmf); memset(ctxcanvas, 0, sizeof(cdCtxCanvas)); free(ctxcanvas); }
static void cdkillcanvas (cdCtxCanvas *ctxcanvas) { cdwKillCanvas(ctxcanvas); OpenClipboard(NULL); EmptyClipboard(); if (ctxcanvas->wtype == CDW_WMF) { HMETAFILE hmf = CloseMetaFile(ctxcanvas->hDC); HANDLE hMemG; METAFILEPICT* lpMFP; hMemG = GlobalAlloc(GHND|GMEM_DDESHARE, (DWORD)sizeof(METAFILEPICT)); lpMFP = (METAFILEPICT*) GlobalLock(hMemG); lpMFP->mm = MM_ANISOTROPIC; lpMFP->xExt = (long)(100 * ctxcanvas->canvas->w_mm); lpMFP->yExt = (long)(100 * ctxcanvas->canvas->h_mm); lpMFP->hMF = hmf; GlobalUnlock(hMemG); SetClipboardData(CF_METAFILEPICT, hMemG); } else if (ctxcanvas->wtype == CDW_EMF) { HENHMETAFILE hmf = CloseEnhMetaFile(ctxcanvas->hDC); SetClipboardData(CF_ENHMETAFILE, hmf); } else { HANDLE hDib; GdiFlush(); hDib = cdwCreateCopyHDIB(&ctxcanvas->bmiClip, ctxcanvas->bitsClip); SelectObject(ctxcanvas->hDC, ctxcanvas->hOldBitmapClip); DeleteObject(ctxcanvas->hBitmapClip); DeleteDC(ctxcanvas->hDC); SetClipboardData(CF_DIB, hDib); } CloseClipboard(); memset(ctxcanvas, 0, sizeof(cdCtxCanvas)); free(ctxcanvas); }
static HENHMETAFILE copyToMetafile (Picture me) { RECT rect; HDC dc; PRINTDLG defaultPrinter; int resolution; memset (& defaultPrinter, 0, sizeof (PRINTDLG)); defaultPrinter. lStructSize = sizeof (PRINTDLG); defaultPrinter. Flags = PD_RETURNDEFAULT | PD_RETURNDC; PrintDlg (& defaultPrinter); SetRect (& rect, my selx1 * 2540, (12 - my sely2) * 2540, my selx2 * 2540, (12 - my sely1) * 2540); dc = CreateEnhMetaFile (defaultPrinter. hDC, nullptr, & rect, L"Praat\0"); if (! dc) Melder_throw (U"Cannot create Windows metafile."); resolution = GetDeviceCaps (dc, LOGPIXELSX); // Virtual PC: 360; Parallels Desktop: 600 //Melder_fatal (U"resolution ", resolution); if (Melder_debug == 6) { DEVMODE *devMode = * (DEVMODE **) defaultPrinter. hDevMode; MelderInfo_open (); MelderInfo_writeLine (U"DEVICE CAPS:"); MelderInfo_writeLine (U"aspect x ", GetDeviceCaps (dc, ASPECTX), U" y ", GetDeviceCaps (dc, ASPECTY)); MelderInfo_writeLine (U"res(pixels) hor ", GetDeviceCaps (dc, HORZRES), U" vert ", GetDeviceCaps (dc, VERTRES)); MelderInfo_writeLine (U"size(mm) hor ", GetDeviceCaps (dc, HORZSIZE), U" vert ", GetDeviceCaps (dc, VERTSIZE)); MelderInfo_writeLine (U"pixels/inch hor ", GetDeviceCaps (dc, LOGPIXELSX), U" vert ", GetDeviceCaps (dc, LOGPIXELSY)); MelderInfo_writeLine (U"physicalOffset(pixels) hor ", GetDeviceCaps (dc, PHYSICALOFFSETX), U" vert ", GetDeviceCaps (dc, PHYSICALOFFSETY)); MelderInfo_writeLine (U"PRINTER:"); MelderInfo_writeLine (U"dmFields ", devMode -> dmFields); if (devMode -> dmFields & DM_YRESOLUTION) MelderInfo_writeLine (U"y resolution ", devMode -> dmYResolution); if (devMode -> dmFields & DM_PRINTQUALITY) MelderInfo_writeLine (U"print quality ", devMode -> dmPrintQuality); if (devMode -> dmFields & DM_PAPERWIDTH) MelderInfo_writeLine (U"paper width ", devMode -> dmPaperWidth); if (devMode -> dmFields & DM_PAPERLENGTH) MelderInfo_writeLine (U"paper length ", devMode -> dmPaperLength); if (devMode -> dmFields & DM_PAPERSIZE) MelderInfo_writeLine (U"paper size ", devMode -> dmPaperSize); if (devMode -> dmFields & DM_ORIENTATION) MelderInfo_writeLine (U"orientation ", devMode -> dmOrientation); MelderInfo_close (); } autoGraphics pictGraphics = Graphics_create_screen ((void *) dc, nullptr, resolution); Graphics_setWsViewport (pictGraphics.peek(), 0, WIN_WIDTH * resolution, 0, WIN_HEIGHT * resolution); Graphics_setWsWindow (pictGraphics.peek(), 0.0, WIN_WIDTH, 12.0 - WIN_HEIGHT, 12.0); Graphics_play (my graphics.get(), pictGraphics.peek()); HENHMETAFILE metafile = CloseEnhMetaFile (dc); return metafile; }
void CreateRoutine (HWND hwnd) { HDC hdcEMF ; HENHMETAFILE hemf ; hdcEMF = CreateEnhMetaFile (NULL, TEXT ("emf11.emf"), NULL, TEXT ("EMF11\0EMF Demo #11\0")) ; SetMapMode (hdcEMF, MM_LOENGLISH) ; DrawRuler (hdcEMF, 600, 100) ; hemf = CloseEnhMetaFile (hdcEMF) ; DeleteEnhMetaFile (hemf) ; }
int GPdestroywidget (Gwidget_t *widget) { HENHMETAFILE mfile; if (WPU->mode == 1) { mfile = CloseEnhMetaFile (GC); OpenClipboard (NULL); EmptyClipboard (); SetClipboardData (CF_ENHMETAFILE, mfile); CloseClipboard (); DeleteMetaFile (mfile); } else { EndPage (GC); EndDoc (GC); } return 0; }
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { static HENHMETAFILE hemf ; HDC hdc, hdcEMF ; PAINTSTRUCT ps ; RECT rect ; switch (message) { case WM_CREATE: hdcEMF = CreateEnhMetaFile (NULL, NULL, NULL, NULL) ; Rectangle (hdcEMF, 100, 100, 200, 200) ; MoveToEx (hdcEMF, 100, 100, NULL) ; LineTo (hdcEMF, 200, 200) ; MoveToEx (hdcEMF, 200, 100, NULL) ; LineTo (hdcEMF, 100, 200) ; hemf = CloseEnhMetaFile (hdcEMF) ; return 0 ; case WM_PAINT: hdc = BeginPaint (hwnd, &ps) ; GetClientRect (hwnd, &rect) ; rect.left = rect.right / 4 ; rect.right = 3 * rect.right / 4 ; rect.top = rect.bottom / 4 ; rect.bottom = 3 * rect.bottom / 4 ; PlayEnhMetaFile (hdc, hemf, &rect) ; EndPaint (hwnd, &ps) ; return 0 ; case WM_DESTROY: DeleteEnhMetaFile (hemf) ; PostQuitMessage (0) ; return 0 ; } return DefWindowProc (hwnd, message, wParam, lParam) ; }
static void private_delmetafile(metafile obj) { HENHMETAFILE hm; if (!obj || (obj->kind != MetafileObject)) return; hm = (HENHMETAFILE) CloseEnhMetaFile((HDC) obj->handle); if (strlen(GA_gettext(obj))) { /* real file*/ DeleteEnhMetaFile(hm); return; } if (OpenClipboard(NULL) && EmptyClipboard() && /* try to save to the*/ SetClipboardData(CF_ENHMETAFILE, hm) && /*clipboard */ CloseClipboard()) return; else { R_ShowMessage(_("Unable to save metafile to the clipboard")); DeleteEnhMetaFile(hm); return; } }
HENHMETAFILE FilterEMF(HENHMETAFILE hEmf, KEnumEMF & filter) { ENHMETAHEADER emh; GetEnhMetaFileHeader(hEmf, sizeof(emh), & emh); RECT rcFrame; memcpy(& rcFrame, & emh.rclFrame, sizeof(RECT)); HDC hDC = QuerySaveEMFFile("Filtered EMF\0", & rcFrame, NULL); if ( hDC==NULL ) return NULL; Map10umToLogical(hDC, rcFrame); filter.EnumEMF(hDC, hEmf, & rcFrame); return CloseEnhMetaFile(hDC); }
void MCWidgetContextEndOffscreen(MCContext *p_context, void *p_dc) { HDC t_metafile_dc; t_metafile_dc = (HDC)p_dc; HENHMETAFILE t_metafile; t_metafile = CloseEnhMetaFile(t_metafile_dc); UINT t_size; t_size = GetEnhMetaFileBits(t_metafile, 0, NULL); void *t_buffer; t_buffer = malloc(t_size); if (t_buffer != NULL) { GetEnhMetaFileBits(t_metafile, t_size, (LPBYTE)t_buffer); p_context -> drawpict((uint1 *)t_buffer, t_size, true, p_context -> getclip(), p_context -> getclip()); free(t_buffer); } DeleteEnhMetaFile(t_metafile); }
static int close_emf(cairo_surface_t *surface) { HDC hdc; HENHMETAFILE emf; int r; hdc = cairo_win32_surface_get_dc(surface); cairo_surface_flush(surface); cairo_surface_copy_page(surface); cairo_surface_finish(surface); r = 1; EndPage(hdc); emf = CloseEnhMetaFile(hdc); if (emf == NULL) { return 1; } DeleteEnhMetaFile(emf); /* DeleteDC() is called in the cairo library */ return r; }
void SaveEnhMetaFile(HWND hWnd) { OPENFILENAME SFile; WCHAR FileName[MAX_PATH], FilePath[MAX_PATH]; FileName[0] = '\0'; FilePath[0] = '\0'; SFile.lStructSize = sizeof(OPENFILENAME); SFile.hwndOwner = hWnd; SFile.lpstrFilter = L"EMF(*.emf)\0"; SFile.lpstrCustomFilter = 0; SFile.lpstrFile = FilePath; SFile.nMaxFile = MAX_PATH * sizeof(WCHAR); SFile.lpstrFileTitle = FileName; SFile.nMaxFileTitle = MAX_PATH * sizeof(WCHAR); SFile.lpstrInitialDir = 0; SFile.lpstrDefExt = L"emf"; SFile.lpstrTitle = L"Save file as:"; SFile.Flags = OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT; GetSaveFileName(&SFile); HDC hdcRef = GetDC(hWnd); int iWidthMM, iHeightMM, iWidthPels, iHeightPels; RECT EnhClient; iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE); iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE); iWidthPels = GetDeviceCaps(hdcRef, HORZRES); iHeightPels = GetDeviceCaps(hdcRef, VERTRES); GetClientRect(hWnd, &EnhClient); EnhClient.left = (EnhClient.left * iWidthMM * 100) / iWidthPels; EnhClient.top = (EnhClient.top * iHeightMM * 100) / iHeightPels; EnhClient.right = (EnhClient.right * iWidthMM * 100) / iWidthPels; EnhClient.bottom = (EnhClient.bottom * iHeightMM * 100) / iHeightPels; HDC hdcEmf = CreateEnhMetaFile(hdcRef, SFile.lpstrFile, &EnhClient, 0); BitBlt(hdcEmf, 0, 0, scrhor/3, scrvert/3, hdc1, scrhor/3, scrvert/3, SRCCOPY); CloseEnhMetaFile(hdcEmf); ReleaseDC(hWnd, hdcRef); }
//********************************* // OnButtonRun //********************************* void CDialogWmf::OnButtonRun() { BeginWaitCursor(); UpdateData(TRUE); // Get DC CDC *pDC = m_pDoc->GetView()->GetDC(); ASSERT(pDC); // Get view rect CRect rect; m_pDoc->GetView()->GetClientRect(&rect); rect.InflateRect(5,5); // Create metafile device context HDC hMetaDC = CreateEnhMetaFile(pDC->m_hDC,"metafile.emf",NULL,NULL); if(!hMetaDC) { AfxMessageBox("Unable to create MetaFile"); ReleaseDC(pDC); return; } // Get DC from handle CDC *pMetaDC = CDC::FromHandle(hMetaDC); ASSERT(pMetaDC); pMetaDC->SetMapMode(MM_TEXT); // Position / translation / scale glPushMatrix(); CMeshView *pView = (CMeshView *)m_pDoc->GetView(); glTranslated(pView->m_xTranslation,pView->m_yTranslation,pView->m_zTranslation); glRotatef(pView->m_xRotation, 1.0, 0.0, 0.0); glRotatef(pView->m_yRotation, 0.0, 1.0, 0.0); glRotatef(pView->m_zRotation, 0.0, 0.0, 1.0); glScalef(pView->m_xScaling,pView->m_yScaling,pView->m_zScaling); // Get OpenGL parameters GLdouble modelMatrix[16]; GLdouble projMatrix[16]; GLint viewport[4]; glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix); glGetDoublev(GL_PROJECTION_MATRIX,projMatrix); glGetIntegerv(GL_VIEWPORT,viewport); // Start rendering via std GDI 2D drawing functions CSceneGraph3d *pScene = &m_pDoc->m_SceneGraph; for(int i=0;i<pScene->NbObject();i++) { CObject3d *pObject = pScene->GetAt(i); if(pObject->GetType() == TYPE_MESH3D) // meshes only // The line mode (no sort) if(m_Mode == MODE_LINE) ((CMesh3d *)pObject)->glDrawProjectLine(pMetaDC, modelMatrix, projMatrix, viewport, m_ColorLine, m_Ratio, rect.Height()); else // The face mode (faces are z-sorted // according to their barycenter) ((CMesh3d *)pObject)->glDrawProjectFace(pMetaDC, modelMatrix, projMatrix, viewport, m_ColorLine, m_ColorFace, m_Ratio, rect.Height(), m_RatioNbFaces); } glPopMatrix(); // Close metafile HENHMETAFILE hMetaFile = CloseEnhMetaFile(hMetaDC); // Fill the clipboard (direct sent to wmf2eps or // any windows app such as Powerpoint) OpenClipboard(); EmptyClipboard(); SetClipboardData(CF_ENHMETAFILE,CopyEnhMetaFile(hMetaFile,NULL)); CloseClipboard(); // Cleanup DeleteEnhMetaFile(hMetaFile); ReleaseDC(pDC); EndWaitCursor(); }
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId; PAINTSTRUCT ps; HDC windowDC; int keys; int wheelDelta; POINT tempPoint; bool copyBeforeErase; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); switch (wmId) { case IDM_EXIT: CloseEnhMetaFile(metafileDC); DestroyWindow(hWnd); break; case IDM_SAVE: SaveMetafile(hWnd); break; case IDM_OPEN: OpenMetafile(hWnd); break; case IDM_CANCEL: /* //load from metafile copyBeforeErase = TRUE; */ shape->CancelLastAction(); break; case IDM_PEN: if (shape != NULL) shape->~Shape(); shape = new Pen(color, penWidth); break; case IDM_LINE: if (shape != NULL) shape->~Shape(); shape = new Line(color, penWidth); break; case IDM_POLYLINE: if (shape != NULL) shape->~Shape(); shape = new PolylineShape(color, penWidth); break; case IDM_POLYGON: if (shape != NULL) shape->~Shape(); shape = new PolygonShape(color, penWidth); break; case IDM_ELLIPSE: if (shape != NULL) shape->~Shape(); shape = new EllipseShape(color, penWidth); break; case IDM_RECTANGLE: if (shape != NULL) shape->~Shape(); shape = new RectangleShape(color, penWidth); break; case IDM_TEXT: if (shape != NULL) { shape->~Shape(); shape = NULL; } break; case IDM_ERASER: if (shape != NULL) shape->~Shape(); shape = new EraserShape(color, penWidth); break; case IDM_COLOR: COLORREF chosenColor; if (chosenColor = GetColor(hWnd)) color = chosenColor; shape->SetPenColor(color); break; case IDM_PENWIDTH_1: penWidth = 1; shape->SetPenWidth(penWidth); break; case IDM_PENWIDTH_2: penWidth = 2; shape->SetPenWidth(penWidth); break; case IDM_PENWIDTH_4: penWidth = 4; shape->SetPenWidth(penWidth); break; case IDM_PENWIDTH_8: penWidth = 8; shape->SetPenWidth(penWidth); break; case IDM_PENWIDTH_12: penWidth = 12; shape->SetPenWidth(penWidth); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_CREATE: DragAcceptFiles(hWnd, true); GetClientRect(hWnd, &rect); memoryDC = InitialiseMemoryDC(hWnd); metafileDC = InitialiseEnhMetafileDC(hWnd); break; case WM_DROPFILES: OpenDropedFile(hWnd, (HDROP) wParam); break; case WM_LBUTTONDOWN: /*if ((shape->isContinuous) && (copyBeforeErase)) { //copy to metafile copyBeforeErase = FALSE; }*/ startPoint.x = LOWORD(lParam); startPoint.y = HIWORD(lParam); if (shape != NULL) { isDrawing = TRUE; shape->SetStartPoint(startPoint); } else { memset(textSymbols, 0, MAX_LOADSTRING); } break; case WM_LBUTTONUP: if (shape != NULL) { if (isDrawing) { windowDC = GetDC(hWnd); BitBlt(windowDC, 0, 0, rect.right, rect.bottom, memoryDC, 0, 0, SRCCOPY); shape->Draw(memoryDC, startPoint, lParam); shape->Draw(metafileDC, startPoint, lParam); ReleaseDC(hWnd, windowDC); } if (shape->isFinished) { windowDC = GetDC(hWnd); BitBlt(windowDC, 0, 0, rect.right, rect.bottom, memoryDC, 0, 0, SRCCOPY); isDrawing = FALSE; ReleaseDC(hWnd, windowDC); } } UpdateWindow(hWnd); break; case WM_RBUTTONDOWN: if (shape != NULL) { shape->isFinished = TRUE; isDrawing = FALSE; if (shape->PolylineFirstPoint.x != -1) { windowDC = GetDC(hWnd); shape->Draw(memoryDC, startPoint, lParam); shape->Draw(metafileDC, startPoint, lParam); BitBlt(windowDC, 0, 0, rect.right, rect.bottom, memoryDC, 0, 0, SRCCOPY); ReleaseDC(hWnd, windowDC); } shape->PolylineLastPoint.x = -1; } break; case WM_MOUSEMOVE: if (shape != NULL) { if (isDrawing) { windowDC = GetDC(hWnd); if (shape->isContinuous) { tempPoint = shape->GetStartPoint(); BitBlt(windowDC, 0, 0, rect.right, rect.bottom, memoryDC, 0, 0, SRCCOPY); shape->Draw(memoryDC, startPoint, lParam); shape->SetStartPoint(tempPoint); shape->Draw(metafileDC, startPoint, lParam); } ReleaseDC(hWnd, windowDC); UpdateWindow(hWnd); PostMessage(hWnd, WM_PAINT, NULL, NULL); } } break; case WM_CHAR: if (shape == NULL) { UINT charCode = (UINT)wParam; TCHAR symbol = (TCHAR)charCode; int i = 0; while (true) { if (textSymbols[i] == '\0') { textSymbols[i] = symbol; textSymbols[i + 1] = '\0'; break; } i++; } LPSTR str = (LPSTR)textSymbols; RECT textRect; textRect.left = startPoint.x; textRect.top = startPoint.y; textRect.right = startPoint.x + 500; textRect.bottom = startPoint.y + 30; DrawText(memoryDC,(LPCWSTR)str, -1, &textRect, DT_LEFT); DrawText(metafileDC,(LPCWSTR)str, -1, &textRect, DT_LEFT); HDC windowDC = GetDC(hWnd); BitBlt(windowDC, 0, 0, rect.right, rect.bottom, memoryDC, 0, 0, SRCCOPY); ReleaseDC(hWnd, windowDC); } break; case WM_MOUSEWHEEL: if (GET_WHEEL_DELTA_WPARAM(wParam) < 0) wheelDelta = 10; else wheelDelta = -10; keys = GET_KEYSTATE_WPARAM(wParam); windowDC = GetDC(hWnd); switch(keys) { case MK_CONTROL: zoom += wheelDelta; break; case MK_SHIFT: horizontal_shift += wheelDelta; break; default: vertical_shift += wheelDelta; break; } FillRect(windowDC, &rect, (HBRUSH)(COLOR_WINDOW + 1)); StretchBlt(windowDC, horizontal_shift, vertical_shift, rect.right + zoom, rect.bottom + rect.bottom*zoom / rect.right , memoryDC, 0, 0, rect.right, rect.bottom, SRCCOPY); ReleaseDC(hWnd, windowDC); break; case WM_SIZE: RefreshWindow(hWnd); break; case WM_PAINT: windowDC = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); break; case WM_DESTROY: DeleteDC(metafileDC); PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
HBITMAP CContextMenuHelper::InitializeOwnerDrawItem(HMENU hMenu, UINT index, SIZE *lpSize) { m_iLeftOfText = 0; m_pBuffer = NULL; HBITMAP hBitmap = NULL; HRESULT hr; IContextMenu2* pcm2; if (SUCCEEDED(hr = m_lpcm->QueryInterface(IID_IContextMenu2, (LPVOID*)&pcm2))) { // get item data MENUITEMINFO mii; ZeroMemory(&mii, sizeof(MENUITEMINFO)); mii.cbSize = sizeof(MENUITEMINFO); mii.fMask = MIIM_DATA | MIIM_ID; if (::GetMenuItemInfo(hMenu, index, TRUE, &mii) && mii.dwItemData != NULL) { // get item dimensions MEASUREITEMSTRUCT mis; ZeroMemory(&mis, sizeof(MEASUREITEMSTRUCT)); mis.CtlType = ODT_MENU; mis.itemData = mii.dwItemData; mis.itemID = mii.wID; // fake ownerdraw msg if (SUCCEEDED(hr = (pcm2->HandleMenuMsg(WM_MEASUREITEM, 0, (LPARAM)&mis)))) { if (mis.itemWidth && mis.itemHeight > 0) { HDC hDC = CreateEnhMetaFile(NULL, NULL, NULL, NULL); RECT r = { 0, 0, mis.itemWidth, mis.itemHeight }; BOOL bStringFound = FALSE; // fake ownerdraw msg DRAWITEMSTRUCT dis; ZeroMemory(&dis, sizeof(DRAWITEMSTRUCT)); dis.CtlType = ODT_MENU; dis.itemID = mii.wID; dis.itemData = mii.dwItemData; dis.itemAction = ODA_DRAWENTIRE; dis.hwndItem = (HWND)hMenu; dis.hDC = hDC; dis.rcItem = r; if (SUCCEEDED(hr = pcm2->HandleMenuMsg(WM_DRAWITEM, 0, (LPARAM)&dis))) { HENHMETAFILE hEMF = CloseEnhMetaFile(hDC); // enum metafile records and search for strings char buf[MAX_PATH] = { 0 }; m_pBuffer = buf; m_iLeftOfText = 0; ::EnumEnhMetaFile(NULL, hEMF, EnhMetaFileProc, this, NULL); ::DeleteEnhMetaFile(hEMF); m_pBuffer = NULL; if (buf[0] != 0) { bStringFound = ::ModifyMenu(hMenu, index, MF_BYPOSITION | MF_STRING, mii.wID, buf); } } // Try to get bitmap hDC = ::CreateCompatibleDC(m_hDC); if (hDC != NULL) { // obtain image rect if (bStringFound) { if (m_iLeftOfText > 0) { r.left = (m_iLeftOfText - 16) / 2; r.top = (mis.itemHeight - 16) / 2; } else { r.top = (mis.itemHeight - 16) / 2; r.left = r.top; } r.right = r.left + 16; r.bottom = r.top + 16; } if (lpSize != NULL) { lpSize->cx = r.right - r.left; lpSize->cy = r.bottom - r.top; } hBitmap = ::CreateCompatibleBitmap(m_hDC, r.right - r.left, r.bottom - r.top); if (hBitmap != NULL) { HBITMAP hPrevBitmap = (HBITMAP)::SelectObject(hDC, hBitmap); // draw item on a bitmap COLORREF crBack = ::GetSysColor(COLOR_MENU); ::SetWindowOrgEx(hDC, r.left, r.top, NULL); ::FillRect(hDC, &r, ::CreateSolidBrush(crBack)); dis.hDC = hDC; pcm2->HandleMenuMsg(WM_DRAWITEM, 0, (LPARAM)&dis); ::SelectObject(hDC, hPrevBitmap); } ::DeleteDC(hDC); } } } } pcm2->Release(); } return hBitmap; }
LRESULT CMainDlg::OnSavePic(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { CSaveArgs dlg; dlg.width = picWidth; dlg.height = picHeight; dlg.inchOrMM = picInchOrMM; strcpy(dlg.fileName, picFileName); if (dlg.DoModal(m_hWnd) == IDOK) { picWidth = dlg.width; picHeight = dlg.height; picInchOrMM = dlg.inchOrMM; strcpy(picFileName, dlg.fileName); int dx, dy; int iWidthMM, iHeightMM; int iWidthPels, iHeightPels; HDC hdcRef = NULL; int isIC = FALSE; /* * Not really necessary, but useful... * This will calculate resolution for the default printer. * That generates a larger image generally and maybe will * look better when printed from a document file. */ PRINTDLG pd; memset(&pd, 0, sizeof(pd)); pd.lStructSize = sizeof(PRINTDLG); pd.Flags = PD_RETURNDEFAULT; pd.hwndOwner = m_hWnd; if (PrintDlg(&pd)) { DEVNAMES *dn = (DEVNAMES*)GlobalLock(pd.hDevNames); char *driver = ((char *)dn) + dn->wDriverOffset; char *device = ((char *)dn) + dn->wDeviceOffset; char *port = ((char *)dn) + dn->wOutputOffset; hdcRef = CreateIC(driver, device, port, NULL); if (hdcRef) isIC = TRUE; GlobalUnlock(pd.hDevNames); GlobalFree(pd.hDevNames); GlobalFree(pd.hDevMode); } if (!hdcRef) hdcRef = GetDC(); iWidthMM = GetDeviceCaps(hdcRef, HORZSIZE); iHeightMM = GetDeviceCaps(hdcRef, VERTSIZE); iWidthPels = GetDeviceCaps(hdcRef, HORZRES); iHeightPels = GetDeviceCaps(hdcRef, VERTRES); dx = GetDeviceCaps(hdcRef, LOGPIXELSX); dy = GetDeviceCaps(hdcRef, LOGPIXELSY); // Calculate bounds at output resolution RECT rcpix; rcpix.left = 0; rcpix.top = 0; if (picInchOrMM) { rcpix.right = (int) ((double)dx * (picWidth / 25.4)); rcpix.bottom = (int) ((double) dy * (picHeight / 25.4)); } else { rcpix.right = (int) ((double)dx * picWidth); rcpix.bottom = (int) ((double) dy * picHeight); } // produce a bounding box in HIMETRIC for the metafile RECT rc; rc.left = (rcpix.left * iWidthMM * 100)/iWidthPels; rc.top = (rcpix.top * iHeightMM * 100)/iHeightPels; rc.right = (rcpix.right * iWidthMM * 100)/iWidthPels; rc.bottom = (rcpix.bottom * iHeightMM * 100)/iHeightPels; HDC drawdc = CreateEnhMetaFile(hdcRef, picFileName, &rc, "Waveform Explorer, (c) Daniel R. Mitchell\0Waveform Explorer\0"); //HFONT hf = CreateFont((8*dy)/72, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, ANSI_CHARSET, // OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, PROOF_QUALITY, FF_DONTCARE|DEFAULT_PITCH, "Tahoma"); //SelectObject(drawdc, hf); wndPlot.Plot(drawdc, rcpix); HENHMETAFILE mf = CloseEnhMetaFile(drawdc); DeleteEnhMetaFile(mf); // DeleteObject(hf); if (isIC) DeleteDC(hdcRef); else ReleaseDC(hdcRef); } return 0; }
// Вызывается ТОЛЬКО в главной нити! void CPluginBackground::UpdateBackground() { if (!mn_BgPluginsCount) return; if (!ghConEmuWndDC || !IsWindow(ghConEmuWndDC)) return; if (mb_ThNeedLoad) { LoadThSet(TRUE/*Мы уже в главной нити*/); } //RECT rcClient; GetClientRect(ghConEmuWndDC, &rcClient); struct PaintBackgroundArg Arg = m_Default; Arg.cbSize = sizeof(struct PaintBackgroundArg); //m_Default.dcSizeX = Arg.dcSizeX = rcClient.right+1; //m_Default.dcSizeY = Arg.dcSizeY = rcClient.bottom+1; m_Default.dcSizeX = Arg.dcSizeX = (m_Default.rcConWorkspace.right-m_Default.rcConWorkspace.left+1)*m_Default.MainFont.nFontCellWidth; m_Default.dcSizeY = Arg.dcSizeY = (m_Default.rcConWorkspace.bottom-m_Default.rcConWorkspace.top+1)*m_Default.MainFont.nFontHeight; // ********************************************************************************** // запомнить данные из m_Default в m_Last, но т.к. там есть указатели - move не катит // ********************************************************************************** //memmove(&m_Last, &m_Default, sizeof(m_Last)); m_Last.MainFont = m_Default.MainFont; memmove(m_Last.crPalette, m_Default.crPalette, sizeof(m_Last.crPalette)); m_Last.dcSizeX = m_Default.dcSizeX; m_Last.dcSizeY = m_Default.dcSizeY; m_Last.rcDcLeft = m_Default.rcDcLeft; m_Last.rcDcRight = m_Default.rcDcRight; m_Last.rcConWorkspace = m_Default.rcConWorkspace; m_Last.conCursor = m_Default.conCursor; m_Last.FarInterfaceSettings.Raw = m_Default.FarInterfaceSettings.Raw; m_Last.FarPanelSettings.Raw = m_Default.FarPanelSettings.Raw; memmove(m_Last.nFarColors, m_Default.nFarColors, sizeof(m_Last.nFarColors)); m_Last.bPanelsAllowed = m_Default.bPanelsAllowed; // struct tag_BkPanelInfo m_Last.LeftPanel.bVisible = m_Default.LeftPanel.bVisible; m_Last.LeftPanel.bFocused = m_Default.LeftPanel.bFocused; m_Last.LeftPanel.bPlugin = m_Default.LeftPanel.bPlugin; m_Last.LeftPanel.rcPanelRect = m_Default.LeftPanel.rcPanelRect; m_Last.RightPanel.bVisible = m_Default.RightPanel.bVisible; m_Last.RightPanel.bFocused = m_Default.RightPanel.bFocused; m_Last.RightPanel.bPlugin = m_Default.RightPanel.bPlugin; m_Last.RightPanel.rcPanelRect = m_Default.RightPanel.rcPanelRect; // строки lstrcpyW(m_Last.LeftPanel.szCurDir, m_Default.LeftPanel.szCurDir); lstrcpyW(m_Last.LeftPanel.szFormat, m_Default.LeftPanel.szFormat); lstrcpyW(m_Last.LeftPanel.szHostFile, m_Default.LeftPanel.szHostFile); lstrcpyW(m_Last.RightPanel.szCurDir, m_Default.RightPanel.szCurDir); lstrcpyW(m_Last.RightPanel.szFormat, m_Default.RightPanel.szFormat); lstrcpyW(m_Last.RightPanel.szHostFile, m_Default.RightPanel.szHostFile); // ********************************************************************************** if (m_Default.dcSizeX < 1 || m_Default.dcSizeY < 1) { _ASSERTE(m_Default.dcSizeX >= 1 && m_Default.dcSizeY >= 1); return; } SetDcPanelRect(&Arg.rcDcLeft, &Arg.LeftPanel, &Arg); SetDcPanelRect(&Arg.rcDcRight, &Arg.RightPanel, &Arg); // gpTabs отстает от реальности. Arg.Place = m_Default.Place; //if (!gpTabs) // Arg.Place = pbp_Panels; //else if (gnCurrentWindowType == WTYPE_EDITOR) // Arg.Place = pbp_Editor; //else if (gnCurrentWindowType == WTYPE_VIEWER) // Arg.Place = pbp_Viewer; //else if (Arg.LeftPanel.bVisible || Arg.RightPanel.bVisible) //{ // _ASSERTE(gnCurrentWindowType == WTYPE_PANELS); // Arg.Place = pbp_Panels; //} BITMAPINFOHEADER bi = {sizeof(BITMAPINFOHEADER)}; bi.biWidth = Arg.dcSizeX; bi.biHeight = Arg.dcSizeY; bi.biPlanes = 1; bi.biBitCount = 32; //-V112 bi.biCompression = BI_RGB; //_ASSERTE(Arg.LeftPanel.bVisible || Arg.RightPanel.bVisible); HDC hScreen = GetDC(NULL); RECT rcMeta = {0,0, Arg.dcSizeX, Arg.dcSizeY}; // (in pixels) int iWidthMM = GetDeviceCaps(hScreen, HORZSIZE); if (iWidthMM <= 0) { _ASSERTE(iWidthMM>0); iWidthMM = 1024; } int iHeightMM = GetDeviceCaps(hScreen, VERTSIZE); if (iHeightMM <= 0) { _ASSERTE(iHeightMM>0); iHeightMM = 768; } int iWidthPels = GetDeviceCaps(hScreen, HORZRES); if (iWidthPels <= 0) { _ASSERTE(iWidthPels>0); iWidthPels = 0; } int iHeightPels = GetDeviceCaps(hScreen, VERTRES); if (iHeightPels <= 0) { _ASSERTE(iHeightPels>0); iHeightPels = 0; } RECT rcMetaMM = {0,0, (rcMeta.right * iWidthMM * 100)/iWidthPels, (rcMeta.bottom * iHeightMM * 100)/iHeightPels}; // (in .01-millimeter units) HDC hdc = NULL; HENHMETAFILE hEmf = NULL; COLORREF* pBits = NULL; HBITMAP hDib = NULL, hOld = NULL; #ifdef CREATE_EMF_TEMP_FILES wchar_t szEmfFile[MAX_PATH] = {}; #endif wchar_t *pszEmfFile = NULL; if (SETBACKGROUND_USE_EMF==1) { #ifdef CREATE_EMF_TEMP_FILES GetTempPath(MAX_PATH-32, szEmfFile); int nLen = lstrlen(szEmfFile); if (*szEmfFile && szEmfFile[nLen-1] != L'\\') { szEmfFile[nLen++] = L'\\'; szEmfFile[nLen] = 0; } _wsprintf(szEmfFile+nLen, SKIPLEN(31) L"CeBack%u.emf", GetCurrentProcessId()); pszEmfFile = szEmfFile; #endif hdc = CreateEnhMetaFile(hScreen, pszEmfFile, &rcMetaMM, L"ConEmu\0Far Background\0\0"); if (!hdc) { _ASSERTE(hdc!=NULL); return; } } else { hdc = CreateCompatibleDC(hScreen); if (!hdc) { _ASSERTE(hdc!=NULL); return; } _ASSERTE(pBits = NULL); hDib = CreateDIBSection(hScreen, (BITMAPINFO*)&bi, DIB_RGB_COLORS, (void**)&pBits, NULL, 0); } ReleaseDC(NULL, hScreen); hScreen = NULL; Arg.hdc = hdc; if (SETBACKGROUND_USE_EMF==1) { HBRUSH hFillBr = CreateSolidBrush ( #ifdef _DEBUG RGB(128,128,0) #else RGB(0,0,0) #endif ); FillRect(hdc, &rcMeta, hFillBr); DeleteObject(hFillBr); } else { if (!hDib || !pBits) { _ASSERTE(hDib && pBits); if (hDib) DeleteObject(hDib); if (hdc) DeleteDC(hdc); return; } hOld = (HBITMAP)SelectObject(hdc, hDib); // Залить черным - по умолчанию #ifdef _DEBUG memset(pBits, 128, bi.biWidth*bi.biHeight*4); //-V112 #else memset(pBits, 0, bi.biWidth*bi.biHeight*4); #endif } // Painting! int nProcessed = 0; MSectionLock SC; SC.Lock(csBgPlugins, TRUE); DWORD nFromLevel = 0, nNextLevel, nSuggested; DWORD dwDrawnPlaces = Arg.Place; while(true) { nNextLevel = nFromLevel; struct RegisterBackgroundArg *p = mp_BgPlugins; for(int i = 0; i < mn_BgPluginsCount; i++, p++) { if (p->Cmd != rbc_Register || !(p->dwPlaces & Arg.Place) || !(p->PaintConEmuBackground)) continue; // пустая, неактивная в данном контексте, или некорректная ячейка // Слои nSuggested = p->dwSuggestedLevel; if (nSuggested < nFromLevel) { continue; // Этот слой уже обработан } else if (nSuggested > nFromLevel) { // Этот слой нужно будет обработать в следующий раз if ((nNextLevel == nFromLevel) || (nSuggested < nNextLevel)) nNextLevel = nSuggested; continue; } // На уровне 0 (заливающий фон) должен быть только один плагин Arg.dwLevel = (nProcessed == 0) ? 0 : (nFromLevel == 0 && nProcessed) ? 1 : nFromLevel; Arg.lParam = mp_BgPlugins[i].lParam; Arg.dwDrawnPlaces = 0; //mp_BgPlugins[i].PaintConEmuBackground(&Arg); UpdateBackground_Exec(mp_BgPlugins+i, &Arg); // Что плагин покрасил (панели/редактор/вьювер считаются покрашенными по умолчанию) dwDrawnPlaces |= Arg.dwDrawnPlaces; // nProcessed++; } if (nNextLevel == nFromLevel) break; // больше слоев нет nFromLevel = nNextLevel; } SC.Unlock(); // Sending background to GUI! if (nProcessed < 1) { // Ситуация возникает при старте ConEmu, когда панелей "еще нет" //_ASSERTE(nProcessed >= 1); if (mb_BgWasSent) { mb_BgWasSent = FALSE; CESERVER_REQ *pIn = ExecuteNewCmd(CECMD_SETBACKGROUND, sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_SETBACKGROUND)); if (pIn) { pIn->Background.nType = 1; pIn->Background.bEnabled = FALSE; pIn->Background.dwDrawnPlaces = 0; CESERVER_REQ *pOut = ExecuteGuiCmd(FarHwnd, pIn, FarHwnd); if (pOut) { ExecuteFreeResult(pOut); } ExecuteFreeResult(pIn); } } } else // есть "отработавшие" плагины, обновить Background! { GdiFlush(); DWORD nBitSize = 0, nBitsError = 0; if (SETBACKGROUND_USE_EMF==1) { hEmf = CloseEnhMetaFile(hdc); hdc = NULL; nBitSize = GetEnhMetaFileBits(hEmf, 0, NULL); if (nBitSize == 0) { dwDrawnPlaces = 0; nBitsError = GetLastError(); _ASSERTE(nBitSize!=0); if (hEmf) { // В случае ошибки - сразу удаляем DeleteEnhMetaFile(hEmf); hEmf = NULL; } } } else { nBitSize = bi.biWidth*bi.biHeight*sizeof(COLORREF); } DWORD nWholeSize = sizeof(CESERVER_REQ_HDR)+sizeof(CESERVER_REQ_SETBACKGROUND)+nBitSize; //-V103 //-V119 CESERVER_REQ *pIn = ExecuteNewCmd(CECMD_SETBACKGROUND, nWholeSize); if (!pIn) { _ASSERTE(pIn); } else { pIn->Background.nType = 1; pIn->Background.bEnabled = TRUE; pIn->Background.dwDrawnPlaces = dwDrawnPlaces; if (SETBACKGROUND_USE_EMF==1) pIn->Background.bmp.bfType = 0x4645/*EF*/; else pIn->Background.bmp.bfType = 0x4D42/*BM*/; pIn->Background.bmp.bfSize = nBitSize+sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER); //-V119 pIn->Background.bmp.bfOffBits = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER); //-V119 pIn->Background.bi = bi; if (SETBACKGROUND_USE_EMF==1) { LPBYTE pBits = ((LPBYTE)&pIn->Background)+sizeof(pIn->Background); DWORD nBitsRc = (nBitSize && hEmf) ? GetEnhMetaFileBits(hEmf, nBitSize, pBits) : 0; _ASSERTE(nBitsRc == nBitSize); if (!nBitsRc) { _ASSERTE(nBitsRc!=NULL); // Отключить нафиг ExecutePrepareCmd(&pIn->hdr, CECMD_SETBACKGROUND, nWholeSize-nBitSize); pIn->Background.nType = 1; pIn->Background.bEnabled = FALSE; pIn->Background.dwDrawnPlaces = 0; } } else { memmove(((LPBYTE)&pIn->Background)+sizeof(pIn->Background), pBits, bi.biWidth*bi.biHeight*sizeof(COLORREF)); } CESERVER_REQ *pOut = ExecuteGuiCmd(FarHwnd, pIn, FarHwnd); // Вызывается ТОЛЬКО в главной нити _ASSERTE(GetCurrentThreadId() == gnMainThreadId); if (pOut) { mb_BgWasSent = TRUE; // Сбросим флажок "Ошибка уже была показана" if (pOut->BackgroundRet.nResult == esbr_OK) { mb_BgErrorShown = FALSE; } // Показать ошибку, если есть else if ((pOut->BackgroundRet.nResult > esbr_OK) && (pOut->BackgroundRet.nResult <= esbr_LastErrorNo) && (pOut->BackgroundRet.nResult != esbr_ConEmuInShutdown) && !mb_BgErrorShown) { mb_BgErrorShown = TRUE; Plugin()->ShowMessage(CEBkError_ExecFailed+pOut->BackgroundRet.nResult, 0); } ExecuteFreeResult(pOut); } else if (!mb_BgErrorShown) { mb_BgErrorShown = TRUE; Plugin()->ShowMessage(CEBkError_ExecFailed, 0); } ExecuteFreeResult(pIn); } } if (SETBACKGROUND_USE_EMF == 0) { if (hdc && hOld) SelectObject(hdc, hOld); if (hDib) DeleteObject(hDib); if (hdc) DeleteDC(hdc); } else { if (hdc) { hEmf = CloseEnhMetaFile(hdc); hdc = NULL; } if (hEmf) { DeleteEnhMetaFile(hEmf); hEmf = NULL; } } }
BOOL CDrawDoc::StoreForPrinting(CArchive& ar) { // setting up EMF DC, using default printer as reference HDC hPrt = ((CDrawApp*)AfxGetApp()) -> GetDefaultPrinterIC() ; if (!hPrt) return FALSE; RECT rect={0, 0, GetDeviceCaps(hPrt,HORZSIZE)*100, GetDeviceCaps(hPrt,VERTSIZE)*100}; CDC dc; if (! (dc.m_hDC = CreateEnhMetaFile(hPrt, NULL, &rect, NULL))) return FALSE; dc.SetAttribDC(dc.m_hDC); // recording meta file POSITION pos = GetFirstViewPosition(); CDrawView* pView = (CDrawView*)GetNextView(pos); if (pView == NULL) return FALSE; CDrawView::m_IsRecording = TRUE; pView -> OnPrepareDC(&dc, NULL); Draw(&dc, pView); CDrawView::m_IsRecording = FALSE; HENHMETAFILE hEmf = CloseEnhMetaFile(dc.m_hDC); // storing EMF into archive DWORD size = GetEnhMetaFileBits(hEmf, NULL, NULL); if (size == 0) return FALSE; HGLOBAL hglobal = GlobalAlloc(GMEM_MOVEABLE, size); if (hglobal == NULL) return FALSE; LPBYTE buf = (LPBYTE)GlobalLock(hglobal); if (buf == NULL) return FALSE; if (GetEnhMetaFileBits(hEmf,size,buf) != size) return FALSE; SEPFILEHEADER header; // set EMF size (header) header.dwEmfSize = size; // get text objects count pos = m_objects.GetHeadPosition(); DWORD count=0; while (pos != NULL) { CDrawText* pObj = (CDrawText*)(m_objects.GetNext(pos)); if (pObj->GetLogFontCopy() != NULL) count++; } // set text records (header) header.dwTextRecords = count; // set page size (in logical) (header) header.sizePage = GetSize(); // write header ar.Write(&header,sizeof(SEPFILEHEADER)); // write EMF into archive ar.Write(buf, size); GlobalUnlock(hglobal); GlobalFree(hglobal); DeleteEnhMetaFile(hEmf); // Save text objects for job-info realization and printing // write text records into archive pos = m_objects.GetHeadPosition(); while (pos != NULL) { CDrawText* pObj = (CDrawText*)(m_objects.GetNext(pos)); LOGFONT *plf; if ((plf=pObj->GetLogFontCopy()) != NULL) // is text object { TEXTBOX tbox; tbox.position = pObj->m_position; tbox.color = pObj->m_color; tbox.align = pObj->m_align; tbox.lf = pObj->m_lf; strncpy(tbox.text,pObj->m_text,SEPMAXTEXT); ar.Write(&tbox,sizeof(TEXTBOX)); } } return TRUE; }
/* It is recommended to redraw the window after this call. */ void HEndSpoolGraf() { WritingToMeta = FALSE; CloseEnhMetaFile(memDC); memDC = DCSaved; }
// // Draw a series of "tabs" into a meta-file, // which we will use to custom-draw one of the inserted // scrollbar buttons // void InitMetaFile(void) { HDC hdcEMF; RECT rect; int totalwidth = 120; int width = 110, height = GetSystemMetrics(SM_CYHSCROLL); LOGFONT lf; POINT pts[4]; int tabwidth = 40, tabxslope = 5; pts[0].x = 0; pts[0].y = 0; pts[1].x = tabxslope; pts[1].y = height - 1; pts[2].x = tabwidth - tabxslope; pts[2].y = height - 1; pts[3].x = tabwidth; pts[3].y = 0; hpen = CreatePen(PS_SOLID,0,GetSysColor(COLOR_3DSHADOW)); whitepen = CreatePen(PS_INSIDEFRAME,0,RGB(0xff,0xff,0xff)); SetRect(&rect, 0, 0, totalwidth, height+1); hdcEMF = CreateEnhMetaFile(NULL, NULL, NULL, NULL); ZeroMemory(&lf, sizeof(lf)); lf.lfHeight = -MulDiv(7, GetDeviceCaps(hdcEMF, LOGPIXELSY), 72); lf.lfPitchAndFamily = DEFAULT_PITCH; lf.lfCharSet = ANSI_CHARSET; lstrcpy(lf.lfFaceName, "Arial");//Small fonts"); hfont = CreateFontIndirect(&lf); pts[0].x = 0; pts[0].y = 0; pts[1].x = tabxslope; pts[1].y = height - 1; pts[2].x = tabwidth - tabxslope; pts[2].y = height - 1; pts[3].x = tabwidth; pts[3].y = 0; FillRect (hdcEMF, &rect, GetSysColorBrush(COLOR_3DFACE));//GetStockObject(WHITE_BRUSH); //fit as many lines in as space permits SelectObject(hdcEMF, GetSysColorBrush(COLOR_3DFACE)); DrawTab(hdcEMF, width-tabwidth, tabwidth, height - 1, tabxslope, FALSE); DrawTab(hdcEMF, width-tabwidth-tabwidth+tabxslope, tabwidth, height - 1, tabxslope, FALSE); DrawTab(hdcEMF, 0, tabwidth, height - 1, tabxslope, TRUE); SelectObject(hdcEMF, hpen); MoveToEx(hdcEMF, 110, 0, 0); LineTo(hdcEMF, totalwidth, 0); SelectObject(hdcEMF, hfont); SetBkMode(hdcEMF, TRANSPARENT); TextOut(hdcEMF, 10,1, "Build", 5); TextOut(hdcEMF, 42,1, "Debug", 5); TextOut(hdcEMF, 78,1, "Result", 6); SelectObject(hdcEMF, oldpen); DeleteObject(hpen); DeleteObject(whitepen); hemf = CloseEnhMetaFile(hdcEMF); }
HRESULT CSTEditorDoc::GetPages (CStringArray &pages) { TCHAR szTempName[_MAX_PATH]; TCHAR szPath[_MAX_PATH]; long lLinesPerPage; long lLineNum = 0; CDC dcPrint; TEXTMETRIC tm; CFont Font; CFont * pOldFont; long lCharsPerLine = 80; if (FAILED(AttachPrinterDC(&dcPrint))) { return (E_FAIL); } dcPrint.m_bPrinting = TRUE; CRect rect; rect.SetRect( 0, 0, GetPageWidth (), GetPageHeight () ); // printing lLinesPerPage = GetPrintLinesPerPage(&dcPrint); HDC hdcMeta = NULL; CDC dcMeta; for (LINEDESC * pLine = m_Edit.m_pLine; NULL != pLine; pLine = pLine->pNext) { bool bSuccess; CString strText; bSuccess = m_Edit.ExpandLine (pLine, strText); ASSERT (bSuccess); strText.TrimRight (); // if text line is empty make it a line with a single // blank character if (strText.IsEmpty()) { strText = _T(" "); } while (!strText.IsEmpty()) { if (hdcMeta == NULL) { VERIFY(GetTempPath(sizeof(szPath), szPath) != 0); VERIFY(GetTempFileName(szPath, _T("pst"), 0, szTempName) != 0); pages.Add( szTempName ); CString strDesc; CString strAppl; TCHAR* pBuf; strAppl = GetPathName(); // read documentation of CreateEnhMetaFile() to understand the // formatting of this string strDesc.Format("STEditor %s Page %d ", strAppl, pLine->iLineNo); pBuf = strDesc.GetBuffer(0); pBuf[8] = 0; pBuf[strDesc.GetLength() - 1] = 0; strDesc.ReleaseBuffer(); hdcMeta = ::CreateEnhMetaFile( dcPrint, szTempName, &rect, strDesc); if (!hdcMeta) { return (E_FAIL); } dcMeta.Attach(hdcMeta); dcMeta.m_bPrinting = TRUE; dcMeta.SetMapMode (MM_TEXT); pOldFont = SelectPrintFont(&dcMeta, &Font); dcMeta.GetTextMetrics(&tm); CSize tmSize(tm.tmAveCharWidth, tm.tmHeight); dcMeta.LPtoHIMETRIC(&tmSize); lCharsPerLine = GetPageWidth() / tmSize.cx; } dcMeta.TextOut(0, lLineNum * tm.tmHeight, strText.Left(lCharsPerLine)); lLineNum++; if (strText.GetLength() > lCharsPerLine) { strText = strText.Mid(lCharsPerLine); } else { strText = _T(""); } if (lLineNum >= lLinesPerPage) { lLineNum = 0; dcMeta.SelectObject(pOldFont); Font.DeleteObject(); dcMeta.Detach(); DeleteEnhMetaFile (CloseEnhMetaFile(hdcMeta)); hdcMeta = NULL; } } } if (NULL != hdcMeta) { dcMeta.SelectObject(pOldFont); dcMeta.Detach(); DeleteEnhMetaFile (CloseEnhMetaFile(hdcMeta)); hdcMeta = NULL; } return (S_OK); }