上一篇的方法有很大的缺陷:(1)有的时候会掉线,主要是横线;(2)有的电脑没有画图程序,画图的方式也不唯一,有的叫无标题,有的叫未命名。
研究了整整一天,终于找到了方法,今天就只写了这一个函数
private Bitmap CopyFromWordToImage()
{
Bitmap b = null;
object Nothing = System.Reflection.Missing.Value;
object missing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Application WordApp = Marshal.GetActiveObject("Word.Application") as Microsoft.Office.Interop.Word.ApplicationClass;
Microsoft.Office.Interop.Word.Document WordDoc = WordApp.ActiveDocument;
WordDoc.ActiveWindow.Selection.WholeStory();
WordDoc.ActiveWindow.Selection.Copy();
IntPtr hwnd = ClsWindows.FindWindow(null, WordDoc.Name + " - Microsoft Word");
try
{
if (ClsWindows.OpenClipboard(hwnd))
{
IntPtr data = ClsWindows.GetClipboardData(14);
if (data != IntPtr.Zero)
{
using (Metafile mf = new Metafile(data, true))
{
int w = mf.Width;
int h = mf.Height;
int maxh = 1000;
float r = (float)(w * 1.0 / h);
if (h > maxh)
{
h = maxh;
w = (int)(h * r);
}
int maxw = 600;
if (w > maxw)
{
w = maxw;
h= (int)(w / r);
}
b = new Bitmap( w, h);
Graphics g =Graphics.FromImage(b) ;
g.Clear(Color.White);
g.DrawImage(mf, 0, 0);
b.Save(@"D:\web\" + System.Guid.NewGuid() + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg ); ;
}
}
}
}
finally { ClsWindows.CloseClipboard(); }
return b;
}
其中ClsWindows类是定义来封装API函数的
public class ClsWindows
{
[DllImport("User32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("User32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseClipboard();
[DllImport("User32.dll")]
public static extern IntPtr GetClipboardData(System.UInt32 uFormat);
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "FindWindowEx", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, uint hwndChildAfter, string lpszClass, string lpszWindow);
[DllImport("user32.dll", EntryPoint = "SendMessage", SetLastError = true, CharSet = CharSet.Auto)]
public static extern int SendMessage(IntPtr hwnd, uint wMsg, int wParam, int lParam);
[DllImport("user32.dll", EntryPoint = "SetForegroundWindow", SetLastError = true)]
private static extern void SetForegroundWindow(IntPtr hwnd);
[DllImport("user32.dll", EntryPoint = "GetMenu")]
public static extern int GetMenu(int hwnd);
[DllImport("user32.dll", EntryPoint = "GetSubMenu")]
public static extern int GetSubMenu(int hMenu, int nPos);
[DllImport("user32.dll", EntryPoint = "GetMenuItemID")]
public static extern int GetMenuItemID(int hMenu, int nPos);
[DllImport("user32.dll", EntryPoint = "PostMessage")]
public static extern int PostMessage(int hwnd, int wMsg, int wParam, int lParam);
public const int WM_COMMAND = 0x111;
}