Corrupt docx File After Adding Custom Properties Part

I spent a few days implementing a component that adds some custom properties to Office 2007 files. Using the System.IO.Packaging namespace from .NET 3.0, and looking at some sample code in some Visual Studio snippets, things went pretty smoothly. Just when I thought I was done, though, I tried opening a manipulated .docx file in Word and got the message “The file is corrupt and cannot be opened.”

Continue reading

Getting the Host’s Main Window Handle in an Office Add-in

Sometimes you want the window handle of the host application when you’re writing an Office add-in. Excel includes that as a property of the Application object in newer versions of the object model, but Word and PowerPoint don’t. I seem to remember some sample code from Microsoft that suggests using FindWindow to get the handle, but that always seems problematic:

  • You can search by class name (e.g. “OpusApp” for Word), but what if you somehow have multiple Word processes running? Which window do you get?
  • You can search by window text, but it can be really hard to figure out what the window text is.
  • You can set the Caption property on the Application object to some magic text and search for a window with the magic text, but Word throws all kinds of other stuff into the caption so this generally doesn’t work reliably.

Instead, if you’re using managed code, you can just do this:

IntPtr hwnd = Process.GetCurrentProcess().MainWindowHandle;

Underneath this uses EnumWindows and GetWindowThreadProcessId to find the right window.

Paste Special Macro for Word

I sometimes wonder how often the default paste operation in an application is appropriate. Maybe I’m abnormal (maybe?) but it seems like 73.2% of the time, I want pasted text to match the formatting of where it is going rather than where it came from. I guess the exception is when I’m copying and pasting from within the same document. The result is that I use “Paste Special” a lot.

Continue reading

DRM I’m Content With

I don’t generally buy music or ebooks online, even though I would like to. I just can’t bear the restrictive copy protection that comes attached with online purchases. In fact, I get angry as I think about the experiences I’ve had with DRM, and the ever encroaching control that content owners leverage with it. So I was surprised to discover a use of DRM that I’m actually not too bothered by. Continue reading

By Chance

A few years ago I was reading some books about biological evolution. At some point, probably reading something by Richard Dawkins, I was thinking about randomness and its ability to produce apparently non-random things. All you need is a little pressure that selects one random thing over another. So I wrote a little program that demonstrates the idea by transforming a black box into a picture through entirely random steps. Continue reading