Search code examples
c#bitmapsolidworksvsta

GetPreviewBitmapFile save preview bitmap with strange colors (SolidWorks)


I'm developing C# VSTA macro for our manufacturing department. I'm using SldWorks.GetPreviewBitMapFile to save a bitmap preview of the selected model and show it in the picturebox as shown below:

enter image description here

The code looks fine and execute fine except for the strange colors:

bool status = swApp.GetPreviewBitmapFile(filepath, configuration, "D:\\preview.bmp");
            pictureBox1.ImageLocation = "D:\\Preview.bmp";
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
            pictureBox1.Refresh();

Has anyone had a similar problem and what's the remedy?


Solution

  • Here is an example of working code:

    //to compare output
    iSwApp.GetPreviewBitmapFile(@"c:\Path\Part1.SLDPRT", "Default", @"c:\Path\Part1_0.bmp");
    
    object com = iSwApp.GetPreviewBitmap(@"c:\Path\Part1.SLDPRT", "Default");
    stdole.StdPicture pic = com as stdole.StdPicture;
    Bitmap bmp = Bitmap.FromHbitmap((IntPtr)pic.Handle);
    bmp.Save(@"c:\Path\Part1_1.bmp");
    

    There are few notes about GetPreviewBitmap from SW API:

    • Currently only in-process applications (that is, macros or add-ins) can use this method; out-of-process applications (that is, executables) will get an automation error because the IPictureDisp interface cannot be marshalled across process boundaries. This is a Microsoft behavior by design. See the Microsoft Knowledge Base for details.
    • This method is not supported in macros or out-of-process applications in SolidWorks x64.

    I was able to make it work in SolidWorks x64 only in .NET add-in and in VBA macros. Let me know if you need add-in example.