代码基本框架来源: CSDN 博主:zjlovety的专栏       地址:https://blog.csdn.net/zjlovety/article/details/24463117

public partial class WinWordViewer : UserControl
    {
        public WinWordViewer()
        {
            InitializeComponent();

this.ParentChanged += new EventHandler(WinWordViewer_ParentChanged);
            this.Disposed += new EventHandler(WinWordViewer_Disposed);
            this.Click += new EventHandler(WinWordViewer_Click);  
        }

#region 窗体事件

void WinWordViewer_Click(object sender, EventArgs e)
        {
            if (wd != null)
            {
                wd.ActiveWindow.SetFocus();  //嵌入的窗体焦点是独立与父窗体,此功能为能生效。
            }
        }

void WinWordViewer_Disposed(object sender, EventArgs e)
        {
            this.CloseControl();  //父窗体资源释放时,主动释放打开的创建的word应用、文档和进程。
        }

void WinWordViewer_ParentChanged(object sender, EventArgs e)
        {
            if (wd != null)
            {
                if (this.Parent == null)
                {
                    wd.Visible = false;  
                }
                else
                {
                    wd.Visible = true; // 当WinWordViewer加入到其他控件中时才展示。
                }
            }
        }

#endregion

public Microsoft.Office.Interop.Word.Document document;  //文档的引用
        public Microsoft.Office.Interop.Word.ApplicationClass wd = null;  //应用的引用
        public int wordWnd = 0;     //word引用的句柄
        public string filename = null;  //打开的文件名称
        private bool deactivateevents = false; //窗体激活标识

public void PreActivate()
        {
            if (wd == null) wd = new Microsoft.Office.Interop.Word.ApplicationClass();
        }

/// <summary>
        /// 关闭引用
        /// </summary>
        public void CloseControl()
        {
            try
            {
                deactivateevents = true;
                object dummy = null;
                object dummy2 = (object)false;
                if (wd != null)
                {
                    wd.Visible = false;
                }
                if (document != null)
                {
                    document.Close(ref dummy, ref dummy, ref dummy);
                }
                // Change the line below.
                if (wd != null)
                {
                    wd.Quit(ref dummy2, ref dummy, ref dummy);
                    wd = null;
                }
                deactivateevents = false;

foreach (Process pro in Process.GetProcesses()) //这里是找到那些没有界面的Word进程
                {
                    if (pro.ProcessName == "WINWORD")
                    {
                        IntPtr ip = pro.MainWindowHandle;

string str = pro.MainWindowTitle; //发现程序中打开跟用户自己打开的区别就在这个属性
                        //用户打开的str 是文件的名称,程序中打开的就是空字符串
                        if (str == "")
                        {
                            pro.Kill();
                        }
                    }
                }

//以下2种方法都无法获取进程。
                //int id;
                //int td;
                //td = User32.GetWindowThreadProcessId(new IntPtr(wordWnd), out id);
                //if (id == 0)
                //{
                //     Process[] processes = Process.GetProcesses();
                //    foreach(Process process in processes)
                //    {
                //        if (process.ProcessName == "WINWORD")
                //        {
                //            if(process.Handle == new IntPtr(wordWnd))
                //            {
                //                MessageBox.Show(process.Id.ToString());
                //            }
                //        }
                //    }
                //}
                //if (id != 0)
                //{
                //    var p = Process.GetProcessById(id);
                //    p.Kill();
                //}
            }
            catch (Exception ex)
            {
                String strErr = ex.Message;
            }
        }

/// <summary>
        /// catches Word's close event
        /// starts a Thread that send a ESC to the word window ;)
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="test"></param>
        private void OnClose(Microsoft.Office.Interop.Word.Document doc, ref bool cancel)
        {
            if (!deactivateevents)
            {
                cancel = true;
            }
        }

/// <summary>
        /// catches Word's open event
        /// just close
        /// </summary>
        /// <param name="doc"></param>
        private void OnOpenDoc(Microsoft.Office.Interop.Word.Document doc)
        {
            OnNewDoc(doc);
        }

/// <summary>
        /// catches Word's newdocument event
        /// just close
        /// </summary>
        /// <param name="doc"></param>
        private void OnNewDoc(Microsoft.Office.Interop.Word.Document doc)
        {
            if (!deactivateevents)
            {
                deactivateevents = true;
                object dummy = null;
                doc.Close(ref dummy, ref dummy, ref dummy);
                deactivateevents = false;
            }
        }

/// <summary>
        /// 加载文件
        /// </summary>
        /// <param name="t_filename"></param>
        public void LoadDocument(string t_filename)
        {
            deactivateevents = true;
            filename = t_filename;

if (wd == null) wd = new Microsoft.Office.Interop.Word.ApplicationClass();
            try
            {
                wd.DocumentBeforeClose += new Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentBeforeCloseEventHandler(OnClose);
                wd.ApplicationEvents2_Event_NewDocument += new Microsoft.Office.Interop.Word.ApplicationEvents2_NewDocumentEventHandler(OnNewDoc);
                wd.DocumentOpen += new Microsoft.Office.Interop.Word.ApplicationEvents4_DocumentOpenEventHandler(OnOpenDoc);
            }
            catch
            {
            }

if (document != null)
            {
                try
                {
                    object dummy = null;
                    wd.Documents.Close(ref dummy, ref dummy, ref dummy);
                }
                catch
                {
                }
            }

if (wordWnd == 0) wordWnd = User32.FindWindow("Opusapp", null);
            if (wordWnd != 0)
            {
                User32.SetParent(wordWnd, this.Handle.ToInt32());

object fileName = filename;
                object newTemplate = false;
                object docType = 0;
                object readOnly = true;
                object isVisible = true;
                object missing = System.Reflection.Missing.Value;

try
                {
                    if (wd == null)
                    {
                        throw new WordInstanceException();
                    }

if (wd.Documents == null)
                    {
                        throw new DocumentInstanceException();
                    }

if (wd != null && wd.Documents != null)
                    {
                        document = wd.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);
                    }

if (document == null)
                    {
                        throw new ValidDocumentException();
                    }
                }
                catch
                {
                }

try
                {
                    //int wordWndN = 0;
                    取消所有边框
                    //User32.SetWindowLong(wordWnd, GWL_STYLE, User32.GetWindowLong(wordWnd, (int)WinWordViewer.GWL_STYLE) & ~(int)Enum.WindowStyles.WS_CAPTION & ~(int)Enum.WindowStyles.WS_THICKFRAME);
                    //User32.SetWindowPos(wordWnd, wordWndN, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED);

//long style = User32.GetWindowLong(wordWnd, (int)WinWordViewer.GWL_STYLE);
                    style &= ~(int)Enum.WindowStyles.WS_SIZEBOX; //去掉可变大小
                    //style &= ~(int)Enum.WindowStyles.WS_BORDER; //去掉边框
                    //style |= (int)Enum.WindowStyles.WS_MAXIMIZE; //最大化
                    设置风格
                    //User32.SetWindowLong(wordWnd, (int)WinWordViewer.GWL_STYLE, style);

//int counter = wd.ActiveWindow.Application.CommandBars.Count;
                     //for (int i = 1; i <= counter; i++)
                     //{
                     //    wd.ActiveWindow.Application.CommandBars[i].Visible = false;
                     //    wd.ActiveWindow.View.DisplayBackgrounds = true;
                     //    wd.ActiveWindow.View.DisplayPageBoundaries = false;
                     //}
                }
                catch
                {
 
                }
            }
            deactivateevents = false;
        }
        //static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        //static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
        //static readonly IntPtr HWND_TOP = new IntPtr(0);
        //const UInt32 SWP_NOSIZE = 0x0001;
        //const UInt32 SWP_NOMOVE = 0x0002;
        //const UInt32 SWP_NOZORDER = 0x0004;
        //const UInt32 SWP_NOREDRAW = 0x0008;
        //const UInt32 SWP_NOACTIVATE = 0x0010;
        //const UInt32 SWP_FRAMECHANGED = 0x0020;
        //const UInt32 SWP_SHOWWINDOW = 0x0040;
        //const UInt32 SWP_HIDEWINDOW = 0x0080;
        //const UInt32 SWP_NOCOPYBITS = 0x0100;
        //const UInt32 SWP_NOOWNERZORDER = 0x0200;
        //const UInt32 SWP_NOSENDCHANGING = 0x0400;
        //const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
    }

public class User32
    {
        //获取句柄
        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        internal static extern int FindWindow(
        string lpClassName,
        string lpWindowName);

//设置父控件(将句柄转至父控件)
        [DllImport("User32.dll", EntryPoint = "SetParent")]
        internal static extern int SetParent(
        int hWndChild,
        int hWndNewParent);

//[DllImport("User32.dll", EntryPoint = "SetWindowLong")]
        //internal static extern int SetWindowLong(
        //int hWnd,
        //int nIndex,
        //long dwNewLong);

[DllImport("User32.dll", EntryPoint = "SetWindowLong")]
        internal static extern long SetWindowLong(
        int hWnd,
        int nIndex,
        long dwNewLong);

[DllImport("User32.dll", EntryPoint = "GetWindowLong")]
        internal static extern long GetWindowLong(
        int hWnd,
        int nIndex);

[DllImport("user32.dll", EntryPoint = "MoveWindow")]
        internal static extern int MoveWindow(
        int hWnd,
        int x,
        int y,
        int cx,
        int cy,
        bool repaint);

[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
        internal static extern bool SetWindowPos(
            int hWnd,               // handle to window
           int hWndInsertAfter,    // placement-order handle
            int X,                  // horizontal position
            int Y,                  // vertical position
            int cx,                 // width
            int cy,                 // height
            uint uFlags             // window-positioning options
            );

[DllImport("user32.dll", EntryPoint = "DrawMenuBar")]
        internal static extern Int32 DrawMenuBar(
            Int32 hWnd
            );

[DllImport("user32.dll", EntryPoint = "GetMenuItemCount")]
        internal static extern Int32 GetMenuItemCount(
            Int32 hMenu
            );

[DllImport("user32.dll", EntryPoint = "GetSystemMenu")]
        internal static extern Int32 GetSystemMenu(
            Int32 hWnd,
            bool Revert
            );

[DllImport("user32.dll", EntryPoint = "RemoveMenu")]
        internal static extern Int32 RemoveMenu(
            Int32 hMenu,
            Int32 nPosition,
            Int32 wFlags
            );

[DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hWnd, out int ID);
    }

--------------------------------------------------------------------------------------------

由于个人水平不高,对原代码的修改主要还是基于对自定义控件本身逻辑的调整。

对 word API 的使用还是比较简单。

无法成功的对调用的word引用的焦点和样式进行调整(找了其他的资料,但是无法成功运用),故很多代码选择删除或者。

转载于:https://www.cnblogs.com/DarkWill-BlackGod/p/9230291.html

基于word API 创建的可以打开word的自定义控件相关推荐

  1. html实现打开word文档,用javascript打开word文档的方法

    用javascript打开word文档的方法 首先我们新建一个html文件,并且写一个FileUpLoad以及button控件. 代码如下: 复制代码 代码如下: fileUpload 然后,在写一个 ...

  2. 把word地址做链接在线打开word

    <a href="http://loalhost:8080/document/2.doc">word</a> ie   浏览起中点击超链   如果是.doc ...

  3. word显示打印机服务器脱机,打开word显示正在连接打印机是为什么

    原因可能有以下几种: 1.可能没有安装打印机驱动 首先检查一下是否安装了打印机驱动程序.方法是:在"计算机"上右键--"属性"--"设备管理器&quo ...

  4. 咕咕数据 HTML 转 Word API 接口

    HTML 转 Word API 接口 支持网页转 Word. 1. 产品功能 超高性能转换效率: 支持将传递的 HTML 转换为 Word,支持 HTML 中的 CSS 格式在 Word 文档中的呈现 ...

  5. 【Python】生成Word写入数据 -操作Excel、Word、CSV(5)(保姆级图文注释+测试代码+api例程)

    目录 API说明: 1.创建有标题的 Word例程 2. 创建章节和段落 3. 设置字体和引用 4. 创建项目列表 5. 图片和表格 总结 欢迎关注 『Python』 系列,持续更新中 欢迎关注 『P ...

  6. word中复制、双击打开编辑公式(Axmath/mathtype)出现卡死(无响应)现象的解决方案

    问题描述: 1. 最近使用microsoft word时,发现双击打开word中已有的Axmath公式时word直接卡死未响应,要等待几分钟才能弹出Axmath的窗口: 2. 在把visio对象图复制 ...

  7. 打开word时提示需要安装包gaozhi.msi

    打开word时提示需要安装包gaozhi.msi, 重新安装也没用图文详细解决方案 最近在维护校内局域网电脑终端时发现多台机器在更新后word 2003出现异常,打开word出现提示需要安装包gaoz ...

  8. WordZ:Word终结者,基于Google API的文档自动化 电子合同发票流水账单线上集成方案

    WordZ: Word终结者, 基于Google API开发的文档自动化产品.可用于线上合同,发票,所有有关文档的业务流程.主要功能包含,创建,复制文档,填充变量,导出word,导出pdf等一系列优秀 ...

  9. 打开 WORD 报错“无法创建工作文件, 请检查临时环境变量”

    打开WORD报错"无法创建工作文件,请检查临时环境变量"

最新文章

  1. 计算机毕业论文过程管理手册,毕业论文过程管理手册(修改)-陈亚琴.doc
  2. applicationContext.xml中设置读取jdbc.properties文件
  3. Visual Studio服务器控件被警告问题
  4. 10G DB_LINK的问题
  5. lib(静态库)和dll(动态库)的生成和使用详细说明以及注意事项
  6. Windows Server AppFabric Beta 2 for For Vistual Studio 2010已经发布
  7. mysql中in的用法
  8. qq动态页面变方格_微信更新“分组显示、群管理”等功能,网友:都是QQ玩剩的姿势...
  9. linux中强大且常用命令:find、grep
  10. 四.激光SLAM框架学习之A-LOAM框架---项目工程代码介绍---2.scanRegistration.cpp--前端雷达处理和特征提取
  11. python install causes ModuleNotFoundError: No module named ‘_swigfaiss‘
  12. MAC Home-brew 和 Home-brew Cask
  13. 基于 Vue3 的颜色选择器
  14. 【EMD和EEMD】EEMD工具箱使用
  15. ensp:静态路由配置和ospf动态路由配置
  16. 农历php,php 阴历-农历-转换类代码
  17. [附源码]计算机毕业设计springboot基于微信小程序的网络办公系统
  18. 微信公众号编辑器图片上传后有白色背景
  19. 这两款iPhone不要升级iOS14.5.1 ,将会被降频!
  20. 360开机小助手的广告怎么关

热门文章

  1. vs2012 与 win7 不兼容的问题
  2. 通过键盘上下键 JS事件,控制候选词的选择项
  3. VScode 结局插件prettier和vetur格式化冲突
  4. [pytorch、学习] - 5.8 网络中的网络(NiN)
  5. 第一篇-Html标签中head标签,body标签中input系列,textarea和select标签
  6. Excel 转为 MySQL 语句
  7. 使用Configuration Manager部署及管理软件更新(2)
  8. 同批号不同批次同一单据中出现数量不限制
  9. cant find module express
  10. MongoDB 主从集群配置