DocToolKit使用方法

由DrawTool提供的DocToolKit包括如下內容:
watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
    DrawTools實現了一些特別的應用程序功能
 
  • DocManager 處理文件操做:打開,新建,保存,更新窗體標題,爲Windows Shell註冊文件類型。建立這個類引用了Chris Sells 的文章 Creating Document-Centric Applications in Windows Forms 
  • DragDropManager 在Windows Form應用程序中容許你經過拖拽的方式從瀏覽器(文件瀏覽器)中打開文件。

     

  • MruManager 管理大多數最近使用的文件列表。

     

  • PersistWindowState 容許你把最近一次的窗口狀態保存到註冊表 ,在窗體載入的時候從新得到。來源: Saving and Restoring the Location, Size and Windows State of a .NET Form By Joel Matthias.
這4個類是窗體程序通用的,我這裏進行了初步的使用小結,實際上很是簡單。
1、DockManager序列化和發序列化
DocManager提供了相似MFC中序列化和反序列號的操做
 
    /// <summary>
    /// Document manager. Makes file-related operations:
    /// open, new, save, updating of the form title, 
    /// registering of file type for Windows Shell.
    /// Built using the article:
    /// Creating Document-Centric Applications in Windows Forms
    /// by Chris Sells
    /// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnforms/html/winforms09182003.asp【已失效】
    /// </summary>
在具體的使用過程當中,是Csharp獨特的委託機制。
 
 
            // Subscribe to DocManager events.
            docManager.SaveEvent += docManager_SaveEvent;
            docManager.LoadEvent += docManager_LoadEvent;
 
就配置使用這塊來看,將docManager定義並初始化後,着重是直接操做兩個Event。
 private void docManager_SaveEvent(object sender, SerializationEventArgs e)
        {
            // DocManager asks to save document to supplied stream
            try
            {
                e.Formatter.Serialize(e.SerializationStream, drawArea.GraphicsList);
            }
            catch (ArgumentNullException ex)
            {
                HandleSaveException(ex, e);
            }
            catch (SerializationException ex)
            {
                HandleSaveException(ex, e);
            }
            catch (SecurityException ex)
            {
                HandleSaveException(ex, e);
            }
        }
 private void docManager_LoadEvent(object sender, SerializationEventArgs e)
        {
            // DocManager asks to load document from supplied stream
            try
            {
                drawArea.GraphicsList = (GraphicsList)e.Formatter.Deserialize(e.SerializationStream);
            }
            catch (ArgumentNullException ex)
            {
                HandleLoadException(ex, e);
            }
            catch (SerializationException ex)
            {
                HandleLoadException(ex, e);
            }
            catch (SecurityException ex)
            {
                HandleLoadException(ex, e);
            }
        }
 
能夠直接將控件進行序列化操做。它的代碼中提供了較爲詳細的操做說明
 
/*
Using:
1. Write class which implements program-specific tasks. This class keeps some data,
   knows to draw itself in the form window, and implements ISerializable interface.
   Example:
   
    [Serializable]
    public class MyTask : ISerializable
    {
        // class members
        private int myData;
        // ...
   
        public MyTask()
        {
           // ...
        }
       
        public void Draw(Graphics g, Rectangle r)
        {
            // ...
        }
       
        // other functions
        // ...
       
        // Serialization
        // This function is called when file is loaded
        protected GraphicsList(SerializationInfo info, StreamingContext context)
        {
            myData = info.GetInt32("myData");
            // ...
        }
        // Serialization
        // This function is called when file is saved
        public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("myData", myData);
            // ...
        }
    }
       
    Add member of this class to the form:
    
    private MyClass myClass;
2. Add the DocManager member to the owner form:
private DocManager docManager;
3. Add DocManager message handlers to the owner form:
        private void docManager_ClearEvent(object sender, EventArgs e)
        {
            // DocManager executed New command
            // Clear here myClass or create new empty instance:
            myClass = new MyClass();
            Refresh();
        }
        
        private void docManager_DocChangedEvent(object sender, EventArgs e)
        {
            // DocManager reports that document was changed (loaded from file)
            Refresh();
        }
        private void docManager_OpenEvent(object sender, OpenFileEventArgs e)
        {
            // DocManager reports about successful/unsuccessful Open File operation
            // For example:
            
            if ( e.Succeeded )
                // add e.FileName to MRU list
            else
                // remove e.FileName from MRU list
        }
        
        private void docManager_LoadEvent(object sender, SerializationEventArgs e)
        {
            // DocManager asks to load document from supplied stream
            try
            {
                myClass  = (MyClass)e.Formatter.Deserialize(e.SerializationStream);
            }
            catch ( catch possible exceptions here )
            { 
                  // report error
                  
                  e.Error = true;
            }
        }
        
        private void docManager_SaveEvent(object sender, SerializationEventArgs e)
        {
            // DocManager asks to save document to supplied stream
            try
            {
                e.Formatter.Serialize(e.SerializationStream, myClass);
            }
            catch ( catch possible exceptions here )
            { 
                  // report error
                  
                  e.Error = true;
            }
        }
        
4. Initialize docManager member in the form initialization code:
            DocManagerData data = new DocManagerData();
            data.FormOwner = this;
            data.UpdateTitle = true;
            data.FileDialogFilter = "MyProgram files (*.mpf)|*.mpf|All Files (*.*)|*.*";
            data.NewDocName = "Untitled.mpf";
            data.RegistryPath = "Software\\MyCompany\\MyProgram";
            docManager = new DocManager(data);
            docManager.SaveEvent += docManager_SaveEvent;
            docManager.LoadEvent += docManager_LoadEvent;
            docManager.OpenEvent += docManager_OpenEvent;
            docManager.DocChangedEvent += docManager_DocChangedEvent;
            docManager.ClearEvent += docManager_ClearEvent;
            docManager.NewDocument();
            // Optionally - register file type for Windows Shell
            bool result = docManager.RegisterFileType("mpf", "mpffile", "MyProgram File");            
5. Call docManager functions when necessary. For example:
        // File is dropped into the window;
        // Command line parameter is handled.
        public void OpenDocument(string file)
        {
            docManager.OpenDocument(file);
        }
        // User Selected File - Open command.
        private void CommandOpen()
        {
            docManager.OpenDocument("");
        }
        // User selected File - Save command
        private void CommandSave()
        {
            docManager.SaveDocument(DocManager.SaveType.Save);
        }
        // User selected File - Save As command
        private void CommandSaveAs()
        {
            docManager.SaveDocument(DocManager.SaveType.SaveAs);
        }
        // User selected File - New command
        private void CommandNew()
        {
            docManager.NewDocument();
        }
6. Optionally: test for unsaved data in the form Closing event:
        private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if ( ! docManager.CloseDocument() )
                e.Cancel = true;
        }
7. Optionally: handle command-line parameters in the main function:
        [STAThread]
        static void Main(string[] args) 
        {
            // Check command line
            if( args.Length > 1 ) 
            {
                MessageBox.Show("Incorrect number of arguments. Usage: MyProgram.exe [file]", "MyProgram");
                return;
            }
            // Load main form, taking command line into account
            MainForm form = new MainForm();
            if ( args.Length == 1 ) 
                form.OpenDocument(args[0]);     // OpenDocument calls docManager.OpenDocument
            Application.Run(form);
        }
*/
 
編寫一個界面,實現了另存和讀取。
watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
若是須要同時保存多種狀態的話,就可使用結構體。好比這個結構體:
 
        [Serializable]
        struct StreamStruct
        {
            public  string str;
            public  Bitmap bmp;
        }
 
同時將保存和讀取的代碼貼出來。
private void docManager_LoadEvent(object sender, SerializationEventArgs e)
        {
            try
            {
                StreamStruct streamStruct = new StreamStruct();
                streamStruct = (StreamStruct)e.Formatter.Deserialize(e.SerializationStream);
                pictureBox1.Image = streamStruct.bmp;
                textBox1.Text = streamStruct.str;
            }
            catch { }
                mruManager.Add(e.FileName);
        }
        private void docManager_SaveEvent(object sender, SerializationEventArgs e)
        {
            // DocManager asks to save document to supplied stream
            try
            {
                StreamStruct streamStruct = new StreamStruct();
                streamStruct.str = textBox1.Text;
                streamStruct.bmp = (Bitmap) pictureBox1.Image;
                List<List<Rectangle>> llr = new List<List<Rectangle>>();
                for(int index = 0;index<70;index++)
                {
                    List<Rectangle> innerList = new List<Rectangle>();
                    for (int innerIndex = 0; innerIndex < 4; innerIndex++)
                        innerList.Add(new Rectangle(0, 0, 0, 0));
                    llr.Add(innerList);
                }
                streamStruct.llr = llr;
                e.Formatter.Serialize(e.SerializationStream, streamStruct);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
 
2、DragDropManager 拖動
【首先我須要注意專業程序對待程序的專業態度,而後想辦法學習過來】
 /// <summary>
    /// DragDropManager class allows to open files dropped from 
    /// Windows Explorer in Windows Form application.
    /// 
    /// Using:
    /// 1) Write function which opens file selected from MRU:
    ///
    /// private void dragDropManager_FileDroppedEvent(object sender, FileDroppedEventArgs e)
    /// {
    ///    // open file(s) from e.FileArray:
    ///    // e.FileArray.GetValue(0).ToString() ...
    /// }
    ///     
    /// 2) Add member of this class to the parent form:
    ///  
    /// private DragDropManager dragDropManager;
    /// 
    /// 3) Create class instance in parent form initialization code:
    ///  
    /// dragDropManager = new DragDropManager(this);
    /// dragDropManager.FileDroppedEvent += dragDropManager_FileDroppedEvent; 
    /// 
    /// </summary>
 
 
它的使用配置方法相對簡單,聲明後設置爲本程序
dragDropManager = new DragDropManager(this);
最後進行綁定
            // DragDropManager
            dragDropManager = new DragDropManager(this);
            dragDropManager.FileDroppedEvent += delegate(object sender, FileDroppedEventArgs e)
            {
                OpenDocument(e.FileArray.GetValue(0).ToString());
            };
 
watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
 
3、MruManager 最近使用文件
NOTE: This class works with new Visual Studio 2005 MenuStrip class.
If owner form has old-style MainMenu, use previous MruManager version.
Using:
1) Add menu item Recent Files (or any name you want) to main application menu.
   This item is used by MruManager as popup menu for MRU list.
2) Write function which opens file selected from MRU:
     private void mruManager_MruOpenEvent(object sender, MruFileOpenEventArgs e)
     {
         // open file e.FileName
     }
3) Add MruManager member to the form class and initialize it:
     private MruManager mruManager;
   Initialize it in the form initialization code:
   
         mruManager = new MruManager();
         mruManager.Initialize(
             this,                              // owner form
             mnuFileMRU,                        // Recent Files menu item (ToolStripMenuItem class)
             mruItemParent,                     // Recent Files menu item parent (ToolStripMenuItem class)
             "Software\\MyCompany\\MyProgram"); // Registry path to keep MRU list
        mruManager.MruOpenEvent += this.mruManager_MruOpenEvent;
        // Optional. Call these functions to change default values:
        mruManager.CurrentDir = ".....";           // default is current directory
        mruManager.MaxMruLength = ...;             // default is 10
        mruMamager.MaxDisplayNameLength = ...;     // default is 40
     NOTES:
     - If Registry path is, for example, "Software\MyCompany\MyProgram",
       MRU list is kept in
       HKEY_CURRENT_USER\Software\MyCompany\MyProgram\MRU Registry entry.
     - CurrentDir is used to show file names in the menu. If file is in
       this directory, only file name is shown.
4) Call MruManager Add and Remove functions when necessary:
       mruManager.Add(fileName);          // when file is successfully opened
       mruManager.Remove(fileName);       // when Open File operation failed
*******************************************************************************/
// Implementation details:
//
// MruManager loads MRU list from Registry in Initialize function.
// List is saved in Registry when owner form is closed.
//
// MRU list in the menu is updated when parent menu is poped-up.
//
// Owner form OnMRUFileOpen function is called when user selects file
// from MRU list.
 
watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=
 
 
只須要初始化的時候,將其相關定義正確就能夠。

            ////MruManager////
            mruManager = new MruManager();
            mruManager.Initialize(
                this,                              // owner form
                mRUToolStripMenuItem,             // 具體要顯示的menu
                fileToolStripMenuItem,            // 父menu
                registryPath);                     // Registry path to keep MRU list
            mruManager.MruOpenEvent += delegate (object sender, MruFileOpenEventArgs e)
            {
                // OpenDocument(e.FileName);
                MessageBox.Show(e.FileName);
            };
 
這裏不少內容最終都歸併到了OpenDocment中去,所以首先將其抽象出來,也是很是重要的。
 
4、PersisWindowState 保持窗體狀態
 
PersistWindowState的做用就是保持窗體爲上一次關閉時候的狀態。對於現有的窗體來講,確實缺少這樣一個狀態。
 /// <summary>
    /// Class allows to keep last window state in Registry
    /// and restore it when form is loaded.
    /// 
    /// Source: Saving and Restoring the Location, Size and 
    ///         Windows State of a .NET Form
    ///         By Joel Matthias 
    ///         
    ///  Downloaded from http://www.codeproject.com
    ///  
    ///  Using:
    ///  1. Add class member to the owner form:
    ///  
    ///  private PersistWindowState persistState;
    ///  
    ///  2. Create it in the form constructor:
    ///  
    ///  persistState = new PersistWindowState("Software\\MyCompany\\MyProgram", this);
    ///  
    /// </summary>
 
然後定義並顯示就能夠。
   const string registryPath = "Software\\GreenOpen\\WindowsFormDocManager";
   ////registryPath////
            persistState = new PersistWindowState(registryPath, this);
 
 
 




附件列表

相關文章
相關標籤/搜索