Search Results

Search found 41 results on 2 pages for 'hbitmap'.

Page 2/2 | < Previous Page | 1 2 

  • Win32 C/C++ Load Image from memory buffer

    - by Bruno
    I want to load a image (.bmp) file on a Win32 application, but I do not want to use the standard LoadBitmap/LoadImage from Windows API: I want it to load from a buffer that is already in memory. I can easily load a bitmap directly from file and print it on the screen, but this issue is making me stuck :( What I'm looking for is a function that works like this: HBITMAP LoadBitmapFromBuffer(char* buffer, int width, int height); Thanks.

    Read the article

  • Need Help Setting an Image with Transparent Background to Clipboard

    - by AMissico
    I need help setting a transparent image to the clipboard. I keep getting "handle is invalid". Basically, I need a "second set of eyes" to look over the following code. (The complete working project at ftp://missico.net/ImageVisualizer.zip.) This is an image Debug Visualizer class library, but I made the included project to run as an executable for testing. (Note that window is a toolbox window and show in taskbar is set to false.) I was tired of having to perform a screen capture on the toolbox window, open the screen capture with an image editor, and then deleting the background added because it was a screen capture. So I thought I would quickly put the transparent image onto the clipboard. Well, the problem is...no transparency support for Clipboard.SetImage. Google to the rescue...not quite. This is what I have so far. I pulled from a number of sources. See the code for the main reference. My problem is the "invalid handle" when using CF_DIBV5. Do I need to use BITMAPV5HEADER and CreateDIBitmap? Any help from you GDI/GDI+ Wizards would be greatly appreciated. public static void SetClipboardData(Bitmap bitmap, IntPtr hDC) { const uint SRCCOPY = 0x00CC0020; const int CF_DIBV5 = 17; const int CF_BITMAP = 2; //'reference //'http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/816a35f6-9530-442b-9647-e856602cc0e2 IntPtr memDC = CreateCompatibleDC(hDC); IntPtr memBM = CreateCompatibleBitmap(hDC, bitmap.Width, bitmap.Height); SelectObject(memDC, memBM); using (Graphics g = Graphics.FromImage(bitmap)) { IntPtr hBitmapDC = g.GetHdc(); IntPtr hBitmap = bitmap.GetHbitmap(); SelectObject(hBitmapDC, hBitmap); BitBlt(memDC, 0, 0, bitmap.Width, bitmap.Height, hBitmapDC, 0, 0, SRCCOPY); if (!OpenClipboard(IntPtr.Zero)) { throw new System.Runtime.InteropServices.ExternalException("Could not open Clipboard", new Win32Exception()); } if (!EmptyClipboard()) { throw new System.Runtime.InteropServices.ExternalException("Unable to empty Clipboard", new Win32Exception()); } //IntPtr hClipboard = SetClipboardData(CF_BITMAP, memBM); //works but image is not transparent //all my attempts result in SetClipboardData returning hClipboard = IntPtr.Zero IntPtr hClipboard = SetClipboardData(CF_DIBV5, memBM); //because if (hClipboard == IntPtr.Zero) { // InnerException: System.ComponentModel.Win32Exception // Message="The handle is invalid" // ErrorCode=-2147467259 // NativeErrorCode=6 // InnerException: throw new System.Runtime.InteropServices.ExternalException("Could not put data on Clipboard", new Win32Exception()); } if (!CloseClipboard()) { throw new System.Runtime.InteropServices.ExternalException("Could not close Clipboard", new Win32Exception()); } g.ReleaseHdc(hBitmapDC); } } private void __copyMenuItem_Click(object sender, EventArgs e) { using (Graphics g = __pictureBox.CreateGraphics()) { IntPtr hDC = g.GetHdc(); MemoryStream ms = new MemoryStream(); __pictureBox.Image.Save(ms, ImageFormat.Png); ms.Seek(0, SeekOrigin.Begin); Image imag = Image.FromStream(ms); // Derive BitMap object using Image instance, so that you can avoid the issue //"a graphics object cannot be created from an image that has an indexed pixel format" Bitmap img = new Bitmap(new Bitmap(imag)); SetClipboardData(img, hDC); g.ReleaseHdc(); } }

    Read the article

  • Need Help Setting Transparent Image to Clipboard

    - by AMissico
    I need help setting a transparent image to the clipboard. I keep getting "handle is invalid". Following is the specific code with the complete working project at ftp://missico.net/ImageVisualizer.zip. This is an image Debug Visualizer class library, but I made to run as executable for testing. (Note that window is a toolbox window and show in taskbar is set to false.) I was tired of having to perform a screen capture on the toolbox window, open with an image editor, and then deleting the background added due to the screen capture. So I thought I would quickly put the transparent image onto the clipboard. Well, the problem is...no transparency support for Clipboard.SetImage. Google to the rescue...not quite. This is what I have so far pulled from a number of sources. See the code for the main reference. My problem is the "invalid handle" when using CF_DIBV5. I imagine the problem is related to BITMAPV5HEADER and CreateDIBitmap. Any help from you GDI/GDI+ Wizards would be greatly appreciated. public static void SetClipboardData(Bitmap bitmap, IntPtr hDC) { const uint SRCCOPY = 0x00CC0020; const int CF_DIBV5 = 17; const int CF_BITMAP = 2; //'reference //'http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/816a35f6-9530-442b-9647-e856602cc0e2 IntPtr memDC = CreateCompatibleDC(hDC); IntPtr memBM = CreateCompatibleBitmap(hDC, bitmap.Width, bitmap.Height); SelectObject(memDC, memBM); using (Graphics g = Graphics.FromImage(bitmap)) { IntPtr hBitmapDC = g.GetHdc(); IntPtr hBitmap = bitmap.GetHbitmap(); SelectObject(hBitmapDC, hBitmap); BitBlt(memDC, 0, 0, bitmap.Width, bitmap.Height, hBitmapDC, 0, 0, SRCCOPY); if (!OpenClipboard(IntPtr.Zero)) { throw new System.Runtime.InteropServices.ExternalException("Could not open Clipboard", new Win32Exception()); } if (!EmptyClipboard()) { throw new System.Runtime.InteropServices.ExternalException("Unable to empty Clipboard", new Win32Exception()); } //IntPtr hClipboard = SetClipboardData(CF_BITMAP, memBM); //works but image is not transparent //all my attempts result in SetClipboardData returning hClipboard = IntPtr.Zero IntPtr hClipboard = SetClipboardData(CF_DIBV5, memBM); //because if (hClipboard == IntPtr.Zero) { // InnerException: System.ComponentModel.Win32Exception // Message="The handle is invalid" // ErrorCode=-2147467259 // NativeErrorCode=6 // InnerException: throw new System.Runtime.InteropServices.ExternalException("Could not put data on Clipboard", new Win32Exception()); } if (!CloseClipboard()) { throw new System.Runtime.InteropServices.ExternalException("Could not close Clipboard", new Win32Exception()); } g.ReleaseHdc(hBitmapDC); } } private void __copyMenuItem_Click(object sender, EventArgs e) { //'Applications that I have verified can paste the clipboard custom data format PNG are: //' Word 2003 //' Excel 2003 using (Graphics g = __pictureBox.CreateGraphics()) { IntPtr hDC = g.GetHdc(); MemoryStream ms = new MemoryStream(); __pictureBox.Image.Save(ms, ImageFormat.Png); ms.Seek(0, SeekOrigin.Begin); Image imag = Image.FromStream(ms); // Derive BitMap object using Image instance, so that you can avoid the issue //"a graphics object cannot be created from an image that has an indexed pixel format" Bitmap img = new Bitmap(new Bitmap(imag)); SetClipboardData(img, hDC); g.ReleaseHdc(); } }

    Read the article

  • QT: Scroll widget that renders directly to the DC

    - by shoosh
    I'm trying to create a widget which paints directly to the windows Device Context by calling getDC() and painting an HBITMAP to it. The widget I'm painting resides inside a scroll widget. I've implemented the paintEvent() and it does seem to paint but immediatly after painting the widget gets painted over again with a blank gray color. I've tried setting WA_PaintOnScreen and Qt::WA_NoSystemBackground but none of those help. In theory this should be possible since this is basically how the GLWidget works. What am I missing?

    Read the article

  • System context menu Icon not transparent like WinRAR

    - by Samir
    I added a icon at the system context menu(the popped up menu when we right mouse click on any file/foler). But the icon is not transparent(in xp its not notice able, but in vista/win7 it is clearly visible) there is a white background beneath the icon. But WinRAR or TortoiseSVN icons don't have any white background, they are transparent. I tried the following C++ code: #define BITMAP_MAIN 201 //in resource.h BITMAP_MAIN BITMAP "main.bmp" // in .rc file // showing icon in menu... HBITMAP imgMain = LoadBitmap( aHinstance, MAKEINTRESOURCE(BITMAP_MAIN) ); SetMenuItemBitmaps ( hSubmenu, uMenuIndex, MF_BYPOSITION, imgMain, imgMain); [main.bmp is 16X16] Also the icon(.bmp) is not shown fully in non-english OS. So is there be any special technique to make the icon in the system context menu transparent like WinRAR?

    Read the article

  • Is it possible to BitBlt directly on to a GDI+ bitmap?

    - by jnm2
    I am trying to BitBlt from an HBITMAP to a GDI+ bitmap. I tried this, but nothing happens: Bitmap Buffer = New Bitmap(608, 392) Graphics BufferGraphics = Graphics.FromImage(Buffer); IntPtr hBufferDC = BufferGraphics.GetHdc(); ... BitBlt(hBufferDC, x, y, width, height, hInputDC, 0, 0, SRCCOPY); EDIT: Apparently the hDC doesn't work if I acquire it and then much later use it with BitBlt. I needed to make sure the hDC was still valid. This is the solution: Bitmap Buffer = New Bitmap(608, 392) Graphics BufferGraphics = Graphics.FromImage(Buffer); ... IntPtr hBufferDC = BufferGraphics.GetHdc(); BitBlt(hBufferDC, x, y, width, height, hInputDC, 0, 0, SRCCOPY); BufferGraphics.ReleaseHdc(hBufferDC); Does anyone know why this change is necessary? Why might it not work to use an hDC that was gotten earlier as in the first example?

    Read the article

  • C++ context menu image at left side showing partially, no fully

    - by Samir
    In C++ #define BITMAP_MAIN 201 //in resource.h BITMAP_MAIN BITMAP "main.bmp" // in .rc file // showing icon in menu... HBITMAP imgMain = LoadBitmap( aHinstance, MAKEINTRESOURCE(BITMAP_MAIN) ); SetMenuItemBitmaps ( hSubmenu, uMenuIndex, MF_BYPOSITION, imgMain, imgMain); The problem is in non-English XP OS the main.bmp is showing partially in the context menu. In Vista, Window7 main.bmp is showing just fine. Also in English XP its ok. But why the image is not showing fully in non-English XP? How would I use .ico file here instead of .bmp? This is to make the image transparent.

    Read the article

  • Screen capture code produces black bitmap

    - by wadetandy
    I need to add the ability to take a screenshot of the entire screen, not just the current window. The following code produces a bmp file with the correct dimensions, but the image is completely black. What am I doing wrong? void CaptureScreen(LPCTSTR lpszFilePathName) { BITMAPFILEHEADER bmfHeader; BITMAPINFO *pbminfo; HBITMAP hBmp; FILE *oFile; HDC screen; HDC memDC; int sHeight; int sWidth; LPBYTE pBuff; BITMAP bmp; WORD cClrBits; RECT rcClient; screen = GetDC(0); memDC = CreateCompatibleDC(screen); sHeight = GetDeviceCaps(screen, VERTRES); sWidth = GetDeviceCaps(screen, HORZRES); //GetObject(screen, sizeof(BITMAP), &bmp); hBmp = CreateCompatibleBitmap ( screen, sWidth, sHeight ); // Retrieve the bitmap color format, width, and height. GetObject(hBmp, sizeof(BITMAP), (LPSTR)&bmp) ; // Convert the color format to a count of bits. cClrBits = (WORD)(bmp.bmPlanes * bmp.bmBitsPixel); if (cClrBits == 1) cClrBits = 1; else if (cClrBits bmiHeader.biSize = sizeof(BITMAPINFOHEADER); pbminfo-bmiHeader.biWidth = bmp.bmWidth; pbminfo-bmiHeader.biHeight = bmp.bmHeight; pbminfo-bmiHeader.biPlanes = bmp.bmPlanes; pbminfo-bmiHeader.biBitCount = bmp.bmBitsPixel; if (cClrBits bmiHeader.biClrUsed = (1bmiHeader.biCompression = BI_RGB; // Compute the number of bytes in the array of color // indices and store the result in biSizeImage. // The width must be DWORD aligned unless the bitmap is RLE // compressed. pbminfo-bmiHeader.biSizeImage = ((pbminfo-bmiHeader.biWidth * cClrBits +31) & ~31) /8 * pbminfo-bmiHeader.biHeight; // Set biClrImportant to 0, indicating that all of the // device colors are important. pbminfo-bmiHeader.biClrImportant = 0; CreateBMPFile(lpszFilePathName, pbminfo, hBmp, memDC); } void CreateBMPFile(LPTSTR pszFile, PBITMAPINFO pbi, HBITMAP hBMP, HDC hDC) { HANDLE hf; // file handle BITMAPFILEHEADER hdr; // bitmap file-header PBITMAPINFOHEADER pbih; // bitmap info-header LPBYTE lpBits; // memory pointer DWORD dwTotal; // total count of bytes DWORD cb; // incremental count of bytes BYTE *hp; // byte pointer DWORD dwTmp; int lines; pbih = (PBITMAPINFOHEADER) pbi; lpBits = (LPBYTE) GlobalAlloc(GMEM_FIXED, pbih-biSizeImage); // Retrieve the color table (RGBQUAD array) and the bits // (array of palette indices) from the DIB. lines = GetDIBits(hDC, hBMP, 0, (WORD) pbih-biHeight, lpBits, pbi, DIB_RGB_COLORS); // Create the .BMP file. hf = CreateFile(pszFile, GENERIC_READ | GENERIC_WRITE, (DWORD) 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, (HANDLE) NULL); hdr.bfType = 0x4d42; // 0x42 = "B" 0x4d = "M" // Compute the size of the entire file. hdr.bfSize = (DWORD) (sizeof(BITMAPFILEHEADER) + pbih-biSize + pbih-biClrUsed * sizeof(RGBQUAD) + pbih-biSizeImage); hdr.bfReserved1 = 0; hdr.bfReserved2 = 0; // Compute the offset to the array of color indices. hdr.bfOffBits = (DWORD) sizeof(BITMAPFILEHEADER) + pbih-biSize + pbih-biClrUsed * sizeof (RGBQUAD); // Copy the BITMAPFILEHEADER into the .BMP file. WriteFile(hf, (LPVOID) &hdr, sizeof(BITMAPFILEHEADER), (LPDWORD) &dwTmp, NULL); // Copy the BITMAPINFOHEADER and RGBQUAD array into the file. WriteFile(hf, (LPVOID) pbih, sizeof(BITMAPINFOHEADER) + pbih-biClrUsed * sizeof (RGBQUAD), (LPDWORD) &dwTmp, ( NULL)); // Copy the array of color indices into the .BMP file. dwTotal = cb = pbih-biSizeImage; hp = lpBits; WriteFile(hf, (LPSTR) hp, (int) cb, (LPDWORD) &dwTmp,NULL); // Close the .BMP file. CloseHandle(hf); // Free memory. GlobalFree((HGLOBAL)lpBits); }

    Read the article

  • Trying to Create a ToolBar with an ImageList, not working.

    - by blaquee
    Im trying to get my toolbar to work, with an imagelist. The images are png's and are individual So i was adding them in the ImageList in succession. But it wasnt working, Here is the code to add the Image to the ImageList HIMAGELIST CreateToolBarImages( HINSTANCE hInst) { HIMAGELIST v_ImageList = NULL; //IMAGE_LIST v_Img; HICON hIcon; HBITMAP hBit; COLORMAP cMap; COLORREF fromColor = RGB( 0,0,0 ); InitCommonControls(); v_ImageList = ImageList_Create( 32,32, ILC_MASK, 1,1 ); cMap.from = fromColor; cMap.to = ::GetSysColor ( COLOR_BTNFACE ); hBit = CreateMappedBitmap( hInst, IDB_CONSOLE, 0, &cMap, 1 ); //hBit = LoadBitmap( hInst, MAKEINTRESOURCE(IDB_CONSOLE) ); consoleImg = ImageList_Add( v_ImageList, hBit, 0 ); if( consoleImg == -1 ) return NULL; DeleteObject( hBit ); Then i create The ToolBar, but it fails at the Image function. HWND CreateToolBarButton( HWND hWndParent ) { const int ImageID = 0; const int numB = 1; COLORREF iColor; HWND hToolBar = CreateWindowEx( 0, TOOLBARCLASSNAME, NULL, WS_CHILD |TBSTYLE_LIST |TBSTYLE_FLAT | WS_VISIBLE, 0,0,0,0, hWndParent, NULL, g_hInst, NULL ); if( hToolBar == NULL ) return NULL; HIMAGELIST ImgList = CreateToolBarImages ( g_hInst); if( ImgList == NULL ) MessageBox( hWndParent, L"No Tool Images", L"BOB", MB_OK ); return NULL; Is there something im missing? or not doing?

    Read the article

  • How to properly recreate BITMAP, that was previously shared by CreateFileMapping()?

    - by zim22
    Dear friends, I need your help. I need to send .bmp file to another process (dialog box) and display it there, using MMF(Memory Mapped File) But the problem is that image displays in reversed colors and upside down. In first application I open picture from HDD and link it to the named MMF "Gigabyte_picture" HANDLE hFile = CreateFile("123.bmp", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, "Gigabyte_picture"); In second application I open mapped bmp file and at the end I display m_HBitmap on the static component, using SendMessage function. HANDLE hMappedFile = OpenFileMapping(FILE_MAP_READ, FALSE, "Gigabyte_picture"); PBYTE pbData = (PBYTE) MapViewOfFile(hMappedFile, FILE_MAP_READ, 0, 0, 0); BITMAPINFO bmpInfo = { 0 }; LONG lBmpSize = 60608; // size of the bmp file in bytes bmpInfo.bmiHeader.biBitCount = 32; bmpInfo.bmiHeader.biHeight = 174; bmpInfo.bmiHeader.biWidth = 87; bmpInfo.bmiHeader.biPlanes = 1; bmpInfo.bmiHeader.biSizeImage = lBmpSize; bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); UINT * pPixels = 0; HDC hDC = CreateCompatibleDC(NULL); HBITMAP m_HBitmap = CreateDIBSection(hDC, &bmpInfo, DIB_RGB_COLORS, (void **)& pPixels, NULL, 0); SetBitmapBits(m_HBitmap, lBmpSize, pbData); SendMessage(gStaticBox, STM_SETIMAGE, (WPARAM)IMAGE_BITMAP,(LPARAM)m_HBitmap); ///////////// HWND gStaticBox = CreateWindowEx(0, "STATIC","", SS_CENTERIMAGE | SS_REALSIZEIMAGE | SS_BITMAP | WS_CHILD | WS_VISIBLE, 10,10,380, 380, myDialog, (HMENU)-1,NULL,NULL);

    Read the article

  • OpenCV. cvFnName() works, but cv::FunName() doesn't work

    - by Innuendo
    I'm using OpenCV to write a plugin for a simulator. I've made an OpenCV project (single - not a plugin) and it works fine. When I added OpenCV libs to the plugin project, I added all libs required. Visual Studio 2010 doesn't highlight any code line with red. All looks fine and compiles fine. But in execution, the program halts with a Runtime Error on any cv::function. For example: cv::imread, or cv::imwrite. But if I replace them with cvLoadImage() and cvSaveImage(), it works fine. Why does this happen? I don't want to rewrite the whole script in old-api-style (cvFnName). It means I should change all Mat objects to IplImages, and so on. UPDATE: // preparing template ifstream ifile(tmplfilename); if ( !FILE_LOADED && ifile ) { // loading template file Mat tmpl = cv::imread(tmplfilename, 1); // << here occurs error FILE_LOADED = true; } Mat src; Bmp2Mat(hDC, hBitmap, src); TargetDetector detector(src, tmpl); detector.detectTarget(); If I change to: if ( !FILE_LOADED && ifile ) { IplImage* tmpl = 0; tmpl = cvLoadImage(tmplfilename, 1); // no error occurs } And then no error occurs. Early it displayed some Runtime Error. Now, I wanted to copy exact message and it just crashes the application (simulator, what I am pluginning). It displays window error - to kill process or no. (I can't show exact message, because I'm using russian windows now)

    Read the article

  • How do you convert bytes of bitmap into x, y location of pixels?

    - by Jon
    I have a win32 program that creates a bitmap screenshot. I am trying to figure out the x and y coordinates of the bmBits. Below is the code I have so far: UINT32 nScreenX = GetSystemMetrics(SM_CXSCREEN); UINT32 nScreenY = GetSystemMetrics(SM_CYSCREEN); HDC hdc = GetDC(NULL); HDC hdcScreen = CreateCompatibleDC(hdc); HBITMAP hbmpScreen = CreateDIBSection( hdcDesk, ( BITMAPINFO* )&bitmapInfo.bmiHeader,DIB_RGB_COLORS, &bitmapDataPtr, NULL, 0 ); SelectObject(hdcScreen, hbmpScreen); BitBlt(hdcScreen, 0, 0, nScreenX , nScreenY , hdc, 0, 0, SRCCOPY); ReleaseDC(NULL, hdc); BITMAP bmpScreen; GetObject(hbmpScreen, sizeof(bmpScreen), &bmpScreen); DWORD *pScreenPixels = (DWORD*)bmpScreen.bmBits, UINT32 x = 0; UINT32 y = 0; UINT32 nCntPixels = nScreenX * nScreenY; for(int n = 0; n < nCntPixels; n++) { x = n % nScreenX; y = n / nScreenX; //do stuff with the x and y vals } The code seem correct to me but, when I use this code the x and y values appear to be off. Where does the first pixel of bmBits start? When x and y are both 0. Is that the top left, bottom left, bottom right or top right? Thanks.

    Read the article

  • How to quickly acquire and process real time screen output

    - by Akusete
    I am trying to write a program to play a full screen PC game for fun (as an experiment in Computer Vision and Artificial Intelligence). For this experiment I am assuming the game has no underlying API for AI players (nor is the source available) so I intend to process the visual information rendered by the game on the screen. The game runs in full screen mode on a win32 system (direct-X I assume). Currently I am using the win32 functions #include <windows.h> #include <cvaux.h> class Screen { public: HWND windowHandle; HDC windowContext; HBITMAP buffer; HDC bufferContext; CvSize size; uchar* bytes; int channels; Screen () { windowHandle = GetDesktopWindow(); windowContext = GetWindowDC (windowHandle); size = cvSize (GetDeviceCaps (windowContext, HORZRES), GetDeviceCaps (windowContext, VERTRES)); buffer = CreateCompatibleBitmap (windowContext, size.width, size.height); bufferContext = CreateCompatibleDC (windowContext); SelectObject (bufferContext, buffer); channels = 4; bytes = new uchar[size.width * size.height * channels]; } ~Screen () { ReleaseDC(windowHandle, windowContext); DeleteDC(bufferContext); DeleteObject(buffer); delete[] bytes; } void CaptureScreen (IplImage* img) { BitBlt(bufferContext, 0, 0, size.width, size.height, windowContext, 0, 0, SRCCOPY); int n = size.width * size.height; int imgChannels = img->nChannels; GetBitmapBits (buffer, n * channels, bytes); uchar* src = bytes; uchar* dest = (uchar*) img->imageData; uchar* end = dest + n * imgChannels; while (dest < end) { dest[0] = src[0]; dest[1] = src[1]; dest[2] = src[2]; dest += imgChannels; src += channels; } } The rate at which I can process frames using this approach is much to slow. Is there a better way to acquire screen frames?

    Read the article

  • Windows splash screen using GDI+

    - by Luther
    The eventual aim of this is to have a splash screen in windows that uses transparency but that's not what I'm stuck on at the moment. In order to create a transparent window, I'm first trying to composite the splash screen and text on an off screen buffer using GDI+. At the moment I'm just trying to composite the buffer and display it in response to a 'WM_PAINT' message. This isn't working out at the moment; all I see is a black window. I imagine I've misunderstood something with regards to setting up render targets in GDI+ and then rendering them (I'm trying to render the screen using straight forward GDI blit) Anyway, here's the code so far: //my window initialisation code void MyWindow::create_hwnd(HINSTANCE instance, const SIZE &dim) { DWORD ex_style = WS_EX_LAYERED ; //eventually I'll be making use of this layerd flag m_hwnd = CreateWindowEx( ex_style, szFloatingWindowClass , L"", WS_POPUP , 0, 0, dim.cx, dim.cy, null, null, instance, null); SetWindowLongPtr(m_hwnd ,0, (__int3264)(LONG_PTR)this); m_display_dc = GetDC(NULL); //This was sanity check test code - just loading a standard HBITMAP and displaying it in WM_PAINT. It worked fine //HANDLE handle= LoadImage(NULL , L"c:\\test_image2.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE); m_gdip_offscreen_bm = new Gdiplus::Bitmap(dim.cx, dim.cy); m_gdi_dc = Gdiplus::Graphics::FromImage(m_gdip_offscreen_bm);//new Gdiplus::Graphics(m_splash_dc );//window_dc ;m_splash_dc //this draws the conents of my splash screen - this works if I create a GDI+ context for the window, rather than for an offscreen bitmap. //For all I know, it might actually be working but when I try to display the contents on screen, it shows a black image draw_all(); //this is just to show that drawing something simple on the offscreen bit map seems to have no effect Gdiplus::Pen pen(Gdiplus::Color(255, 0, 0, 255)); m_gdi_dc->DrawLine(&pen, 0,0,100,100); DWORD last_error = GetLastError(); //returns '0' at this stage } And here's the snipit that handles the WM_PAINT message: ---8<----------------------- //Paint message snippit case WM_PAINT: { BITMAP bm; PAINTSTRUCT ps; HDC hdc = BeginPaint(vg->m_hwnd, &ps); //get the HWNDs DC HDC hdcMem = vg->m_gdi_dc->GetHDC(); //get the HDC from our offscreen GDI+ object unsigned int width = vg->m_gdip_offscreen_bm->GetWidth(); //width and height seem fine at this point unsigned int height = vg->m_gdip_offscreen_bm->GetHeight(); BitBlt(hdc, 0, 0, width, height, hdcMem, 0, 0, SRCCOPY); //this blits a black rectangle DWORD last_error = GetLastError(); //this was '0' vg->m_gdi_dc->ReleaseHDC(hdcMem); EndPaint(vg->m_hwnd, &ps); //end paint return 1; } ---8<----------------------- My apologies for the long post. Does anybody know what I'm not quite understanding regarding how you write to an offscreen buffer using GDI+ (or GDI for that matter)and then display this on screen? Thank you for reading.

    Read the article

  • BitBlt ignores CAPTUREBLT and seems to always capture a cached copy of the target...

    - by Jake Petroules
    I am trying to capture screenshots using the BitBlt function. However, every single time I capture a screenshot, the non-client area NEVER changes no matter what I do. It's as if it's getting some cached copy of it. The client area is captured correctly. If I close and then re-open the window, and take a screenshot, the non-client area will be captured as it is. Any subsequent captures after moving/resizing the window have no effect on the captured screenshot. Again, the client area will be correct. Furthermore, the CAPTUREBLT flag seems to do absolutely nothing at all. I notice no change with or without it. Here is my capture code: QPixmap WindowManagerUtils::grabWindow(WId windowId, GrabWindowFlags flags, int x, int y, int w, int h) { RECT r; switch (flags) { case WindowManagerUtils::GrabWindowRect: GetWindowRect(windowId, &r); break; case WindowManagerUtils::GrabClientRect: GetClientRect(windowId, &r); break; case WindowManagerUtils::GrabScreenWindow: GetWindowRect(windowId, &r); return QPixmap::grabWindow(QApplication::desktop()->winId(), r.left, r.top, r.right - r.left, r.bottom - r.top); case WindowManagerUtils::GrabScreenClient: GetClientRect(windowId, &r); return QPixmap::grabWindow(QApplication::desktop()->winId(), r.left, r.top, r.right - r.left, r.bottom - r.top); default: return QPixmap(); } if (w < 0) { w = r.right - r.left; } if (h < 0) { h = r.bottom - r.top; } #ifdef Q_WS_WINCE_WM if (qt_wince_is_pocket_pc()) { QWidget *widget = QWidget::find(winId); if (qobject_cast<QDesktopWidget*>(widget)) { RECT rect = {0,0,0,0}; AdjustWindowRectEx(&rect, WS_BORDER | WS_CAPTION, FALSE, 0); int magicNumber = qt_wince_is_high_dpi() ? 4 : 2; y += rect.top - magicNumber; } } #endif // Before we start creating objects, let's make CERTAIN of the following so we don't have a mess Q_ASSERT(flags == WindowManagerUtils::GrabWindowRect || flags == WindowManagerUtils::GrabClientRect); // Create and setup bitmap HDC display_dc = NULL; if (flags == WindowManagerUtils::GrabWindowRect) { display_dc = GetWindowDC(NULL); } else if (flags == WindowManagerUtils::GrabClientRect) { display_dc = GetDC(NULL); } HDC bitmap_dc = CreateCompatibleDC(display_dc); HBITMAP bitmap = CreateCompatibleBitmap(display_dc, w, h); HGDIOBJ null_bitmap = SelectObject(bitmap_dc, bitmap); // copy data HDC window_dc = NULL; if (flags == WindowManagerUtils::GrabWindowRect) { window_dc = GetWindowDC(windowId); } else if (flags == WindowManagerUtils::GrabClientRect) { window_dc = GetDC(windowId); } DWORD ropFlags = SRCCOPY; #ifndef Q_WS_WINCE ropFlags = ropFlags | CAPTUREBLT; #endif BitBlt(bitmap_dc, 0, 0, w, h, window_dc, x, y, ropFlags); // clean up all but bitmap ReleaseDC(windowId, window_dc); SelectObject(bitmap_dc, null_bitmap); DeleteDC(bitmap_dc); QPixmap pixmap = QPixmap::fromWinHBITMAP(bitmap); DeleteObject(bitmap); ReleaseDC(NULL, display_dc); return pixmap; } Most of this code comes from Qt's QWidget::grabWindow function, as I wanted to make some changes so it'd be more flexible. Qt's documentation states that: The grabWindow() function grabs pixels from the screen, not from the window, i.e. if there is another window partially or entirely over the one you grab, you get pixels from the overlying window, too. However, I experience the exact opposite... regardless of the CAPTUREBLT flag. I've tried everything I can think of... nothing works. Any ideas?

    Read the article

  • Unable to Calculate Position within Owner-Draw Text

    - by Jonathan Wood
    I'm trying to use Visual Studio 2012 to create a Windows Forms application that can place the caret at the current position within a owner-drawn string. However, I've been unable to find a way to accurately calculate that position. I've done this successfully before in C++. I've now tried numerous methods in C#. Originally, I tried using .NET classes to determine the correct position, but then I tried accessing the Windows API directly. In some cases, I came close, but after some time I still cannot place the caret accurately. I've created a small test program and posted key parts below. I've also posted the entire project here. The exact font used is not important to me; however, my application assumes a mono-spaced font. Any help is appreciated. Form1.cs This is my main form. public partial class Form1 : Form { private string TestString; private int AveCharWidth; private int Position; public Form1() { InitializeComponent(); TestString = "123456789012345678901234567890123456789012345678901234567890"; AveCharWidth = GetFontWidth(); Position = 0; } private void Form1_Load(object sender, EventArgs e) { Font = new Font(FontFamily.GenericMonospace, 12, FontStyle.Regular, GraphicsUnit.Pixel); } protected override void OnGotFocus(EventArgs e) { Windows.CreateCaret(Handle, (IntPtr)0, 2, (int)Font.Height); Windows.ShowCaret(Handle); UpdateCaretPosition(); base.OnGotFocus(e); } protected void UpdateCaretPosition() { Windows.SetCaretPos(Padding.Left + (Position * AveCharWidth), Padding.Top); } protected override void OnLostFocus(EventArgs e) { Windows.HideCaret(Handle); Windows.DestroyCaret(); base.OnLostFocus(e); } protected override void OnPaint(PaintEventArgs e) { e.Graphics.DrawString(TestString, Font, SystemBrushes.WindowText, new PointF(Padding.Left, Padding.Top)); } protected override bool IsInputKey(Keys keyData) { switch (keyData) { case Keys.Right: case Keys.Left: return true; } return base.IsInputKey(keyData); } protected override void OnKeyDown(KeyEventArgs e) { switch (e.KeyCode) { case Keys.Left: Position = Math.Max(Position - 1, 0); UpdateCaretPosition(); break; case Keys.Right: Position = Math.Min(Position + 1, TestString.Length); UpdateCaretPosition(); break; } base.OnKeyDown(e); } protected int GetFontWidth() { int AverageCharWidth = 0; using (var graphics = this.CreateGraphics()) { try { Windows.TEXTMETRIC tm; var hdc = graphics.GetHdc(); IntPtr hFont = this.Font.ToHfont(); IntPtr hOldFont = Windows.SelectObject(hdc, hFont); var a = Windows.GetTextMetrics(hdc, out tm); var b = Windows.SelectObject(hdc, hOldFont); var c = Windows.DeleteObject(hFont); AverageCharWidth = tm.tmAveCharWidth; } catch { } finally { graphics.ReleaseHdc(); } } return AverageCharWidth; } } Windows.cs Here are my Windows API declarations. public static class Windows { [Serializable, StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct TEXTMETRIC { public int tmHeight; public int tmAscent; public int tmDescent; public int tmInternalLeading; public int tmExternalLeading; public int tmAveCharWidth; public int tmMaxCharWidth; public int tmWeight; public int tmOverhang; public int tmDigitizedAspectX; public int tmDigitizedAspectY; public short tmFirstChar; public short tmLastChar; public short tmDefaultChar; public short tmBreakChar; public byte tmItalic; public byte tmUnderlined; public byte tmStruckOut; public byte tmPitchAndFamily; public byte tmCharSet; } [DllImport("user32.dll")] public static extern bool CreateCaret(IntPtr hWnd, IntPtr hBitmap, int nWidth, int nHeight); [DllImport("User32.dll")] public static extern bool SetCaretPos(int x, int y); [DllImport("User32.dll")] public static extern bool DestroyCaret(); [DllImport("User32.dll")] public static extern bool ShowCaret(IntPtr hWnd); [DllImport("User32.dll")] public static extern bool HideCaret(IntPtr hWnd); [DllImport("gdi32.dll", CharSet = CharSet.Auto)] public static extern bool GetTextMetrics(IntPtr hdc, out TEXTMETRIC lptm); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj); [DllImport("GDI32.dll")] public static extern bool DeleteObject(IntPtr hObject); }

    Read the article

< Previous Page | 1 2