コード例 #1
0
        public void FileSave()
        {
            if (!this.IsDirty)
            {
                return;
            }

            if (this.Filename.Length == 0)
            {
                System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
                System.Windows.Forms.DialogResult   result         = saveFileDialog.ShowDialog();
                if (result != System.Windows.Forms.DialogResult.OK)
                {
                    saveFileDialog.Dispose();
                    return;
                }
                this.Filename = saveFileDialog.FileName;
                saveFileDialog.Dispose();

                if (this.Filename.Length == 0)
                {
                    return;
                }
            }

            System.IO.FileStream   stream = new System.IO.FileStream(this.Filename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            System.IO.StreamWriter writer = new System.IO.StreamWriter(stream, System.Text.Encoding.Default);
            writer.Write(this.EditorText);
            writer.Flush();
            stream.Close();
            this.IsDirty = false;
        }
コード例 #2
0
        private void btn_guardar_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1;
            saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Title = "Guardar Archivo de Texto";
            saveFileDialog1.Filter = "Archivo de Texto (.txt) |*.txt";

            saveFileDialog1.DefaultExt = "txt";
            saveFileDialog1.AddExtension = true;
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.InitialDirectory = @"H:\LO DEL ESCRITORIO";

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string ruta = saveFileDialog1.FileName;

                StreamWriter fichero = new StreamWriter(ruta);
                fichero.Write(txt_error.Text);
                fichero.Close();

            }
            else
            {

            }
            saveFileDialog1.Dispose();
            saveFileDialog1 = null;
        }
コード例 #3
0
        private void buttonSalvar_Click(object sender, EventArgs e)
        {
            //Salva os arquivos gerados para relatorio
            SaveFileDialog SFD = new SaveFileDialog();

            //Extensões possíveis de salvar o relatório
            SFD.Filter = "Texto|*.txt|Word|*.doc|planilha|*.ods|html|*.html|PDF|*.pdf|Todos os Arquivos|*.*";
            SFD.FilterIndex = 2;
            SFD.FileName = "Historico1";
            if (SFD.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = new FileStream(SFD.FileName, FileMode.Create);
                StreamWriter writer = new StreamWriter(fs);
                writer.WriteLine("\tHistorico");
                writer.WriteLine();
                int i = 0;
                while (i < listViewHistorico.Items.Count)
                {
                    //salva os dados que estão no listview
                    writer.Write(listViewHistorico.Items[i].Text + " - ");
                    writer.Write(listViewHistorico.Items[i].SubItems[1].Text + " - ");
                    writer.Write(listViewHistorico.Items[i].SubItems[2].Text + " - ");
                    writer.Write(listViewHistorico.Items[i].SubItems[3].Text + " - ");
                    writer.Write(listViewHistorico.Items[i].SubItems[4].Text);
                    writer.WriteLine();
                    writer.WriteLine();
                    i++;
                }
                writer.Close();
                SFD.Dispose();
            }
        }
コード例 #4
0
ファイル: Form1.cs プロジェクト: RobFisher/SchoolRegister
        private void SaveButton_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog
            {
                AddExtension = true,
                DefaultExt   = "rsr"
            };

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                using (BinaryWriter bw = new BinaryWriter(File.Open(sfd.FileName, FileMode.Create)))
                {
                    bw.Write(dataGridView1.Columns.Count);
                    bw.Write(dataGridView1.Rows.Count);
                    foreach (DataGridViewRow dgvR in dataGridView1.Rows)
                    {
                        for (int j = 0; j < dataGridView1.Columns.Count; ++j)
                        {
                            object val = dgvR.Cells[j].Value;
                            if (val == null)
                            {
                                bw.Write(false);
                                bw.Write(false);
                            }
                            else
                            {
                                bw.Write(true);
                                bw.Write(val.ToString());
                            }
                        }
                    }
                }
            }
            sfd.Dispose();
        }
コード例 #5
0
        public void Execute(IMenuCommand command)
        {
            var dslDiagram = DiagramContext.CurrentDiagram.GetObject<Diagram>();

            if (dslDiagram == null)
                return;

            var dialog = new SaveFileDialog
                             {
                                 AddExtension = true,
                                 DefaultExt = "image.bmp",
                                 Filter = "Bitmap ( *.bmp )|*.bmp|JPEG File ( *.jpg )|*.jpg|Enhanced Metafile (*.emf )|*.emf|Portable Network Graphic ( *.png )|*.png",
                                 FilterIndex = 1,
                                 Title = "Save Diagram to Image"
                             };

            if (dialog.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(dialog.FileName))
            {
                var bitmap = dslDiagram.CreateBitmap(dslDiagram.NestedChildShapes, Diagram.CreateBitmapPreference.FavorClarityOverSmallSize);
                bitmap.Save(dialog.FileName, GetImageType(dialog.FilterIndex));
                bitmap.Dispose();
            }

            dialog.Dispose();
        }
コード例 #6
0
ファイル: MainForm.cs プロジェクト: geger009/Raiderz_Public
        private void mnuExportLootReport_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.SaveFileDialog DialogSave = new System.Windows.Forms.SaveFileDialog();

            DialogSave.DefaultExt = "csv";

            DialogSave.Filter = "CSV file (*.csv)|*.csv|All files (*.*)|*.*";

            DialogSave.AddExtension = true;

            DialogSave.RestoreDirectory = true;

            DialogSave.Title = "어디에 저장하시겠습니까?";

            //            DialogSave.InitialDirectory = @"C:/";

            if (DialogSave.ShowDialog() == DialogResult.OK)
            {
                SoulHunt.LootReportExporter lootReportExporter = new SoulHunt.LootReportExporter();
                lootReportExporter.Export(DialogSave.FileName, xmlCore);
                lootReportExporter = null;
            }

            DialogSave.Dispose();
            DialogSave = null;
        }
コード例 #7
0
		public override void Run()
		{
			ResourceEditorControl editor = ((ResourceEditWrapper)SD.Workbench.ActiveViewContent).ResourceEditor;
			ResourceList list = editor.ResourceList;
			
			if(list.SelectedItems.Count != 1) {
				return;
			}
			
			string key = list.SelectedItems[0].Text;
			if(! list.Resources.ContainsKey(key)) {
				return;
			}
			
			ResourceItem item = list.Resources[key];
			SaveFileDialog sdialog 	= new SaveFileDialog();
			sdialog.AddExtension = true;
			sdialog.FileName = key;
			
			if (item.ResourceValue is Bitmap) {
				sdialog.Filter 		= StringParser.Parse("${res:SharpDevelop.FileFilter.ImageFiles} (*.png)|*.png");
				sdialog.DefaultExt 	= ".png";
			} else if (item.ResourceValue is Icon) {
				sdialog.Filter 		= StringParser.Parse("${res:SharpDevelop.FileFilter.Icons}|*.ico");
				sdialog.DefaultExt 	= ".ico";
			} else if (item.ResourceValue is Cursor) {
				sdialog.Filter 		= StringParser.Parse("${res:SharpDevelop.FileFilter.CursorFiles} (*.cur)|*.cur");
				sdialog.DefaultExt 	= ".cur";
			} else if (item.ResourceValue is byte[]){
				sdialog.Filter      = StringParser.Parse("${res:SharpDevelop.FileFilter.BinaryFiles} (*.*)|*.*");
				sdialog.DefaultExt  = ".bin";
			} else {
				return;
			}
			
			DialogResult dr = sdialog.ShowDialog(SD.WinForms.MainWin32Window);
			sdialog.Dispose();
			if (dr != DialogResult.OK) {
				return;
			}
			
			try {
				if (item.ResourceValue is Icon) {
					FileStream fstr = new FileStream(sdialog.FileName, FileMode.Create);
					((Icon)item.ResourceValue).Save(fstr);
					fstr.Close();
				} else if(item.ResourceValue is Image) {
					Image img = (Image)item.ResourceValue;
					img.Save(sdialog.FileName);
				} else {
					FileStream fstr = new FileStream(sdialog.FileName, FileMode.Create);
					BinaryWriter wr = new BinaryWriter(fstr);
					wr.Write((byte[])item.ResourceValue);
					fstr.Close();
				}
			} catch(Exception ex) {
				MessageBox.Show(ex.Message, "Can't save resource to " + sdialog.FileName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
			}
		}
コード例 #8
0
        public void FileSaveAs()
        {
            System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
            System.Windows.Forms.DialogResult   result         = saveFileDialog.ShowDialog();
            if (result != System.Windows.Forms.DialogResult.OK)
            {
                saveFileDialog.Dispose();
                return;
            }
            this.Filename = saveFileDialog.FileName;
            saveFileDialog.Dispose();

            if (this.Filename.Length == 0)
            {
                return;
            }

            this.FileSave();
        }
コード例 #9
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (concreteOpenFileDialog != null)
         {
             concreteOpenFileDialog.Dispose();
             concreteOpenFileDialog = null;
         }
     }
 }
コード例 #10
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (_concreteSaveFileDialog != null)
         {
             _concreteSaveFileDialog.Dispose();
             _concreteSaveFileDialog = null;
         }
     }
 }
コード例 #11
0
        private void SaveMyRoles()
        {
            System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();

            saveFileDialog1.Filter           = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            saveFileDialog1.FilterIndex      = 1;
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.Title            = "Укажите путь и имя файла для сохранения";
            saveFileDialog1.FileName         = _OLAP.db.Name + "RoleMembers.txt";

            if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(saveFileDialog1.FileName, false, Encoding.Default, 10))
                    {
                        string filerowheader = string.Format("\"{0}\",\"{1}\",\"{2}\"", "Database", "Role", "Member");
                        file.WriteLine(filerowheader);

                        string Databasename = _OLAP.db.Name;

                        foreach (mycOLAProle rol in _OLAP.db.listRole)
                        {
                            string Rolename = rol.Name;
                            foreach (mycOLAPuser usr in rol.listUser)
                            {
                                string RoleMember = usr.Name;
                                string filerow    = string.Format("\"{0}\",\"{1}\",\"{2}\"", Databasename, Rolename, RoleMember);
                                file.WriteLine(filerow);
                            }
                        }
                    }
                    MessageBox.Show("Выгрузка успешно завершена", "Инфо");
                }
                catch (Exception ex)
                {
                    if (ex is Microsoft.AnalysisServices.AmoException)
                    {
                        MessageBox.Show("Ошибка чтения данных сервера SSAS");
                        return;
                    }

                    if (ex is System.IO.IOException)
                    {
                        MessageBox.Show("Ошибка открытия или записи в файл. Проверьте не открыт ли он в другой программе.");
                        return;
                    }

                    MessageBox.Show("Неизвестная и самая страшная ошибка, потому что неизвестная");
                }
            }
            saveFileDialog1.Dispose();
        }
コード例 #12
0
 public void saveBitmapAs(MyBitmap myBitmap)
 {
     if (myBitmap != null)
     {
         SaveFileDialog saveDialog = new SaveFileDialog();
         saveDialog.FileName = "moj_plik";
         saveDialog.Filter = "Plik graficzny (*.bmp)|*.BMP; *.bmp";
         saveDialog.ShowDialog();
         myBitmap.CurrentBitmap.Save(saveDialog.FileName);
         saveDialog.Dispose();
     }
 }
コード例 #13
0
 private void btnBrowse_Click(object sender, EventArgs e)
 {
     SaveFileDialog sfd = new SaveFileDialog();
     sfd.CheckFileExists = false;
     sfd.FileName = txtFileLocation.Text;
     sfd.Filter = "txt files (*.txt)|*.txt";
     if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         txtFileLocation.Text = sfd.FileName;
     }
     sfd.Dispose();
 }
 private void btnCSV_Click(object sender, EventArgs e)
 {
     SaveFileDialog sFd = new SaveFileDialog();
     sFd.DefaultExt = ".csv";
     sFd.Filter = "Text|*.csv";
     sFd.Title = "Save CSV to";
     sFd.AddExtension = true;
     if (sFd.ShowDialog(this) == DialogResult.OK)
     {
         txtCSV.Text = sFd.FileName;
     }
     sFd.Dispose();
 }
コード例 #15
0
 private void button1_Click(object sender, EventArgs e)
 {
     SaveFileDialog saveFileDialog = new SaveFileDialog();
     saveFileDialog.CheckPathExists = true;
     saveFileDialog.OverwritePrompt = true;
     saveFileDialog.RestoreDirectory = true;
     saveFileDialog.Filter = "Shapefile(*.shp)|*.shp";
     saveFileDialog.Title = "输出图层位置";
     saveFileDialog.ShowDialog();
     saveFileDialog.Dispose();
     textBoxLocation.Text = saveFileDialog.FileName;
     strFullPath = saveFileDialog.FileName;
 }
コード例 #16
0
ファイル: FormTools.cs プロジェクト: khadoran/reanimator
        /// <summary>
        /// Creates a Save File Dialog box with default name and filters applied. Automatically adds correct file extension to returned path.
        /// </summary>
        /// <param name="fileExtension">The file extension to filter for and apply.</param>
        /// <param name="typeName">The full name description of the file type.</param>
        /// <param name="defaultFileName">Default save name for the file.</param>
        /// <param name="initialDirectory">The initial directory to open to.</param>
        /// <returns>The full String path of the file save location, with file extension, or null on Cancel.</returns>
        public static String SaveFileDialogBox(String fileExtension, String typeName, String defaultFileName, String initialDirectory)
        {
            // This little function is here because for some reason AddExtension = false doesn't seem to do shit.
            // So basically I just check it manually.

            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                AddExtension = false,
                DefaultExt = fileExtension,
                FileName = defaultFileName,
                Filter = String.Format("{1} File(s) (*.{0})|*.{0}", fileExtension, typeName),
                InitialDirectory = initialDirectory
            };

            if (saveFileDialog.ShowDialog() != DialogResult.OK)
            {
                saveFileDialog.Dispose();
                return null;
            }
            String filePath = saveFileDialog.FileName;
            saveFileDialog.Dispose();

            // since AddExtension = false doesn't seem to do shit
            string replaceExtension = "." + fileExtension;
            while (filePath.Contains(replaceExtension))
            {
                filePath = filePath.Replace(replaceExtension, "");
            }
            filePath += replaceExtension;

            if (!filePath.Contains(fileExtension))
            {
                filePath += fileExtension;
            }

            return filePath;
        }
コード例 #17
0
ファイル: Form1.cs プロジェクト: h82258652/MyImageMerge
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            SaveFileDialog sfd = new SaveFileDialog();

            ofd.Multiselect = true;
            var oResult= ofd.ShowDialog();
            if (oResult==DialogResult.OK)
            {
                var files = ofd.FileNames;
                var temp1 = files.ToList();
                temp1.Sort();
                files = temp1.ToArray();

                Bitmap[] bitmaps = new Bitmap[files.Length];

                for (int i = 0; i < files.Length; i++)
                {
                    bitmaps[i] = new Bitmap(files[i]);
                }

                Bitmap output = new Bitmap(bitmaps[0].Width, bitmaps.Select(temp=>temp.Height).Sum());

                int yy = 0;

                for (int i = 0; i < bitmaps.Length; i++)
                {
                    for (int y = 0; y < bitmaps[i].Height; y++)
                    {
                        for (int x = 0; x < bitmaps[i].Width; x++)
                        {
                            var c = bitmaps[i].GetPixel(x, y);

                            output.SetPixel(x,yy, c);
                        }

                        yy++;
                    }
                }

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    output.Save(sfd.FileName, ImageFormat.Jpeg);
                }
            }

            sfd.Dispose();
            ofd.Dispose();
        }
コード例 #18
0
 public void Export(object sender, EventArgs e)
 {
     String expfilter = StringValue.ExportFormats;
     SaveFileDialog dlgExport = new SaveFileDialog();
     dlgExport.Filter = expfilter;
     dlgExport.CheckFileExists = false;
     dlgExport.CheckPathExists = true;
     dlgExport.Title = "Export As...";
     if (dlgExport.ShowDialog() == DialogResult.OK)
     {
         ExportObject((EnumValues.FilterType)dlgExport.FilterIndex, dlgExport.FileName);
     }
     dlgExport.Dispose();
     dlgExport = null;
 }
コード例 #19
0
 public void Export(object sender, EventArgs e)
 {
     String expfilter = "Extensible Markup Language (*.xml)|*.xml|Comma Separate Values (*.csv)|*.csv|Tabbed Delimited (*.txt)|*.txt";
     SaveFileDialog dlgExport = new SaveFileDialog();
     dlgExport.Filter = expfilter;
     dlgExport.CheckFileExists = false;
     dlgExport.CheckPathExists = true;
     dlgExport.Title = "Export As...";
     if (dlgExport.ShowDialog() == DialogResult.OK)
     {
         ExportObject((FilterType)dlgExport.FilterIndex, dlgExport.FileName);
     }
     dlgExport.Dispose();
     dlgExport = null;
 }
コード例 #20
0
        private void OnFileSave(object sender, EventArgs e)
        {
            System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog();

            dlg.Filter = "All files (*.*)|*.*";

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                PsImage.IImageData ImageData = this._ProcImage.IsCreated ? this._ProcImage : this._ImageData;

                PsImage.ImageWriter.WriteImage(dlg.FileName, ImageData);
            }

            dlg.Dispose();
        }
コード例 #21
0
 public override void Run()
 {
     TempletPrintNode owner = (TempletPrintNode) this.Owner;
     if (owner != null)
     {
         TempletPrint domainObject = owner.DomainObject;
         SaveFileDialog dialog = new SaveFileDialog();
         dialog.FileName = domainObject.TempletFile;
         if (dialog.ShowDialog() == DialogResult.OK)
         {
             File.WriteAllBytes(dialog.FileName, domainObject.Data);
         }
         dialog.Dispose();
     }
 }
コード例 #22
0
ファイル: Utils.cs プロジェクト: iamHXQ/Oy
 /// <summary>
 /// 获取文件保存路径
 /// </summary>
 /// <returns></returns>
 public static string GetFilePath(string Extention)
 {
     Forms.SaveFileDialog saveFileDialog = new Forms.SaveFileDialog
     {
         InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
         FileName         = "坐标表-" + Utils.NamedObjectDictionary.ReadFromNOD(lib.AppConfig.ProjectInfoName[1]),//默认文件名
         Filter           = Extention + "|*." + Extention,
         //Filter = "所有文件(*.*)|*.*|Excel 2007 工作簿(*.xlsx)|*.xlsx|Word 2007 文档(*.docx)|*.docx",
         RestoreDirectory = false,
         OverwritePrompt  = false,
     };
     Forms.DialogResult dialogResult = saveFileDialog.ShowDialog();
     saveFileDialog.Dispose();
     if (dialogResult.Equals(Forms.DialogResult.OK))
     {
         return(saveFileDialog.FileName);
     }
     return(null);
 }
コード例 #23
0
 public static bool ShowSaveDialog(out string path)
 {
     path = null;
     var result = false;
     var saver = new SaveFileDialog
     {
         AddExtension = true,
         AutoUpgradeEnabled = true,
         DefaultExt = "pcdb",
         Filter = fileNameFilter
     };
     if (saver.ShowDialog() == DialogResult.OK)
     {
         path = saver.FileName;
         result = true;
     }
     saver.Dispose();
     return result;
 }
コード例 #24
0
ファイル: frmAppraise.cs プロジェクト: hy1314200/HyDM
        private void btnExport_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.RestoreDirectory = true;
            Application.DoEvents();
            try
            {
                string strFilter = "Excel�ļ�(*.xls)|*.xls";
                if (xtraTabControl1.SelectedTabPageIndex == 0)
                {
                    ExportXls();
                }
                else
                {
                    strFilter = "ͼƬ�ļ�(*.jpeg)|*.jpeg";
                    saveFileDialog1.Filter = strFilter;
                    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        this.Cursor = Cursors.WaitCursor;
                        try
                        {
                            chartControl1.ExportToImage(saveFileDialog1.FileName, ImageFormat.Jpeg);
                            XtraMessageBox.Show("����ͼƬ�ɹ�!", "��ʾ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                        catch (Exception ex)
                        {
                            XtraMessageBox.Show("����ͼƬʧ��!", "����", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        saveFileDialog1.FileName = "";
                        saveFileDialog1.Dispose();
                    }
                }
            }
            catch
            {

            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
コード例 #25
0
ファイル: Form1.cs プロジェクト: BrandonLaRue/FirstPrograms
        private void button1_Click(object sender, EventArgs e)
        {
            string path = "";
            string text = "";
            string[] textArray;

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Text File|*.txt";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                path = sfd.FileName;
                sfd.Dispose();
            }
            StreamWriter sw = new StreamWriter(File.Create(path));
            sw.WriteLine(textBox1.Text + ":" + textBox4.Text + ":" + textBox2.Text + ":" + textBox3.Text + ":");
            sw.Dispose();

            StreamReader sr = new StreamReader(File.OpenRead(path));
            text = sr.ReadLine();
            textArray = text.Split(':');
        }
コード例 #26
0
ファイル: DockSampleClosing.cs プロジェクト: lab1021/client
 private void btSave_Click(object sender, EventArgs e)
 {
     SaveFileDialog saveDialog = new SaveFileDialog();
     saveDialog.DefaultExt = "txt";
     saveDialog.AddExtension = true;
     saveDialog.FileName = articleID;
     saveDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
     saveDialog.OverwritePrompt = true;
     saveDialog.Title = "保存到本地";
     saveDialog.ValidateNames = true;
     if (saveDialog.ShowDialog() == DialogResult.OK)
     {
         StreamWriter writer = new StreamWriter(saveDialog.FileName);
         writer.WriteLine(srcRtbText );
         writer.WriteLine(dstRtbText );
         writer.Close();
         MessageBox.Show("保存成功!");
         writer.Close();
         saveDialog.Dispose();
         this.Close();
     }
 }
コード例 #27
0
		private void bGetFilename_Click(object sender, System.EventArgs e)
		{
			SaveFileDialog sfd = new SaveFileDialog();
			sfd.Filter = Strings.DialogDataSourceRef_bGetFilename_Click_DSRFilter;
			sfd.FilterIndex = 1;
			if (tbFilename.Text.Length > 0)
				sfd.FileName = tbFilename.Text;
			else
				sfd.FileName = "*.dsr";

			sfd.Title = Strings.DialogDataSourceRef_bGetFilename_Click_DSRTitle;
			sfd.OverwritePrompt = true;
			sfd.DefaultExt = "dsr";
			sfd.AddExtension = true;
            try
            {
                if (sfd.ShowDialog() == DialogResult.OK)
                    tbFilename.Text = sfd.FileName;
            }
            finally
            {
                sfd.Dispose();
            }
		}
コード例 #28
0
        public bool FileSaveAs()
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "RDL files (*.rdl)|*.rdl|All files (*.*)|*.*";
            sfd.FilterIndex = 1;

            Uri file = SourceFile;

            sfd.FileName = file == null ? "*.rdl" : file.LocalPath;
            try
            {
                if (sfd.ShowDialog(this) != DialogResult.OK)
                    return false;

                // User wants to save!
                string rdl = GetRdlText();
                if (FileSave(new Uri(sfd.FileName), rdl))
                {	// Save was successful
                    Text = sfd.FileName;
                    _SourceFile = new Uri(sfd.FileName);
                    return true;
                }
            }
            finally
            {
                sfd.Dispose();
            }
            return false;
        }
コード例 #29
0
ファイル: TextEditor.cs プロジェクト: NALSS/Telegraph
 /// <summary>
 /// Saves the file to disk, asking for location if the file is unsaved
 /// </summary>
 public void SaveFile()
 {
     if (currentFile == null) {
         SaveFileDialog dlg = new SaveFileDialog ();
         if (dlg.ShowDialog (this) != DialogResult.OK)
             return;
         currentFile = dlg.FileName;
         dlg.Dispose ();
     }
     SaveFile (currentFile);
 }
コード例 #30
0
ファイル: frmMain.cs プロジェクト: andry-dev/TSGE
        /// <summary>
        /// Saves the players current safe items into an xml file.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveSafeItems_Click(object sender, EventArgs e)
        {
            // Ask where to save to..
            var sfd = new SaveFileDialog
                {
                    AddExtension = true,
                    CheckPathExists = true,
                    DefaultExt = "xml",
                    Filter = "TSGE Safe Files (*.xml)|*.xml|All files (*.*)|*.*",
                    InitialDirectory = Application.StartupPath,
                    ValidateNames = true,
                };

            if (sfd.ShowDialog() != DialogResult.OK)
            {
                MessageBox.Show("Failed to save safe!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Create the new xml document..
            var xml = new XDocument(new XElement("BankSafe"));
            if (xml.Root == null)
            {
                sfd.Dispose();
                MessageBox.Show("Failed to save safe!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Loop each item in the players safe..
            foreach (var i in this.Player.Bank2)
            {
                // Add each item to the xml document..
                xml.Root.Add(new XElement("item", new object[]
                    {
                        new XAttribute("id", i.NetID),
                        new XAttribute("count", i.Count),
                        new XAttribute("prefix", i.Prefix)
                    }));
            }

            // Attempt to save the document..
            xml.Save(sfd.FileName);
            sfd.Dispose();
        }
コード例 #31
0
ファイル: frmMain.cs プロジェクト: andry-dev/TSGE
        /// <summary>
        /// Saves the current players gear to an xml file.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveEquipmentSet_Click(object sender, EventArgs e)
        {
            // Ask where to save to..
            var sfd = new SaveFileDialog
                {
                    AddExtension = true,
                    CheckPathExists = true,
                    DefaultExt = "xml",
                    Filter = "TSGE Equipment Files (*.xml)|*.xml|All files (*.*)|*.*",
                    InitialDirectory = Application.StartupPath,
                    ValidateNames = true,
                };

            if (sfd.ShowDialog() != DialogResult.OK)
            {
                MessageBox.Show("Failed to save equipment!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Create the new xml document..
            var xml = new XDocument(new XElement("Equipment"));
            if (xml.Root == null)
            {
                sfd.Dispose();
                MessageBox.Show("Failed to save equipment!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Loop each armor piece..
            foreach (var i in this.Player.Armor)
            {
                // Add each item to the xml document..
                xml.Root.Add(new XElement("armor", new object[]
                    {
                        new XAttribute("id", i.NetID),
                        new XAttribute("prefix", i.Prefix)
                    }));
            }

            // Loop each accessory piece..
            foreach (var i in this.Player.Accessories)
            {
                // Add each item to the xml document..
                xml.Root.Add(new XElement("accessory", new object[]
                    {
                        new XAttribute("id", i.NetID),
                        new XAttribute("prefix", i.Prefix)
                    }));
            }

            // Loop each vanity piece..
            foreach (var i in this.Player.Vanity)
            {
                // Add each item to the xml document..
                xml.Root.Add(new XElement("vanity", new object[]
                    {
                        new XAttribute("id", i.NetID),
                        new XAttribute("prefix", i.Prefix)
                    }));
            }

            // Loop each social accessory piece..
            foreach (var i in this.Player.SocialAccessories)
            {
                // Add each item to the xml document..
                xml.Root.Add(new XElement("socialaccessory", new object[]
                    {
                        new XAttribute("id", i.NetID),
                        new XAttribute("prefix", i.Prefix)
                    }));
            }

            // Loop each dye piece..
            foreach (var i in this.Player.Dye)
            {
                // Add each item to the xml document..
                xml.Root.Add(new XElement("dye", new object[]
                    {
                        new XAttribute("id", i.NetID),
                        new XAttribute("prefix", i.Prefix)
                    }));
            }

            // Attempt to save the document..
            xml.Save(sfd.FileName);
            sfd.Dispose();
        }
コード例 #32
0
ファイル: frmMain.cs プロジェクト: andry-dev/TSGE
        /// <summary>
        /// Exports the current players hair type and colors.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveColorHair_Click(object sender, EventArgs e)
        {
            // Ask where to save to..
            var sfd = new SaveFileDialog
                {
                    AddExtension = true,
                    CheckPathExists = true,
                    DefaultExt = "xml",
                    Filter = "TSGE Hair and Color Files (*.xml)|*.xml|All files (*.*)|*.*",
                    InitialDirectory = Application.StartupPath,
                    ValidateNames = true,
                };

            var ret = sfd.ShowDialog();
            if (ret != DialogResult.OK)
            {
                if (ret == DialogResult.Cancel || ret == DialogResult.Abort)
                    return;
                MessageBox.Show("Failed to save hair and color!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Create the new xml document..
            var xml = new XDocument(new XElement("HairColor"));
            if (xml.Root == null)
            {
                sfd.Dispose();
                MessageBox.Show("Failed to save hair and color!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Add the hair id element..
            xml.Root.Add(new XElement("hair", new object[]
                {
                    new XAttribute("id", this.Player.Hair)
                }));

            // Add the color elements..
            xml.Root.Add(new XElement("HairColor", new object[]
                {
                    new XAttribute("a", this.Player.HairColor.A),
                    new XAttribute("r", this.Player.HairColor.R),
                    new XAttribute("g", this.Player.HairColor.G),
                    new XAttribute("b", this.Player.HairColor.B)
                }));
            xml.Root.Add(new XElement("SkinColor", new object[]
                {
                    new XAttribute("a", this.Player.SkinColor.A),
                    new XAttribute("r", this.Player.SkinColor.R),
                    new XAttribute("g", this.Player.SkinColor.G),
                    new XAttribute("b", this.Player.SkinColor.B)
                }));
            xml.Root.Add(new XElement("EyeColor", new object[]
                {
                    new XAttribute("a", this.Player.EyeColor.A),
                    new XAttribute("r", this.Player.EyeColor.R),
                    new XAttribute("g", this.Player.EyeColor.G),
                    new XAttribute("b", this.Player.EyeColor.B)
                }));
            xml.Root.Add(new XElement("ShirtColor", new object[]
                {
                    new XAttribute("a", this.Player.ShirtColor.A),
                    new XAttribute("r", this.Player.ShirtColor.R),
                    new XAttribute("g", this.Player.ShirtColor.G),
                    new XAttribute("b", this.Player.ShirtColor.B)
                }));
            xml.Root.Add(new XElement("UndershirtColor", new object[]
                {
                    new XAttribute("a", this.Player.UndershirtColor.A),
                    new XAttribute("r", this.Player.UndershirtColor.R),
                    new XAttribute("g", this.Player.UndershirtColor.G),
                    new XAttribute("b", this.Player.UndershirtColor.B)
                }));
            xml.Root.Add(new XElement("PantsColor", new object[]
                {
                    new XAttribute("a", this.Player.PantsColor.A),
                    new XAttribute("r", this.Player.PantsColor.R),
                    new XAttribute("g", this.Player.PantsColor.G),
                    new XAttribute("b", this.Player.PantsColor.B)
                }));
            xml.Root.Add(new XElement("ShoesColor", new object[]
                {
                    new XAttribute("a", this.Player.ShoesColor.A),
                    new XAttribute("r", this.Player.ShoesColor.R),
                    new XAttribute("g", this.Player.ShoesColor.G),
                    new XAttribute("b", this.Player.ShoesColor.B)
                }));

            // Attempt to save the document..
            xml.Save(sfd.FileName);
            sfd.Dispose();
        }
コード例 #33
0
ファイル: frmMain.cs プロジェクト: andry-dev/TSGE
        /// <summary>
        /// Saves the current buff list to an xml file.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveBuffs_Click(object sender, EventArgs e)
        {
            // Ask where to save to..
            var sfd = new SaveFileDialog
                {
                    AddExtension = true,
                    CheckPathExists = true,
                    DefaultExt = "xml",
                    Filter = "TSGE Buff Files (*.xml)|*.xml|All files (*.*)|*.*",
                    InitialDirectory = Application.StartupPath,
                    ValidateNames = true,
                };

            if (sfd.ShowDialog() != DialogResult.OK)
            {
                MessageBox.Show("Failed to save buffs!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Create the new xml document..
            var xml = new XDocument(new XElement("Buffs"));
            if (xml.Root == null)
            {
                sfd.Dispose();
                MessageBox.Show("Failed to save buffs!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Loop each buff in the players buff list..
            foreach (var b in this.Player.Buffs)
            {
                // Add each item to the xml document..
                xml.Root.Add(new XElement("buff", new object[]
                    {
                        new XAttribute("id", b.Id),
                        new XAttribute("duration", b.Duration)
                    }));
            }

            // Attempt to save the document..
            xml.Save(sfd.FileName);
            sfd.Dispose();
        }
コード例 #34
0
        private void ExcelBtn_Click(object sender, RoutedEventArgs e)
        {
            //先选择文件保存的位置
            Forms.SaveFileDialog dialog = new Forms.SaveFileDialog();
            if (dialog.ShowDialog() != Forms.DialogResult.OK)
            {
                return;
            }
            String outputFile = dialog.FileName;

            dialog.Dispose();

            MsExcel.Application oExcApp = null;
            MsExcel.Workbook    oExcBook;
            try
            {
                oExcApp = new MsExcel.Application();
                //创建一个Excel文档
                oExcBook = oExcApp.Workbooks.Add(true);

                #region 读取文本内容到 Excel 表格
                Console.WriteLine("正在读取文本内容到 Excel 表格");
                MsExcel.Worksheet worksheet1 = (MsExcel.Worksheet)oExcBook.Worksheets["sheet1"];
                worksheet1.Activate();
                oExcApp.Visible       = false;
                oExcApp.DisplayAlerts = false;
                MsExcel.Range range1 = worksheet1.get_Range("B1", "H2");
                range1.Columns.ColumnWidth = 8;
                range1.Columns.RowHeight   = 20;
                range1.Merge(false);
                //设置垂直居中和水平居中
                range1.VerticalAlignment   = MsExcel.XlVAlign.xlVAlignCenter;
                range1.HorizontalAlignment = MsExcel.XlHAlign.xlHAlignCenter;
                //range1.Font.Color = System.Drawing.ColorTranslator.ToOle
                range1.Font.Size                  = 20;
                range1.Font.Bold                  = true;
                worksheet1.Cells[1, 2]            = "学生成绩单";
                worksheet1.Cells[3, 1]            = "学号";
                worksheet1.Cells[3, 2]            = "姓名";
                worksheet1.Columns[1].ColumnWidth = 12;
                StreamReader sw = new StreamReader("../../../COM_source/list.csv");
                string       a_str;
                string[]     str_list;
                int          i = 4;
                a_str = sw.ReadLine();
                while (a_str != null)
                {
                    str_list = a_str.Split(",".ToCharArray());
                    worksheet1.Cells[i, 1] = str_list[0];
                    worksheet1.Cells[i, 2] = str_list[1];
                    i++;
                    a_str = sw.ReadLine();
                }
                sw.Close();

                #endregion

                #region 向工作表添加图表
                Console.WriteLine("正在向工作表添加图表");
                //通过随机函数构造源数据
                for (int i1 = 0; i1 < 5; i1++)
                {
                    for (int j = 0; j < 8; j++)
                    {
                        worksheet1.Cells[i1 + 18, j + 3].Value2 = "= CEILING.MATH(RAND() * 100)";
                        worksheet1.Cells[i1 + 4, j + 3].Value2  = worksheet1.Cells[i1 + 18, j + 3].Value;
                    }
                }
                //添加图表
                MsExcel.Shape theShape = worksheet1.Shapes.AddChart2(Type.Missing, MsExcel.XlChartType.xl3DColumn, 120, 130, 380, 250, Type.Missing);
                //设置图表标题文本
                theShape.Chart.ChartTitle.Caption = "学生成绩";
                worksheet1.Cells[3, 3].Value2     = "美术";
                worksheet1.Cells[3, 4].Value2     = "物理";
                worksheet1.Cells[3, 5].Value2     = "政治";
                worksheet1.Cells[3, 6].Value2     = "化学";
                worksheet1.Cells[3, 7].Value2     = "体育";
                worksheet1.Cells[3, 8].Value2     = "英语";
                worksheet1.Cells[3, 9].Value2     = "数学";
                worksheet1.Cells[3, 10].Value2    = "历史";
                //设定图表的数据区域
                MsExcel.Range range = worksheet1.get_Range("b3:j8");
                theShape.Chart.SetSourceData(range, Type.Missing);
                //设置单元格边框线型
                range1 = worksheet1.get_Range("a3", "j8");
                range1.Borders.LineStyle = MsExcel.XlLineStyle.xlContinuous;

                #endregion

                Console.WriteLine("正在将结果保存为Excel文档");

                //将结果保存为Excel文档
                object file_name = outputFile;
                //object file_name = Directory.GetCurrentDirectory() + @"/one.xlsx";

                oExcBook.Close(true, file_name, null);
            }
            catch (Exception e2)
            {
                Console.WriteLine(e2.Message);
            }
            finally
            {
                //释放相应的 COM对象资源
                oExcApp.Quit();
                Marshal.ReleaseComObject(oExcApp);
                oExcApp = null;
                System.GC.Collect();


                //启动 excel
                if (!outputFile.Contains(".xls"))
                {
                    outputFile = String.Concat(outputFile, ".xlsx");
                }
                if (excelCheckBox.IsChecked.Value && File.Exists(outputFile))
                {
                    Process.Start(outputFile);
                }
            }
        }
コード例 #35
0
        /// <summary>
        /// Export Global Settings
        /// </summary>
        private void ExportSelectedSettingsButton_Click(object sender, EventArgs e)
        {
            if (GlobalSettings_ListView.SelectedItems.Count == 1)
              {
            string settingsName = GlobalSettings_ListView.SelectedItems[0].Tag as string;
            System.Diagnostics.Debug.Assert(settingsName != null);

            HavokNavMeshGlobalSettings settingsToExported = GetGlobalSettings(settingsName);
            System.Diagnostics.Debug.Assert(settingsToExported != null);

            SaveFileDialog dlg = new SaveFileDialog();
            dlg.InitialDirectory = EditorManager.Project.ProjectDir;
            dlg.FileName = null;
            dlg.Filter = "Nav Mesh Global Settings|*.*";
            dlg.Title = "Save nav mesh global settings to editor format";

            if (dlg.ShowDialog(this) != DialogResult.OK)
              return;

            string filename = dlg.FileName;
            dlg.Dispose();

            try
            {
              BinaryFormatter fmt = SerializationHelper.BINARY_FORMATTER;
              FileStream fs = new FileStream(filename, FileMode.Create);
              fmt.Serialize(fs, settingsToExported);
              fs.Close();
            }
            catch (Exception ex)
            {
              EditorManager.ShowMessageBox("Failed to save nav mesh global settings to file:\n\n" + ex.Message, "Error saving file", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
              }
        }
コード例 #36
0
        public bool Export(fyiReporting.RDL.OutputPresentationType type)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "Export to " + type.ToString().ToUpper();
            switch (type)
            {
                case OutputPresentationType.CSV:
                    sfd.Filter = "CSV file (*.csv)|*.csv|All files (*.*)|*.*";
                    break;
                case OutputPresentationType.XML:
                    sfd.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
                    break;
                case OutputPresentationType.PDF:
                case OutputPresentationType.PDFOldStyle:
                    sfd.Filter = "PDF file (*.pdf)|*.pdf|All files (*.*)|*.*";
                    break;
                case OutputPresentationType.TIF:
                    sfd.Filter = "TIF file (*.tif, *.tiff)|*.tiff;*.tif|All files (*.*)|*.*";
                    break;
                case OutputPresentationType.RTF:
                    sfd.Filter = "RTF file (*.rtf)|*.rtf|All files (*.*)|*.*";
                    break;
                case OutputPresentationType.Word:
                    sfd.Filter = "DOC file (*.doc)|*.doc|All files (*.*)|*.*";
                    break;
                case OutputPresentationType.Excel:
                    sfd.Filter = "Excel file (*.xlsx)|*.xlsx|All files (*.*)|*.*";
                    break;
                case OutputPresentationType.HTML:
                    sfd.Filter = "Web Page (*.html, *.htm)|*.html;*.htm|All files (*.*)|*.*";
                    break;
                case OutputPresentationType.MHTML:
                    sfd.Filter = "MHT (*.mht)|*.mhtml;*.mht|All files (*.*)|*.*";
                    break;
                default:
                    throw new Exception("Only HTML, MHT, XML, CSV, RTF, DOC, Excel, TIF and PDF are allowed as Export types.");
            }
            sfd.FilterIndex = 1;

            if (SourceFile != null)
            {
                sfd.FileName = Path.GetFileNameWithoutExtension(SourceFile.LocalPath) + "." + type;
            }
            else
            {
                sfd.FileName = "*." + type;
            }

            try
            {
                if (sfd.ShowDialog(this) != DialogResult.OK)
                    return false;

                // save the report in the requested rendered format
                bool rc = true;
                // tif can be either in color or black and white; ask user what they want
                if (type == OutputPresentationType.TIF)
                {
                    DialogResult dr = MessageBox.Show(this, "Do you want to display colors in TIF?", "Export", MessageBoxButtons.YesNoCancel);
                    if (dr == DialogResult.No)
                        type = OutputPresentationType.TIFBW;
                    else if (dr == DialogResult.Cancel)
                        return false;
                }
                try { SaveAs(sfd.FileName, type); }
                catch (Exception ex)
                {
                    MessageBox.Show(this,
                        ex.Message, "Export Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    rc = false;
                }
                return rc;
            }
            finally
            {
                sfd.Dispose();
            }
        }
コード例 #37
0
ファイル: Fmain.cs プロジェクト: Digiman/MyToDoApp
 /// <summary>
 /// Вызов пункта меню Сохранить файл
 /// </summary>
 private void SaveExecute(object sender, EventArgs e)
 {
     SaveFileDialog dg = new SaveFileDialog();
     dg.Title = "Введите название файла для сохранения списка задач";
     dg.Filter = "XML файлы|*.xml";
     dg.ShowDialog();
     if (dg.FileName != "")
     {
         // сохранение списка в файл
         SaveList(dg.FileName);
     }
     dg.Dispose();
 }
コード例 #38
0
ファイル: PicViewer.cs プロジェクト: Chrisjw42/PictureViewer
        private void SaveImageOld(SaveFileDialog dlg, Image img)
        {
            // Create a MemoryStream that will be minimally scoped
            using (MemoryStream memStream = new MemoryStream())
            {
                // Save the image to the memorystream in it's native format
                img.Save(memStream, listLoadedImg[curImgIndex].GetOriginalFormat());

                // Creating an Image that can actually be saved - Should probably make everything up to this point a method
                // Should also incorporate some kind of using statement to close off the MemoryStream
                Image imgToSave = Image.FromStream(memStream);

                // FilterIndex appears to record which filetype is arrIsProcessed
                switch (dlg.FilterIndex)
                {
                    case 1:
                        imgToSave.Save(dlg.FileName, ImageFormat.Jpeg);
                        break;
                    case 2:
                        imgToSave.Save(dlg.FileName, ImageFormat.Bmp);
                        break;
                    case 3:
                        imgToSave.Save(dlg.FileName, ImageFormat.Png);
                        break;
                    case 4:
                        imgToSave.Save(dlg.FileName, ImageFormat.Tiff);
                        break;
                }
            } dlg.Dispose();
        }
コード例 #39
0
 public void Dispose()
 {
     _saveFileDialog.Dispose();
 }
コード例 #40
0
        private void WordBtn_Click(object sender, RoutedEventArgs e)
        {
            //先选择文件保存的位置
            Forms.SaveFileDialog dialog = new Forms.SaveFileDialog();
            if (dialog.ShowDialog() != Forms.DialogResult.OK)
            {
                return;
            }
            String outputFile = dialog.FileName;

            dialog.Dispose();

            MsWord.Application oWordApplic = null;
            MsWord.Document    odoc;
            try
            {
                //创建操作Word文档的项目
                oWordApplic = new MsWord.Application();
                object missing = Missing.Value;
                String filedir = Directory.GetCurrentDirectory(); // debug目录
                Console.WriteLine("当前文件目录: " + filedir);

                #region 创建Word文档的小节
                MsWord.Range curRange;
                object       curTxt;
                int          curSectionNum = 1;
                odoc = oWordApplic.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                odoc.Activate();
                Console.WriteLine("正在生成文档小节");
                object section_nextPage = MsWord.WdBreakType.wdSectionBreakNextPage;
                object page_break       = MsWord.WdBreakType.wdPageBreak;
                //添加4个分节符,共5个小节,小节的类型是下一页
                for (int si = 0; si < 4; si++)
                {
                    //注意:Paragraphs的下标从 1 开始而不是 0
                    odoc.Paragraphs[1].Range.InsertParagraphAfter();
                    odoc.Paragraphs[1].Range.InsertBreak(ref section_nextPage);
                }
                #endregion

                #region 插入摘要文本并设置文本格式
                //从文件 abstract.txt中读取文本内容作为摘要部分内容,Word文档的内容都是具有格式的。
                Console.WriteLine("正在插入摘要内容");
                curSectionNum = 1;
                curRange      = odoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                curRange.Select();
                string one_str, key_word;
                //摘要的文本来自 abstract.txt文件
                StreamReader file_abstract = new StreamReader("../../../COM_source/abstract.txt");
                oWordApplic.Options.Overtype = false; //overtype改写模式
                MsWord.Selection curSelection = oWordApplic.Selection;

                if (curSelection.Type == MsWord.WdSelectionType.wdSelectionNormal)
                {
                    one_str = file_abstract.ReadLine();  //读入题目
                    curSelection.TypeText(one_str);
                    curSelection.TypeParagraph();        //添加段落标记
                    curSelection.TypeText(" 摘要");
                    curSelection.TypeParagraph();        //添加段落标志,进入下一段
                    key_word = file_abstract.ReadLine(); //读入关键字
                    one_str  = file_abstract.ReadLine(); //读入段落文本(例子有 3段)
                    while (one_str != null)
                    {
                        curSelection.TypeText(one_str);
                        curSelection.TypeParagraph(); //读入一个段落就写一段
                        one_str = file_abstract.ReadLine();
                    }
                    curSelection.TypeText("关键字: ");
                    curSelection.TypeText(key_word); ///写关键字
                    curSelection.TypeParagraph();
                }
                file_abstract.Close();

                //下面开始设置摘要的格式(上面是内容的读取)
                //摘要的标题
                curRange           = odoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                curTxt             = curRange.Paragraphs[1].Range.Text;
                curRange.Font.Name = "宋体";
                curRange.Font.Size = 22;
                curRange.Paragraphs[1].Alignment = MsWord.WdParagraphAlignment.wdAlignParagraphCenter; //中间对齐

                //“摘要” 二字
                curRange = odoc.Sections[curSectionNum].Range.Paragraphs[2].Range; //第二段
                curRange.Select();                                                 //成为选择区(在其上进行后续的操作)
                curRange.Paragraphs[1].Alignment = MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
                curRange.Font.Name = "黑体";
                curRange.Font.Size = 16;

                //摘要正文
                //自己用一个变量存起来这个常用的数据
                MsWord.Range curSectionRange = odoc.Sections[curSectionNum].Range;

                odoc.Sections[curSectionNum].Range.Paragraphs[3].Alignment = MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
                for (int i = 3; i < odoc.Sections[curSectionNum].Range.Paragraphs.Count; i++)
                {
                    curRange = odoc.Sections[curSectionNum].Range.Paragraphs[i].Range;
                    curTxt   = curRange.Paragraphs[1].Range.Text;
                    curRange.Select();

                    curRange.Font.Name = "宋体";
                    curRange.Font.Size = 12;
                    odoc.Sections[curSectionNum].Range.Paragraphs[i].LineSpacingRule = MsWord.WdLineSpacing.wdLineSpaceMultiple;
                    //多倍行距,1.25倍,这里的浮点值是以point为单位的,不是行距倍数 ?????-----
                    odoc.Sections[curSectionNum].Range.Paragraphs[i].LineSpacing = 15f;
                    curSectionRange.Paragraphs[i].IndentFirstLineCharWidth(2); //段落开头的缩进
                }
                //设置“关键字:”为黑体
                curRange = curRange.Paragraphs[curRange.Paragraphs.Count].Range; //最后一段的 range
                curTxt   = curRange.Paragraphs[1].Range.Text;                    //能不能直接用 curRange.Text ??????---------
                object range_start, range_end;
                range_start = curRange.Start;
                range_end   = curRange.Start + 4;// ??
                curRange    = odoc.Range(ref range_start, ref range_end);
                curTxt      = curRange.Text;
                curRange.Select();
                curRange.Font.Bold = 1;
                curRange.Font.Name = "黑体"; //应该加上

                #endregion

                #region 插入目录并设置目录格式

                Console.WriteLine("正在插入目录");
                curSectionNum = 2; //转到第二小节了
                curRange      = odoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                curRange.Select(); //变成选择区

                //插入目录时指定的参数
                object useheading_styles     = true; //使用内置的目录标题样式
                object upperheading_level    = 1;    //最高的标题级别 (大纲视图的选择)
                object lowerheading_level    = 3;    //最低标题级别
                object useelds               = 1;    //true表示创建的是目录 ?????
                object tableid               = 1;
                object RightAlignPageNumbers = true; //右边距对齐的页码
                object IncludePageNumbers    = true; //目录中包含页码

                curSelection = oWordApplic.Selection;
                curSelection.TypeText("目录"); //第一段写标题
                curSelection.TypeParagraph();
                curSelection.Select();

                curRange = odoc.Sections[curSectionNum].Range.Paragraphs[2].Range; //转到第二段
                //插入的表格会替代当前range
                //range为非折叠时,TablesOfContents会代替range,引起小节数减少
                curRange.Collapse();
                //在这里添加了目录,记得在最后需要更新目录
                MsWord.TableOfContents tablesOfContents = odoc.TablesOfContents.Add(curRange, ref useheading_styles, ref upperheading_level, ref lowerheading_level, ref useelds, ref tableid, ref RightAlignPageNumbers,
                                                                                    ref IncludePageNumbers, ref missing, ref missing, ref missing, ref missing);


                odoc.Sections[curSectionNum].Range.Paragraphs[1].Alignment       = MsWord.WdParagraphAlignment.wdAlignParagraphCenter; //设置"目录"两个字的样式
                odoc.Sections[curSectionNum].Range.Paragraphs[1].Range.Font.Bold = 1;
                odoc.Sections[curSectionNum].Range.Paragraphs[1].Range.Font.Name = "黑体";
                odoc.Sections[curSectionNum].Range.Paragraphs[1].Range.Font.Size = 16;
                #endregion

                #region 插入第一章正文并设置正文格式
                curSectionNum = 3;
                odoc.Sections[curSectionNum].Range.Paragraphs[1].Range.Select();
                curRange = odoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                Console.WriteLine("正在设置标题样式");
                object wdFontSizeIndex;
                //此序号在Word中的编号是格式->显示格式->样式和格式->显示所有样式的序号
                //14是标题一,一级标题:三号黑体
                wdFontSizeIndex = 14;
                oWordApplic.ActiveDocument.Styles.get_Item(ref wdFontSizeIndex).ParagraphFormat.Alignment = MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
                oWordApplic.ActiveDocument.Styles.get_Item(ref wdFontSizeIndex).Font.Name = "黑体";
                oWordApplic.ActiveDocument.Styles.get_Item(ref wdFontSizeIndex).Font.Size = 16; //三号
                wdFontSizeIndex = 15;                                                           //15是标题二,二级标题:小三号黑体
                oWordApplic.ActiveDocument.Styles.get_Item(ref wdFontSizeIndex).Font.Name = "黑体";
                oWordApplic.ActiveDocument.Styles.get_Item(ref wdFontSizeIndex).Font.Size = 15; //小三号

                //用指定的标题来设置文本格式
                object Style1 = MsWord.WdBuiltinStyle.wdStyleHeading1; //一级标题:三号黑体
                object Style2 = MsWord.WdBuiltinStyle.wdStyleHeading2; //二级标题:小三号黑体

                odoc.Sections[curSectionNum].Range.Select();
                curSelection = oWordApplic.Selection;
                //读入第一章文本信息
                StreamReader file_content = new StreamReader("../../../COM_source/content.txt");
                one_str = file_content.ReadLine(); // 一级标题
                curSelection.TypeText(one_str);
                curSelection.TypeParagraph();
                one_str = file_content.ReadLine(); //二级标题
                curSelection.TypeText(one_str);
                curSelection.TypeParagraph();
                one_str = file_content.ReadLine(); //正文
                while (one_str != null)
                {
                    curSelection.TypeText(one_str);
                    curSelection.TypeParagraph();
                    one_str = file_content.ReadLine(); //正文
                }
                file_content.Close();
                //段落的对齐方式
                curRange = odoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                curRange.set_Style(ref Style1);
                odoc.Sections[curSectionNum].Range.Paragraphs[1].Alignment = MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
                curRange = odoc.Sections[curSectionNum].Range.Paragraphs[2].Range;
                curRange.set_Style(ref Style2);
                //第一章正文文本格式
                for (int i = 3; i < odoc.Sections[curSectionNum].Range.Paragraphs.Count; i++)
                {
                    curRange = odoc.Sections[curSectionNum].Range.Paragraphs[i].Range;
                    curRange.Select();
                    curRange.Font.Name = "宋体";
                    curRange.Font.Size = 12;
                    odoc.Sections[curSectionNum].Range.Paragraphs[i].LineSpacingRule = MsWord.WdLineSpacing.wdLineSpaceMultiple;
                    //多倍行距,1.25倍
                    odoc.Sections[curSectionNum].Range.Paragraphs[i].LineSpacing = 15f;
                    odoc.Sections[curSectionNum].Range.Paragraphs[i].IndentFirstLineCharWidth(2);
                }
                #endregion

                #region 插入表格并设置表格格式
                Console.WriteLine("正在插入第二章内容-表格");
                curSectionNum = 4;
                odoc.Sections[curSectionNum].Range.Select(); //调整了 oWordApplic.Selection
                curRange     = odoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                curSelection = oWordApplic.Selection;
                curSelection.TypeText("2 表格");
                curSelection.TypeParagraph();
                curSelection.TypeText("表格示例");
                curSelection.TypeParagraph();
                curSelection.TypeParagraph();
                curRange = odoc.Sections[curSectionNum].Range.Paragraphs[3].Range;
                odoc.Sections[curSectionNum].Range.Paragraphs[3].Range.Select();
                curSelection = oWordApplic.Selection;
                MsWord.Table oTable;
                oTable = curRange.Tables.Add(curRange, 5, 3, ref missing, ref missing); //添加表格
                oTable.Range.ParagraphFormat.Alignment = MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
                oTable.Range.Rows.Alignment            = MsWord.WdRowAlignment.wdAlignRowCenter;
                oTable.Columns[1].Width         = 80;
                oTable.Columns[2].Width         = 180;
                oTable.Columns[3].Width         = 80;
                oTable.Cell(1, 1).Range.Text    = " 字段";
                oTable.Cell(1, 2).Range.Text    = " 描述";
                oTable.Cell(1, 3).Range.Text    = " 数据类型";
                oTable.Cell(2, 1).Range.Text    = "ProductID";
                oTable.Cell(2, 2).Range.Text    = " 产品标识";
                oTable.Cell(2, 3).Range.Text    = " 字符串";
                oTable.Borders.InsideLineStyle  = MsWord.WdLineStyle.wdLineStyleSingle;
                oTable.Borders.OutsideLineStyle = MsWord.WdLineStyle.wdLineStyleSingle;
                curRange = odoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                curRange.set_Style(ref Style1);
                curRange.ParagraphFormat.Alignment = MsWord.WdParagraphAlignment.wdAlignParagraphCenter;

                #endregion

                #region 插入图片
                Console.WriteLine("正在插入第三章内容-插入图片");
                curSectionNum = 5;
                odoc.Sections[curSectionNum].Range.Paragraphs[1].Range.Select();  // understand what Select() means for ----------------------------- dif with oWordApplic.Selection
                curRange     = odoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                curSelection = oWordApplic.Selection;
                curSelection.TypeText("3 图片");
                curSelection.TypeParagraph();
                curSelection.TypeText("图片示例");
                curSelection.TypeParagraph();
                curSelection.InlineShapes.AddPicture(@"F:\VS2017 code\WinProcedure\COM_source\whu.png", ref missing, ref missing, ref missing); //TODO:插入图片,图片名无法根据相对路径来找到
                curRange = odoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                curRange.set_Style(ref Style1);
                curRange.ParagraphFormat.Alignment = MsWord.WdParagraphAlignment.wdAlignParagraphCenter;

                #endregion

                #region 设置各小节的页眉页脚
                Console.WriteLine("正在设置第1节摘要的页眉内容");
                //设置页脚 section 1 摘要
                curSectionNum = 1;
                odoc.Sections[curSectionNum].Range.Select();
                //进入页脚视图
                oWordApplic.ActiveWindow.View.SeekView = MsWord.WdSeekView.wdSeekCurrentPageFooter;
                odoc.Sections[curSectionNum].Headers[MsWord.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.
                Borders[MsWord.WdBorderType.wdBorderBottom].LineStyle = MsWord.WdLineStyle.wdLineStyleNone;
                oWordApplic.Selection.HeaderFooter.PageNumbers.RestartNumberingAtSection = true;
                oWordApplic.Selection.HeaderFooter.PageNumbers.NumberStyle    = MsWord.WdPageNumberStyle.wdPageNumberStyleUppercaseRoman;
                oWordApplic.Selection.HeaderFooter.PageNumbers.StartingNumber = 1;
                //切换到文档
                oWordApplic.ActiveWindow.ActivePane.View.SeekView = MsWord.WdSeekView.wdSeekMainDocument;
                Console.WriteLine("正在设置第 2节目录页眉内容");
                //设置页脚section 2目录
                curSectionNum = 2;
                odoc.Sections[curSectionNum].Range.Select();
                //进入页脚视图
                oWordApplic.ActiveWindow.ActivePane.View.SeekView = MsWord.WdSeekView.wdSeekCurrentPageFooter;
                odoc.Sections[curSectionNum].Headers[MsWord.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Borders[MsWord.WdBorderType.wdBorderBottom].LineStyle = MsWord.WdLineStyle.wdLineStyleNone;
                oWordApplic.Selection.HeaderFooter.PageNumbers.RestartNumberingAtSection = false;
                oWordApplic.Selection.HeaderFooter.PageNumbers.NumberStyle = MsWord.WdPageNumberStyle.wdPageNumberStyleUppercaseRoman;

                //切换到文档
                oWordApplic.ActiveWindow.ActivePane.View.SeekView = MsWord.WdSeekView.wdSeekMainDocument;
                //第 1章页眉页码设置
                curSectionNum = 3;
                odoc.Sections[curSectionNum].Range.Select();
                //切换进入页脚视图
                oWordApplic.ActiveWindow.ActivePane.View.SeekView = MsWord.WdSeekView.wdSeekCurrentPageFooter;
                curSelection = oWordApplic.Selection;
                curRange     = curSelection.Range;
                //本节页码不续上节
                oWordApplic.Selection.HeaderFooter.PageNumbers.RestartNumberingAtSection = true;
                //页码格式为阿拉伯数字
                oWordApplic.Selection.HeaderFooter.PageNumbers.NumberStyle = MsWord.WdPageNumberStyle.wdPageNumberStyleArabic;
                //起始页码为 1
                oWordApplic.Selection.HeaderFooter.PageNumbers.StartingNumber = 1;
                //添加页码域
                object fieldpage = MsWord.WdFieldType.wdFieldPage;
                oWordApplic.Selection.Fields.Add(oWordApplic.Selection.Range, ref fieldpage, ref missing, ref missing);
                //居中对齐
                oWordApplic.Selection.ParagraphFormat.Alignment = MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
                //本小节不链接到上一节
                odoc.Sections[curSectionNum].Headers[MsWord.WdHeaderFooterIndex.wdHeaderFooterPrimary].LinkToPrevious = false;
                //切换进入正文视图
                oWordApplic.ActiveWindow.ActivePane.View.SeekView = MsWord.WdSeekView.wdSeekMainDocument;

                #endregion

                //更新目录
                Console.WriteLine("正在更新目录");
                tablesOfContents.Update();
                //tablesOfContents.UpdatePageNumbers();

                #region Word文档保存
                Console.WriteLine("正在保存文档");
                //object fileName = filedir + "/My_doc.doc";
                object fileName = outputFile;

                odoc.SaveAs2(fileName);
                odoc.Close();
                //Word文档任务完成后,需要释放Document对象和Application对象
                Console.WriteLine("正在释放 COM 资源");
                //释放COM资源
                Marshal.ReleaseComObject(odoc);
                odoc = null;
                oWordApplic.Quit();
                Marshal.ReleaseComObject(oWordApplic);
                oWordApplic = null;
                #endregion
            }
            catch (Exception ee)
            {
                Console.WriteLine(ee.Message);
            }
            finally
            {
                #region 终止Word进程
                Console.WriteLine("正在结束Word进程");
                //关闭Word进程
                System.Diagnostics.Process[] allProcess = System.Diagnostics.Process.GetProcesses();
                for (int i = 0; i < allProcess.Length; i++)
                {
                    string procName = allProcess[i].ProcessName;
                    if (String.Compare(procName, "WINWORD") == 0)
                    {
                        if (allProcess[i].Responding && !allProcess[i].HasExited)
                        {
                            allProcess[i].Kill();
                        }
                    }
                }
                #endregion

                //启动word
                if (!outputFile.Contains(".doc"))
                {
                    outputFile = String.Concat(outputFile, ".docx");
                }
                if (wordCheckBox.IsChecked.Value && File.Exists(outputFile))
                {
                    Process.Start(outputFile);
                }
            }
        }
コード例 #41
0
ファイル: MainForm.cs プロジェクト: segrived/ImageEditor
 private void MenuFileSaveAs_Click(object sender, EventArgs e)
 {
     if (_workingBitmap == null) return;
     var dialog = new SaveFileDialog {
         Filter = @"Jpeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif|Png Image|*.png",
         Title  = @"Save an Image File"
     };
     if (dialog.ShowDialog() != DialogResult.OK || dialog.FileName.Equals("")) return;
     var format = ImageFormat.Bmp;
     switch (dialog.FilterIndex) {
         case 1: format = ImageFormat.Jpeg; break;
         case 2: format = ImageFormat.Bmp; break;
         case 3: format = ImageFormat.Gif; break;
         case 4: format = ImageFormat.Png; break;
     }
     dialog.Dispose();
     SaveImage(dialog.FileName, format);
 }
コード例 #42
0
ファイル: MapFile.cs プロジェクト: net-haus/My-FyiReporting
 /// <summary>
 /// Asks user for file name and sets the map file name to user specified one
 /// </summary>
 /// <returns></returns>
 private bool SaveAs()
 {
     SaveFileDialog sfd = new SaveFileDialog();
     sfd.DefaultExt = "xml";
     sfd.Filter = "RDL Map files (*.xml)|*.xml|" +
         "All files (*.*)|*.*";
     sfd.FilterIndex = 1;
     sfd.CheckFileExists = false;
     bool rc = false;
     try
     {
         if (sfd.ShowDialog(this) == DialogResult.OK)
         {
             map.File = sfd.FileName;
             rc = true;
         }
     }
     finally
     {
         sfd.Dispose();
     }
     return rc;
 }