• winform应用程序呈现infopath表单


    第一,vs中新建winform项目。

    第二,在winform项目中添加引用

         

    第三,添加一个用户控件

           

    代码
    #region Component Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
    this.labelInfoPathNotInstalled = new System.Windows.Forms.Label();
    this.labelNoDocumentAvailable = new System.Windows.Forms.Label();
    this.SuspendLayout();
    //
    // labelInfoPathNotInstalled
    //
    this.labelInfoPathNotInstalled.Anchor = System.Windows.Forms.AnchorStyles.None;
    this.labelInfoPathNotInstalled.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
    this.labelInfoPathNotInstalled.Location = new System.Drawing.Point(223, 175);
    this.labelInfoPathNotInstalled.Name = "labelInfoPathNotInstalled";
    this.labelInfoPathNotInstalled.Size = new System.Drawing.Size(192, 86);
    this.labelInfoPathNotInstalled.TabIndex = 0;
    this.labelInfoPathNotInstalled.Text = "Unfortunately InfoPath seems to be not installed on this computer.";
    this.labelInfoPathNotInstalled.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
    this.labelInfoPathNotInstalled.Visible = false;
    //
    // labelNoDocumentAvailable
    //
    this.labelNoDocumentAvailable.Anchor = System.Windows.Forms.AnchorStyles.None;
    this.labelNoDocumentAvailable.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
    this.labelNoDocumentAvailable.Location = new System.Drawing.Point(223, 175);
    this.labelNoDocumentAvailable.Name = "labelNoDocumentAvailable";
    this.labelNoDocumentAvailable.Size = new System.Drawing.Size(192, 86);
    this.labelNoDocumentAvailable.TabIndex = 2;
    this.labelNoDocumentAvailable.Text = "No document is available.";
    this.labelNoDocumentAvailable.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
    this.labelNoDocumentAvailable.Click += new System.EventHandler(this.labelNoDocumentAvailable_Click);
    //
    // InfoPathUserControl
    //
    this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.Controls.Add(this.labelNoDocumentAvailable);
    this.Controls.Add(this.labelInfoPathNotInstalled);
    this.Name = "InfoPathUserControl";
    this.Size = new System.Drawing.Size(638, 436);
    this.Load += new System.EventHandler(this.InfoPathUserControl_Load);
    this.ResumeLayout(false);

    }

    #endregion

           
    

    第四,为用户控件添加事件

            

    代码
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Drawing;
    using System.Data;
    using System.Text;
    using System.Windows.Forms;
    using Microsoft.Office.InfoPath;
    using System.IO;
    using System.Reflection;
    using System.Threading;
    using System.Xml.XPath;
    using System.Security.Permissions;
    using System.Globalization;
    using System.Runtime.InteropServices;

    namespace FJGISDraw
    {
    public enum UIStatesForm
    {
    NoDocumentAvailable,
    DocumentReadMode,
    DocumentEditMode
    };

    [EnvironmentPermissionAttribute(
    SecurityAction.InheritanceDemand)]
    public partial class InfoPathUserControl : UserControl
    {
    const string READONLY_VIEW_NAME = "readonly";

    InfoPathInitEventHandler infoPathInitEventHandler;

    private bool readOnly;
    internal bool ReadOnly
    {
    private set { readOnly = value; }
    get { return readOnly; }
    }

    public bool InfoPathInstalled { get; private set; }

    public bool IsInitialized { get; set; }

    private Microsoft.Office.InfoPath.FormControl formControl;

    public InfoPathUserControl()
    {
    InitializeComponent();
    }


    #region Initialize InfoPath

    public void InitInfoPathForm()
    {
    if (this.IsInitialized) return;

    // Write asynchron
    this.InitInfoPath();
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage(
    "Microsoft.Design",
    "CA1031",
    Justification
    ="False initialization does not depend on exception type")]
    void InitInfoPath()
    {
    // Init form component
    System.ComponentModel.ComponentResourceManager resources =
    new System.ComponentModel.ComponentResourceManager(
    typeof(InfoPathUserControl));

    try
    {
    InitInfoPathControlUI(resources);

    this.labelInfoPathNotInstalled.Visible = false;
    this.InfoPathInstalled = true;

    InitInfoPathInitEventhandler();
    }
    catch (Exception)
    {
    this.InfoPathInstalled = false;

    this.labelInfoPathNotInstalled.Visible = true;
    }
    finally
    {
    this.labelNoDocumentAvailable.Visible = false;

    this.IsInitialized = true;

    // update again after init (only this view is needed)
    this.RefreshView(
    UIStatesForm.NoDocumentAvailable);
    }
    }

    private void InitInfoPathControlUI(System.ComponentModel.ComponentResourceManager resources)
    {
    this.formControl =
    new Microsoft.Office.InfoPath.FormControl();
    ((System.ComponentModel.ISupportInitialize)
    (
    this.formControl)).BeginInit();

    this.formControl.Visible = false;
    this.formControl.Dock = DockStyle.Fill;
    this.formControl.Enabled = true;
    this.formControl.Location =
    new System.Drawing.Point(0, 0);
    this.formControl.Name = "formControl1";
    this.formControl.OcxState =
    ((System.Windows.Forms.AxHost.State)
    (resources.GetObject(
    "formControl1.OcxState")));
    this.formControl.Size =
    new System.Drawing.Size(
    this.Width,
    this.Height);
    this.formControl.TabIndex = 0;

    this.Controls.Add(this.formControl);
    ((System.ComponentModel.ISupportInitialize)
    (
    this.formControl)).EndInit();
    }

    private void InitInfoPathInitEventhandler()
    {
    this.infoPathInitEventHandler =
    InfoPathInitEventHandler.CreateInstance(
    this.formControl);

    this.formControl.SetInitEventHandler(
    this.infoPathInitEventHandler);
    }

    private void TestInitialization()
    {
    if (!this.IsInitialized) throw new InvalidOperationException("Object is not initialized");
    if (!this.InfoPathInstalled) throw new InvalidOperationException("InfoPath is not installed on this computer");
    }

    #endregion


    #region InfoPath loading / creating / handling

    [EnvironmentPermissionAttribute(
    SecurityAction.LinkDemand)]
    public void CreateFormTemplate(Uri formUrlName)
    {
    TestInitialization();

    this.CreateFormTemplate(
    formUrlName,
    null);
    }

    [EnvironmentPermissionAttribute(
    SecurityAction.LinkDemand)]
    public void CreateFormTemplate(
    Uri formUrlName,
    Stream dataStream)
    {
    TestInitialization();

    try
    {
    this.formControl.Close();

    // Open / create a form
    if (dataStream != null)
    formControl.NewFromFormTemplate(
    formUrlName.ToString(),
    dataStream,
    XmlFormOpenMode.Default);
    else
    formControl.NewFromFormTemplate(
    formUrlName.ToString());

    // Default view of InfoPath document could be the
    // readonly or another one
    this.InitReadOnlyFlag();

    RefreshView(UIStatesForm.DocumentReadMode);
    }
    catch (Exception)
    {
    RefreshView(UIStatesForm.NoDocumentAvailable);

    throw;
    }
    }

    [EnvironmentPermissionAttribute(
    SecurityAction.LinkDemand)]
    public void CloseFormTemplate()
    {
    formControl.Close();

    RefreshView(UIStatesForm.NoDocumentAvailable);
    }

    [EnvironmentPermissionAttribute(
    SecurityAction.LinkDemand,
    Unrestricted
    = true)]
    public void SetFieldValue(string fieldName, string fieldValue)
    {
    TestInitialization();

    var navigator
    =
    formControl.XmlForm.MainDataSource.CreateNavigator();

    string namespaceName;
    bool foundNamespace;
    FindInfoPathNamespace(
    navigator,
    out namespaceName,
    out foundNamespace);

    var nav2
    = navigator.Clone();
    var found
    = nav2.MoveToFollowing(
    fieldName,
    namespaceName);
    if (found)
    nav2.SetValue(fieldValue);
    }

    [EnvironmentPermissionAttribute(
    SecurityAction.LinkDemand)]
    public void SwitchView()
    {
    TestInitialization();

    try
    {
    ViewInfo readOnlyView
    = null;
    ViewInfo editView
    = null;
    foreach (ViewInfo view in this.formControl.XmlForm.ViewInfos)
    {
    if (string.Compare(view.Name.ToLower(
    CultureInfo.CurrentCulture),
    READONLY_VIEW_NAME,
    StringComparison.CurrentCulture)
    == 0)
    readOnlyView
    = view;
    else editView = view;
    }

    var new_readonly
    = !this.readOnly;

    if (new_readonly)
    this.formControl.XmlForm.ViewInfos.SwitchView(readOnlyView);
    else this.formControl.XmlForm.ViewInfos.SwitchView(editView);

    // Switching view was successful
    this.readOnly = new_readonly;
    }
    catch (COMException)
    {
    // switching view was not successfull, do nothing
    }
    }

    #endregion


    #region Validate and save InfoPath document

    [EnvironmentPermissionAttribute(
    SecurityAction.LinkDemand)]
    public int ValidateInfoPath()
    {
    TestInitialization();

    return this.formControl.XmlForm.Errors.Count;
    }

    public string FormData
    {
    [EnvironmentPermissionAttribute(
    SecurityAction.LinkDemand)]
    get
    {
    TestInitialization();

    XmlForm xf
    = formControl.XmlForm;
    if (xf != null) return xf.MainDataSource.
    CreateNavigator().OuterXml;
    else return string.Empty;
    }
    }

    #endregion


    #region Private help methods

    private static void FindInfoPathNamespace(
    System.Xml.XPath.XPathNavigator navigator2,
    out string namespaceName2,
    out bool foundNamespace2)
    {
    namespaceName2
    = string.Empty;
    foundNamespace2
    = false;
    if (navigator2.MoveToFirstChild())
    {
    namespaceName2
    = navigator2.LookupNamespace(@"xmlns:my");
    while (namespaceName2 == null || namespaceName2.Length <= 0)
    {
    if (!navigator2.MoveToNext())
    break;
    namespaceName2
    = navigator2.LookupNamespace(@"my");
    };
    }
    if (namespaceName2 != null && namespaceName2.Length > 0)
    foundNamespace2
    = true;
    }

    private void RefreshView(UIStatesForm currentUIStatesForms)
    {
    if (this.InfoPathInstalled)
    {
    switch (currentUIStatesForms)
    {
    case UIStatesForm.NoDocumentAvailable:
    this.Enabled = false;
    if (this.formControl != null)
    {
    this.formControl.Visible = false;
    }
    this.labelInfoPathNotInstalled.Visible = false;
    this.labelNoDocumentAvailable.Visible = true;
    break;
    case UIStatesForm.DocumentReadMode:
    case UIStatesForm.DocumentEditMode:
    this.Enabled = true;
    if (this.formControl != null)
    {
    this.formControl.Visible = true;
    }
    this.labelInfoPathNotInstalled.Visible = false;
    this.labelNoDocumentAvailable.Visible = false;
    break;
    }
    }
    else
    {
    this.labelInfoPathNotInstalled.Visible = true;
    }
    }

    internal void InitReadOnlyFlag()
    {
    if (this.IsInitialReadOnly == true)
    this.ReadOnly = true;
    else this.ReadOnly = false;
    }

    private bool IsInitialReadOnly
    {
    get
    {
    return
    (
    string.Compare(this.formControl.
    XmlForm.ViewInfos.Default.Name,
    READONLY_VIEW_NAME,
    true,
    CultureInfo.CurrentCulture)
    == 0);
    }
    }

    #endregion

    private void InfoPathUserControl_Load(object sender, EventArgs e)
    {

    }

    private void labelNoDocumentAvailable_Click(object sender, EventArgs e)
    {

    }
    }
    }
    
    

    第五,为用户控件添加注册事件

            

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Drawing;
    using System.Data;
    using System.Text;
    using System.Windows.Forms;
    using Microsoft.Office.InfoPath;
    using System.IO;
    using System.Reflection;
    using System.Threading;
    using System.Xml.XPath;
    using System.Security.Permissions;
    using System.Globalization;
    using System.Runtime.InteropServices;
    
    namespace FJGISDraw
    {
    public partial class InfoPathUserControl : UserControl
    {
        #region class InfoPathInitEventHandler 
    
        internal class InfoPathInitEventHandler : IInitEventHandler
        {
            private InfoPathInitEventHandler() { }
    
            FormControl formControl;
            bool internalStartupDeclared;
    
            private InfoPathInitEventHandler(
                FormControl formControl)
            {
                this.formControl = formControl;
            }
    
            internal static InfoPathInitEventHandler CreateInstance(
                FormControl formControl)
            {
                return new InfoPathInitEventHandler(
                            formControl);
            }
    
    
            #region IInitEventHandler Members
    
            public void InitEventHandler(
                object sender,
                XmlForm xmlForm,
                out Microsoft.Office.Interop.InfoPath.XdReadOnlyViewMode
                    viewsReadOnlyMode)
            {
                viewsReadOnlyMode =
                    Microsoft.Office.Interop.InfoPath.XdReadOnlyViewMode.xdDefault;
    
                if (!internalStartupDeclared)
                {
                    this.formControl.InternalStartup +=
                        new FormControl.EventHandler<EventArgs>(formControl_InternalStartup);
                    internalStartupDeclared = true;
                }
            }
    
            void formControl_InternalStartup(object sender, EventArgs e)
            {
                this.formControl.EventManager.FormEvents.ContextChanged +=
                    new ContextChangedEventHandler(FormEvents_ContextChanged);
                this.formControl.EventManager.FormEvents.ViewSwitched +=
                    new ViewSwitchedEventHandler(FormEvents_ViewSwitched);
            }
    
            #endregion
    
            void FormEvents_ViewSwitched(object sender, ViewSwitchedEventArgs e)
            {
            }
    
            void FormEvents_ContextChanged(
                object sender,
                ContextChangedEventArgs e)
            {
            }
        }
    
        #endregion
    }
    }
    
    
    

    第六,运行项目用户控件制作完成

           

    第七,新建winform页面 并将这个用户控件拖入窗体上,合适的调整大小

           

    第八,为窗体写入后台代码,加载infopath模板与xml数据文件(我的项目中模板在本地文件夹,xml数据从数据库读取)

            

    public FrmEquipForm()
            {
                InitializeComponent();
                this.infoPathUserControl1.InitInfoPathForm();
            }
            Stream sr = null;
            private void FrmEquipForm_Load(object sender, EventArgs e)
            {
                //得到数据流
               
            }
            public Stream FileToStream(string fileName)
            {
                // 打开文件 
                FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                // 读取文件的 byte[] 
                byte[] bytes = new byte[fileStream.Length];
                fileStream.Read(bytes, 0, bytes.Length);
                fileStream.Close();
                // 把 byte[] 转换成 Stream 
                Stream stream = new MemoryStream(bytes);
                return stream;
            }
            static private void RefreshSwitchViewName(
               InfoPathUserControl InfoPathUserCtrl,
               Button buttonSwitchView)
            {
                buttonSwitchView.Text =
                    "Switch view (Readonly is " +
                    InfoPathUserCtrl.ReadOnly +
                    ")";
            }
    
            static private void CreateDocument(
                InfoPathUserControl InfoPathUserCtrl,
                Stream info,
                Button buttonSetFieldValue,
                Button buttonSwitchView,
                string InfoPathTemplate)
            {
                InfoPathUserCtrl.CreateFormTemplate(
                    new Uri(
                        Path.Combine(
                            System.Environment.CurrentDirectory,
                            InfoPathTemplate)),info);
    
                buttonSetFieldValue.Enabled = true;
                buttonSwitchView.Enabled = true;
                RefreshSwitchViewName(
                    InfoPathUserCtrl,
                    buttonSwitchView);
            }
    
            static private void SetFieldValue(InfoPathUserControl InfoPathUserControl)
            {
                InfoPathUserControl.SetFieldValue(
                    "name", System.Environment.UserName);
            }
    
            static private void SwitchView(
                InfoPathUserControl InfoPathUserCtrl,
                Button buttonSwitchView)
            {
                InfoPathUserCtrl.SwitchView();
                RefreshSwitchViewName(
                    InfoPathUserCtrl,
                    buttonSwitchView);
            }
    
            #region Event handlers for 1st document instance + buttons
    
            private void buttonCreateDocument_Click(
                object sender, EventArgs e)
            {
                //sr = new FileStream(@"462.xml");
                sr = FileToStream(@"462.xml");
                CreateDocument(
                    this.infoPathUserControl1,sr,
                    this.buttonSetFieldValue,
                    this.buttonSwitchView,
                    @"diangan.xsn");
            }
    
            private void buttonSetFieldValue_Click(
                object sender, EventArgs e)
            {
                SetFieldValue(infoPathUserControl1);
            }
    
            private void buttonSwitchView_Click(
                object sender, EventArgs e)
            {
                SwitchView(
                    this.infoPathUserControl1,
                    this.buttonSwitchView);
            }
    
            #endregion
    
    
    

    第九,大功告成,运行项目看下效果

            

         

  • 相关阅读:
    Python汉字转换成拼音
    python之Tkinter控件学习
    python 函数式编程:高阶函数,map/reduce
    python的高级特性:切片,迭代,列表生成式,生成器,迭代器
    python tkinter Listbox用法
    python函数定义语法总结
    Cmder 快捷键
    录音水波动画
    图片截取部分显示
    移动web在ios和android下点击元素出现阴影问题
  • 原文地址:https://www.cnblogs.com/chenjq0717/p/1732682.html
Copyright © 2020-2023  润新知