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

代码基本框架来源: 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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/266787.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

台式计算机机箱都一样吗,别以为组装台式机很简单,机箱选择大有学问

原标题&#xff1a;别以为组装台式机很简单&#xff0c;机箱选择大有学问曾经组装台式机的时候对于机箱完全没有在意&#xff0c;总觉得随便选择一款就可以了&#xff0c; 而且是挑便宜的选择&#xff0c;而那些机箱有便宜也有贵&#xff0c;其实里面的设计完全不一样&#xff…

解压ubi文件_Linux 文件压缩与解压相关

tar [-cxtzjvfpPN] 文件与目录 ....参数&#xff1a;-c &#xff1a;建立一个压缩文件的参数指令-x &#xff1a;解开一个压缩文件的参数指令-t &#xff1a;查看压缩文件里面的文件特别注意&#xff1a; c/x/t 同时只能存在一个&#xff0c;原因是我们不可能同时压缩与解压缩。…

五大板块(3)—— 结构体

参考&#xff1a;五大板块&#xff08;3&#xff09;—— 结构体 作者&#xff1a;丶PURSUING 发布时间&#xff1a; 2021-03-18 16:02:43 网址&#xff1a;https://blog.csdn.net/weixin_44742824/article/details/114981743 目录结构体的三种定义赋值方法结构体数组结构体指针…

tp5更改入口文件到根目录的方法分享

tp5把入口文件放到了public目录中&#xff0c;对于服务器或者vps来说没啥&#xff0c;因为可以指定目录&#xff0c;但是对于虚拟主机就不行了&#xff0c;我们必须吧index.php这入口文件放到根目录&#xff0c;那么我么需要改一下相对的引入文件的路径就可以了&#xff0c;代码…

html 查找添加联系人,使用phonegap查找联系人的实现方法

实例如下&#xff1a;Database Exampledocument.addEventListener("deviceready", onDeviceReady, false);function onDeviceReady() {}function onSuccess(contacts){document.write(contacts.lengthcontacts found.);for(var i0;ifor(var j0;jdocument.write("…

实现连麦_微信年底放了个大招,视频号重磅升级,打赏直播连麦美颜抽奖齐上...

期待已久的视频号连麦功能来了。这次来的不仅有连麦功能&#xff0c;还有视频号打赏的微信豆体系&#xff0c;创作者想要的入口也有了。让我们一起来看看有什么新功能吧&#xff01;太长不看版本&#xff1a;「附近的人」变「附近的直播和人」连麦上线&#xff0c;还有美颜、抽…

【转】 .NET 打印水晶报表(CrystalReport)时,出现“查询引擎错误 C:/DO...

2019独角兽企业重金招聘Python工程师标准>>> 本地开发环境&#xff1a; Win XP, Visual Studio 2003 Oracle 项目背景&#xff1a; WinForm 工程&#xff0c;在一个表单中用Treeview控件显示 部门层级信息&#xff0c;然后有 按照相同格式&#xff08;layout…

洛谷 1226 取余运算||快速幂

洛谷 取余运算||快速幂 1226 其实比起楼下的大佬们&#xff0c;我主要是多了些位运算和讲解。 想法一&#xff1a; 直接输出 pow(b,q)%k 嗯~~勇气可嘉&#xff0c;但是看一眼数据范围&#xff08;长整型&#xff09;就会意识到&#xff0c;这个方法也许一个点都过不了。 想法二…

html5 查看图片,html5实现图片预览和查看原图

一、页面元素只有三个简单元素&#xff1a;拖拽区域二、添加简单的样式&#xff1a;.dragarea{width:300px;height:100px;background:#ddd;text-align:center;line-height:100px;}.drag_hover{background:rgba(0,0,0,.4) !important;}.item{width:300px;height:100px;float:lef…

五大板块(4)——链表

参考&#xff1a;五大板块&#xff08;4&#xff09;——链表 作者&#xff1a;丶PURSUING 发布时间&#xff1a; 2021-02-15 09:33:29 网址&#xff1a;https://blog.csdn.net/weixin_44742824/article/details/114981905 目录一、对比链表与数组同样是存放一串数据&#xff0…

boolean类型默认值_「软帝学院」Java的基本数据类型

Java的基本数据类型Java的两大数据类型: 内置数据类型 引用数据类型内置数据类型Java语言提供了八种基本类型。六种数字类型(四个整数型&#xff0c;两个浮点型)&#xff0c;一种字符类型&#xff0c;还有一种布尔型。byte&#xff1a; byte数据类型是8位、有符号的&#xff0c…

Quickly Find/ Open a file in Visual Studio

ctrl/, enter ">of " search item http://codeblog.shawson.co.uk/quickly-find-open-a-file-in-visual-studio/转载于:https://www.cnblogs.com/joe-yang/archive/2012/10/19/2731201.html

poj 3070

题面 大意就是求斐波那契数列第n项&#xff0c;做法为矩阵快速幂。 代码 #include<iostream> #include<cstdio> #include<cstring> #define LL long longusing namespace std; const int mod 10000; struct Mat{LL a[4][4];Mat(){memset(a,0,sizeof(a));}M…

计算机组装与维修预习,《计算机组装与维修》预习报告、实习报告撰写要求.docx...

《计算机组装与维修》预习报告、实习报告撰写要求本次《计算机组装与维修》课程的实验报告由两部分组成&#xff1a;预习报告和实习报告(总结)。其要求除了必须符合“《计算机组装与维修》课程考核标准及管理办法”外&#xff0c;强调要求预习报告要求每个参加实习的同学必须在…

Updating -- Linux小知识

没想到&#xff0c;10几年后又开始重拾这些曾经学习和使用过的知识&#xff0c;也许一切都是轮回&#xff0c;还好能捡起来。 1. 常用命令(参考 Linux 命令大全 | 菜鸟教程) #命令说明样例1whoami当前用户ID 2id当前用户ID 和 用户组IDid -un # 用户名 id -gn # 用户组…

五大板块(5)——字符串

参考&#xff1a;五大板块&#xff08;5&#xff09;——字符串 作者&#xff1a;丶PURSUING 发布时间&#xff1a; 2021-03-18 16:03:48 网址&#xff1a;https://blog.csdn.net/weixin_44742824/article/details/114982019 目录一、字符串的定义方式与输出二、字符串的结尾是…

潘多拉设置有线中继_避坑指南:购买无线中继器必看

房子太大&#xff0c;一台路由器容易覆盖不全&#xff0c;或者想蹭隔壁老王家的WiFi&#xff0c;这时候需要用到无线中继器。无线中继器主要作为无线路由器的补充产品&#xff0c;选得好就是锦上添花&#xff0c;选不好依旧是气到爆炸。所以&#xff0c;在购买无线中继器前&…

poj2154 Color ——Polya定理

题目&#xff1a;http://poj.org/problem?id2154 今天学了个高端的东西&#xff0c;Polya定理... 此题就是模板&#xff0c;然而还是写了好久好久... 具体看这个博客吧&#xff1a;https://blog.csdn.net/wsniyufang/article/details/6671122 代码如下&#xff1a; #include&l…

[转]sudoers设置

from http://www.cnblogs.com/zhuowei/archive/2009/04/13/1435190.htmlsudo与sudoerssudo 是linux下常用的允许普通用户使用超级用户权限的工具&#xff0c;允许系统管理员让普通用户执行一些或者全部的root命令&#xff0c;如halt&#xff0c;reboot&#xff0c;su等 等。这样…

哈尔滨阳光计算机学院是不是黄了,黑龙江这4所野鸡大学,常被误认为是名校,实则害人不浅...

在高考中拿到高分进入心仪的大学&#xff0c;几乎是所有高三党奋斗努力的目标。但并不是所有的考生都能得偿所愿&#xff0c;没有取得高分&#xff0c;想进入好大学&#xff0c;但是又不想复读再经历一次高三的磨砺。如果此时你收到了录取通知书或者电话&#xff0c;告知你被一…