Previewing images in a SuperToolTip

In my previous post I mentioned the possibility of displaying a PDF page thumbnail in a tooltip to show a larger preview when the user hovers over it. Here’s what our end goal looks like:

Pdf Page SuperToolTip
The thumbnail displays a larger preview of itself when the mouse hovers above a page.

To accomplish this, we’ll add upon the PdfThumbnails solution from the last post to create this new functionality.

First, drop a ToolTipController onto the frmMain form. This component can be used to provide tooltips for DevExpress which implement the IToolTipControlClient interface necessary for displaying tooltips. Don’t worry about the nitty-gritty: DevExpress controls all seem to implement this interface allowing you to customize and create tooltips.

Once you drop the ToolTipController onto your form, make sure that you then set the grdThumbnails GridControl’s ToolTipController property to this new ToolTipController instance.

To provide our tooltips we’ll need to handle an event that is fired when the user hovers over a control (or event an element within a control, such as a single grid cell). This event comes in the form of the ToolTipController’s GetActiveObjectInfo event. Let’s create a handler for this event:


/// Get active object info event handler for the ToolTipController
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolTipController1_GetActiveObjectInfo(object sender, DevExpress.Utils.ToolTipControllerGetActiveObjectInfoEventArgs e)
WinExplorerViewHitInfo hitInfo = wvThumbnails.CalcHitInfo(e.ControlMousePosition);

if (hitInfo.IsValid == false || hitInfo.InItem == false)

ToolTipControlInfo toolTipInfo = null;
SuperToolTip toolTip = new SuperToolTip();

toolTipInfo = new ToolTipControlInfo(hitInfo.RowHandle.ToString(), "Page Preview");
ToolTipItem item1 = new ToolTipItem();
item1.Image = PdfPage.ScaleThumbnailImage(hitInfo.ItemInfo.Image, 640, 480);

toolTipInfo.SuperTip = toolTip;
e.Info = toolTipInfo;

} //End the toolTipController1_GetActiveObjectInfo() method

Our tooltip will be pretty simple–it’s just an image with no text, hyperlinks etc… We construct a SuperToolTip object, and more importantly, a ToolTipControlInfo object. The ToolTipControlInfo object is what is responsible for holding the information we’d like to show in a tooltip. That is, we can set a Title, Text or Image property, all of which are the basis of any tooltip, be it a standard tooltip or SuperToolTip.

One important thing to note is that the ToolTipControlInfo object itself has a property called “Object” (of datatype Object… a little confusing, I agree) which needs to be set to a unique value to identify what the tooltip is associated with. I do this by simply setting the property to the row handle of the WinExplorerView, since it will be unique.

The last bit of code isn’t really DevExpress-centric, but we need a way to scale the image to a manageable size because we don’t want to actually show the full size page image:

/// <summary>
/// Returns a thumbnail scaled to fit within the provided width and height ratio
/// </summary>
/// <param name="ImageToScale">Image to be scaled</param>
/// <param name="MaxWidth">New image maximum width</param>
/// <param name="MaxHeight">New image maximum height</param>
/// <returns>Scaled image</returns>
static internal Image ScaleThumbnailImage(Image ImageToScale, int MaxWidth, int MaxHeight)
    double ratioX = (double)MaxWidth / ImageToScale.Width;
    double ratioY = (double)MaxHeight / ImageToScale.Height;
    double ratio = Math.Min(ratioX, ratioY);

    int newWidth = (int)(ImageToScale.Width * ratio);
    int newHeight = (int)(ImageToScale.Height * ratio);

    Image newImage = new Bitmap(newWidth, newHeight);
    Graphics.FromImage(newImage).DrawImage(ImageToScale, 0, 0, newWidth, newHeight);

    return newImage;

}   //End the ScaleThumbnailImage() method

This method just takes the thumbnail image (which itself is actually a full-sized Bitmap of the page–the WinExplorerView scales it internally to a smaller graphic) and scales it to a new Bitmap of the dimensions requested in the MaxWidth & MaxHeight parameters.

In the future, we’ll get back to our Xpo Contact List project and use this image tooltip functionality to show preview images of our contacts in the program grids. This functionality can be helpful anywhere in your application where you display a small image and want to provide the user with a quick way to view a larger version of that image.

Download the PdfThumbnails_NEW source for our project and see it in action for yourself!

Previewing images in a SuperToolTip

Adding a thumbnail view & navigation to the PdfViewer control

If you’ve used the PdfViewer control you’ll know that it provides an easy way to display PDF documents within  your WinForms application. Currently, you can select text, manipulate a file (via the PdfDocumentProccessor non-visual component) and even fill out PDF forms. The 14.2.5 release even allows the ability to programmatically fill in PDF forms–pretty useful stuff for those of you processing electronic documents and working towards the dream of a paperless office.

One feature that I find lacking in the PdfViewer control is a good thumbnail navigation system. Adobe Reader offers this ability with a simple thumbnail navigation system; each page of the document is displayed as a small image which users can quickly scroll through. Double-clicking on a thumbnail opens the corresponding page and end users can even change the size of the thumbnail images.

Screenshot of Adobe Reader's thumbnail navigation
Screenshot of Adobe Reader’s thumbnail navigation

The DevExpress PdfViewer will display thumbnails for pages if you zoom out to about the 10-20% zoom level, but the functionality ends there. You can’t double-click one of the pages and have the viewer navigate to that particular page. How can we implement a system similar to Adobe Reader ourselves?

DevExpress's non-functional thumbnail mode.
DevExpress’s non-functional thumbnail mode.

To mimic Adobe Reader’s thumbnail function, I immediately though of a few controls that might make our job easier:

  • GalleryControl – This could easily organize and display our thumbnail images. We don’t really need any grouping functionality but that’s easy to ignore.
  • GridControl – This tends to be my default go-to for displaying a list of items/records. But that’s only the first half of the equation–after that, we’d have to decide which view type to use. The LayoutView in a single column mode would work well, but honestly, I hate the layout editor.

In the end, I decided to use the GridControl, but with the WinExplorerView instead of the LayoutView. The WinExplorerView mimics the various ways you might view a folder in Windows Explorer–details, large icons, small icons etc… This is all controlled via the OptionsViewStyles property, so we can even allow the user to toggle between styles at runtime.

At the end of this exercise, we’ll end up with something like this:

Our semi-finished product: a PdfViewer control with a sidebar of page thumbnails.
Our semi-finished product: a PdfViewer control with a sidebar of page thumbnails.

To being, we’ll create a form and place a LayoutControl onto the form. Dock the LayoutControl to fill the form, and then drop a GridControl onto the LayoutControl, followed by a PdfViewer control to the right. The GridControl can be placed in a LayoutControlGroup and the PdfViewer can just be contained within a standard LayoutControlItem. I also changed the view type of the GridControl from the default GridView to the WinExplorerView type.

The thumbnail logic is all going to be contained within a class I’ve called PdfPage. Let’s have a look at it:

namespace PdfThumbnails
    /// <summary>
    /// Encapsulates the properties and methods of a PdfPage
    /// </summary>
    sealed public class PdfPage

        #region Public properties

        /// <summary>
        /// Gets or sets the number of this Pdf Page
        /// </summary>
        public int PageNumber

        /// <summary>
        /// Gets the thumbnail image for this Pdf Page
        /// </summary>
        public Image Thumbnail
            private set;


        /// <summary>
        /// Initializes a new instance of the PdfPage class
        /// </summary>
        public PdfPage()


        /// <summary>
        /// Sets the thumbnail image for the current PdfPage
        /// </summary>
        /// <param name="DocumentViewer">PdfViewer control responsible for displaying the PdfPage</param>
        public void SetThumbnailImage(PdfViewer DocumentViewer)
            int PageWidth = 0;
            int PageHeight = 0;
            int PagePixelWidth = 0;
            int PagePixelHeight = 0;

            using (Graphics graphics = DocumentViewer.CreateGraphics())
                //Get the page dimensions
                PageWidth = (int)DocumentViewer.GetPageSize(PageNumber).Width;
                PageHeight = (int)DocumentViewer.GetPageSize(PageNumber).Height;

                //Convert the page dimensions into screen pixels
                PagePixelWidth = (PageWidth * (int)graphics.DpiX);
                PagePixelHeight = (PageHeight * (int)graphics.DpiY);

                Thumbnail = DocumentViewer.CreateBitmap(PageNumber, Math.Max(PagePixelWidth, PagePixelHeight));

            }   //End the using() statement

        }   //End the SetThumbnailImage class

    }   //End the PdfPage class
}   //End the PdfThumbnails namespace

The class is pretty sparse in and of itself–just two properties. One to keep track of the page number within the document and another to hold the thumbnail image. The important part is the SetThumbnailImage method, which is in charge of creating a thumbnail for this page.

The method requires an instance of the PdfViewer control because unfortunately, the control doesn’t offer a way to get an instance of a single visual page. Luckily, having an instance of the PdfViewer control allows to use its CreateGraphics method to get a reference to the drawing surface which will be useful for generating that thumbnail. And it is useful because the PdfViewer’s GetPageSize method returns the page’s dimensions in inches, not in pixels.

I think this was a poor decision on the part of DevExpress, because it’s not mentioned in the documentation that SizeF struct returned from the method is measured in inches and I have no clue how useful that information would be in metric-based countries. Our demonstration PDF will return 8 & 11 for the page’s width and height, respectively. Since we don’t want to create an 8px X 11px Bitmap, we need to convert these dimensions into pixels.

I’m not a graphics programmer, but I do know that DPI settings will influence the conversion between inches and pixels–after all, its name implies how many dots-per-inch there are on our display! Because of this, we can’t just multiply the page dimensions by some magic number. We have to take this DPI into account and multiply by that instead.

Once we have the page and screen dimensions, it’s a matter of using the PdfViewer’s CreateBitmap method to generate a Bitmap image of current page.

I then create a BindingSource component on the Form and set its DataSource property the PdfThumb class. After that, I set the GridControl’s DataSource to this BindingSource component. The GridControl will automatically read the scheme from this data source, but because we’re using the GridControl with a WinExplorerView there aren’t any columns. Instead, there’s a ColumnSet, which maps properties of the data source to the predefined properties of the WinExplorerView.

Since a future version of this application may allow a user to toggle between thumbnail sizes, we’ll set the values for SmallImageColumn, MediumImageColumnn, LargeImageColumn and ExtraLargeImageColumn members of that ColumnSet property. These are all set to the PdfPage’s ThumbnailImage property, and we’ll set the ColumnSet’s Description andTextColumn properties to the PageNumber property.

At this point, we have a PdfViewer control capable of displaying our PDF, a GridControl capable of displaying page thumbnails and a class capable of generating those thumbnails. The only thing we need to do is actually tell our application to generate those thumbnails at runtime when a PDF is loaded into the viewer.

Create a handler for the the PdfViewer’s DocumentChanged event as this will be fired every time a document is loaded into the PdfViewer control. After that, it’s just a matter of looping through the pages of the PdfViewer and creating an instance of the PdfPage class for each:

/// <summary>
/// Document changed event handler for the PdfViewer control
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pdfViewer1_DocumentChanged(object sender, DevExpress.XtraPdfViewer.PdfDocumentChangedEventArgs e)
    IList<PdfPage> documentPages = new List<PdfPage>(pdfViewer1.PageCount);

    for (int i = 1; i <= pdfViewer1.PageCount; i++)
        PdfPage documentPage = new PdfPage();
        documentPage.PageNumber = i;


    }   //End the for() loop

    bindingSource1.DataSource = documentPages;

}   //End the pdfViewer1_DocumentChanged() method

Once that’s done, our GridControl will automatically show those page thumbnails when the application is run and a Pdf is loaded into the viewer.

The final step is to handle the WinExplorerView’s DoubleClick event:

/// <summary>
/// Double click event handler for the Thumbnails WinExplorerView
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void wvThumbnails_DoubleClick(object sender, EventArgs e)
    PdfPage currentPage = (wvThumbnails.GetFocusedRow() as PdfPage);

    pdfViewer1.CurrentPageNumber = currentPage.PageNumber;

}   //End the wvThumbnails_DoubleClick() method

This code simply takes the current row (thumbnail) from the thumbnail grid and casts it to an instance of our PdfPage class. Since the class is nice enough to keep track of its page number on our behalf, we can tell the PdfViewer to navigate to corresponding page.

And that’s all there is to it! Once small class, a couple of event handlers and we’re done. In an upcoming post, we’ll look at adding a few additional features to this application such as:

  • Allowing the user to change the thumbnail size
  • Synchronizing the thumbnail sidebar scroll position to the PdfViewer scroll position
  • Showing a magnified image of the thumbnail when the user hovers over a thumbnail image

And don’t worry, we’ll also get back to the DxContactList Xpo tutorial soon! In the meantime, here is the full source code for this tutorial: PdfThumbnails.

Adding a thumbnail view & navigation to the PdfViewer control

Overriding XtraReport or print preview toolbar commands

I happened upon a cool question on the Support Center the other day, asking how to override the default functionality in the Print Preview window to email a document via Gmail. If you look at the default Print Preview (in either ribbon or standard toolbar configuration), you’ll see that you’re given the option to email the document in various formats (Pdf, Xls, RTF etc…): Print Preview window Doing so will typically open a dialog window which prompts you to save the file to your computer before your default email program is opened and the file is attached. This is all done via MAPI, which may not be the method you want to take. It opens the user’s default email client and constructs a blank message with the file attached. Historically, DevExpress used the 32-bit version of MAPI which causes issues if you were to build your application to 64 bit. Additionally, you may not want to save the file to your computer before sending it because then you’ll need to delete it afterwards. And if your end user doesn’t have a default email program set up on their PC, they’ll be prompted with the Windows email wizard which attempts to walk them through the process of setting up an email account. So what if you’d prefer the document to be emailed through your server or a third-party server like Gmail? At first glance you have a couple of options:

  • Create a form, place a DocumentViewer component on the form and then create your own toolbar. You’ll have to provide your own implementation for each of the various commands that are offered by the built-in Document Viewer toolbar.
  • Do the same as above, but create the default Document Viewer toolbar (or ribbon control) via the smart tag. Then, assign an ItemClick event handler to the functions you’d like to control. The problem is that your code will run first and then the default button command will run afterwards. Hardly ideal.
  • Again, create a form with a Document Viewer but remove the BarButtomItems that you want to override. Insert your own BarButtonItems for the commands that you’d like to control. There’s nothing inherently wrong with this approach unless you want to use the built-in print-preview methods offered by controls like the XtraGrid or the XtraTreeList. In this case, they’ll use the default print preview window rather than your custom one.

So it can be done, but I’m not sure if any of these options are really optimal. Fortunately for us, all of the BarButtomItems in the Document Viewer window implement an ICommandHandler interface which, when implemented, tells the Document Viewer window two important things:

  1. Can I handle this command? (done by implementing the CanHandleCommand method)
  2. How should I handle this command? (done by implementing the HandleCommand method)

All of this is detailed in the documentation topic for How to: Execute and Modify Commands in a Print Preview. So how can we apply this to the topic that was originally presented?

Assuming we have a simple project containing an XtraReport and we want to send a Pdf copy via Gmail through the standard toolbar, we’ll need to first create our own CommandHandler.

To create your own CommandHandler, create a new class in Visual Studio and name it “MyCommandHandler”. Your class will need to implement ICommandHandler. You can then tell Visual Studio to implement the interface, which will automatically insert a CanHandleCommand and a HandleCommand method.

Let’s start with the CanHandleCommand method:

public virtual bool CanHandleCommand(PrintingSystemCommand command, IPrintControl control)
    //This handler overrides the Send Pdf command.
    return command == PrintingSystemCommand.SendPdf;

This crux of this method is to tell the Document Viewer (or printing system) if this handler can process the provided command. The PrintingSystemCommand enum contains all of the commands that are available by the default toolbar/ribbon control. In this case, we’re telling the printing system that we can handle the SendPdf command ourselves and no default action is necessary.

That being said, we now have to do the heavy lifting ourselves and actually do something when the button is clicked. To do that, we provide an implementation for the HandleCommand method.

public virtual void HandleCommand(PrintingSystemCommand command, object[] args, IPrintControl control, ref bool handled)

    const string Username = "YOUR_GMAIL_USERNAME_HERE";   //your username here
    const string Password = "YOUR_GMAIL_PASSWORD_HERE"; ///your password here

    if (CanHandleCommand(command, control) == false)

    using (MailMessage mailMessage = new MailMessage())
        //Set to/from
        mailMessage.From = new MailAddress("email address here");
        mailMessage.To.Add(new MailAddress("email address here"));
        mailMessage.Subject = "Test message";
        mailMessage.Body = "This is my test email!";

        //Create an attachment
        using (MemoryStream ms = new MemoryStream())
            ms.Position = 0;
            mailMessage.Attachments.Add(new Attachment(ms, "MyFile.pdf", "application/pdf"));

            using (SmtpClient client = new SmtpClient())
                client.Host = "";
                client.Port = 587;
                client.EnableSsl = true;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential(Username, Password);


    //Ensure the default action isn't fired by setting Handled to True
    handled = true;

So here we’ve created a nice implementation that sends a Pdf copy of the document via email.

Note that I’ve decided to user a MemoryStream here instead of saving the Pdf file to the user’s PC first. This alleviates the need to save a file to the disk, but it does remove the ability to customize the Pdf. If you want to change some of the Pdf properties upon export, you can use the PdfExportOptions class offered by the ExportToPdf overload.

The only thing left to do is tell our PrintPreview window to actually use this CommandHandler. We do that via the PrintingSystem.AddCommandHandler method:

// Create a report instance, assigned to a Print Tool.
ReportPrintTool pt = new ReportPrintTool(new XtraReport1());

// Generate the report's document. This step is required
// to activate its PrintingSystem and access it later.

// Override the Send Pdf command.
pt.PrintingSystem.AddCommandHandler(new SendToGmailCommandHandler());

// Show the report's print preview.

And just like that, we’ve overrided the default behavior and created our own implementation.

Going forward, we can also use this CommandHandler for print previewing other DevExpress controls such as the GridControl. By handling the GridView’s PrintInitialize event, we can insert our CommandHandler and reuse the same implementation:

private void gridView1_PrintInitialize(object sender, DevExpress.XtraGrid.Views.Base.PrintInitializeEventArgs e)
    (e.PrintingSystem as PrintingSystemBase).AddCommandHandler(new MyCommandHandler());

The full source code is available here: CustomCommandHandler

Overriding XtraReport or print preview toolbar commands