For some reason after my SaveFileDialog, my app will never show the MessageBox. Is there something I'm missing? Or is this a threading issue?
I run the application as a Windows Form application using VS 2010 Express.
I do not get any exceptions.
To add: When I step through the code, all seems to go well. Which is weird, so I believe it is a timing issue.
Pointed out by LarsTech and others, the MessageBoxes do show up, however the focus is gone; in other words the MessageBox is pushed behind other windows or minimized. This is a problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.IO;
namespace SpeedDating
{
class Program
{
[STAThread]
static void Main(string[] args)
{
string filename = "test.test"; // args[0];
string ext = filename.Substring(filename.LastIndexOf('.'));
SaveFileDialog dialog = new SaveFileDialog();
dialog.Title = "SpeedDating App";
dialog.RestoreDirectory = true;
dialog.CheckFileExists = false;
dialog.CheckPathExists = false;
dialog.FileName = DateTime.Now.ToString("yyyyMMdd") + ext;
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK && dialog.FileName != "")
{
try
{
FileStream outfs = File.Create(dialog.FileName);
FileStream infs = File.Open(filename, FileMode.Open);
infs.CopyTo(outfs);
infs.Close();
outfs.Close();
}
catch (NotSupportedException ex)
{
MessageBox.Show("Probably removed the original file.");
}
}
else
{
MessageBox.Show("No path found to write to.");
}
MessageBox.Show("I came here and all I got was this louzy printline");
}
}
}
I tried this one and it showed right away:
MessageBox.Show(new Form() { WindowState = FormWindowState.Maximized, TopMost = true }, "You clicked Cancel button", "Cancel");
Try this for your Message Box.
MessageBox.Show(this,"Probably removed the original file.");
I created a new project and pasted your code and it works for me. Make sure you have done a full rebuild before running. Also, with this line:
dialog.FileName = DateTime.Now.ToString(format) + "." + ext;
The dialog box will have a file name to begin with. Therefore, only hitting the cancel button (assuming you don't clear the save dialog first) will trigger the message box. Either way, I got the message box to pop up by failing your IF test either way. Your code looks alright.
Perhaps you should put the SaveFileDialog in a using to ensure its disposal prior to the MessageBox call:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.IO;
namespace SpeedDating
{
class Program
{
[STAThread]
static void Main(string[] args)
{
string filename = "test.test"; // args[0];
string ext = filename.Substring(filename.LastIndexOf('.'));
using (SaveFileDialog dialog = new SaveFileDialog())
{
dialog.Title = "SpeedDating App by K.Toet";
dialog.RestoreDirectory = true;
dialog.CheckFileExists = false;
dialog.CheckPathExists = false;
dialog.FileName = DateTime.Now.ToString("yyyyMMdd") + ext;
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK && dialog.FileName != "")
{
try
{
FileStream outfs = File.Create(dialog.FileName);
FileStream infs = File.Open(filename, FileMode.Open);
infs.CopyTo(outfs);
infs.Close();
outfs.Close();
}
catch (NotSupportedException ex)
{
MessageBox.Show("Probably removed the original file.");
}
}
else
{
MessageBox.Show("No path found to write to.");
}
}
MessageBox.Show("I came here and all I got was this louzy printline");
}
}
}
Related
I'm using the Ookii Vista folder dialog for ease of use, and I have this code going on which is called from a button:
using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Ookii.Dialogs;
private string LoadDirectories()
{
VistaFolderBrowserDialog fbd = new VistaFolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK && fbd.SelectedPath.Contains("U000"))
{
return fbd.SelectedPath;
}
else
{
MessageBox.Show("Folder must be root assembly, which has U000 in name");
}
return string.Empty;
}
Currently, if the user does not pick a folder with U000 in the name, the dialog will close, but I want it to stay open until user either cancels or sets the correct folder path. I can't find this anywhere.
A simple realization of your needs (Add a while):
Used nuget: Ookii.Dialogs.Wpf
private string LoadDirectories()
{
VistaFolderBrowserDialog fbd = new VistaFolderBrowserDialog();
while (true)
{
if (fbd.ShowDialog() == false)
{
break;
}
else if (fbd.SelectedPath.Contains("U000"))
{
return fbd.SelectedPath;
}
else
{
MessageBox.Show("Folder must be root assembly, which has U000 in name");
}
}
return string.Empty;
}
output:
I haven't really written anything outside of Powershell in a long time, and I know this is ugly, but I can't seem to figure out why my new PDF is not adding the page numbers. I pulled the example from this itext kb.
I tried to make this basic app so people in the office could add the page numbers to PDF's. Here's what I have so far. It will create the new PDF (duplicate of the original), but it's not adding the page numbers.
Basically they use button1 to find their PDF via the Windows File Explorer dialog. It just stores the filename in a textbox. The second button is the "save" and should take the src file and make a copy of the src with only adding the page number at the bottom of the file (or anywhere at this point).
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
namespace PDFManipulation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
textBox1.Text = file;
}
catch (System.IO.IOException)
{
}
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
}
private void button2_Click(object sender, EventArgs e)
{
Stream myStream;
//SaveFileDialog saveFileDialog1 = new SaveFileDialog();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
string SRC = textBox1.Text;
string DEST = saveFileDialog1.FileName;
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));
Document doc = new Document(pdfDoc);
int numberOfPages = pdfDoc.GetNumberOfPages();
for (int i = 1; i <= numberOfPages; i++)
{
// Write aligned text to the specified by parameters point
doc.ShowTextAligned(new Paragraph("page " + i + " of " + numberOfPages),559, 806, i, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
}
doc.Close();
}
}
MessageBox.Show("PDF Page Numbering Added!", "Pages Added",MessageBoxButtons.OK);
Application.Exit();
}
}
}
I'm a dumb dumb. The x,y coordinates were off as the value 812 for the height is off the page.
I have registered a program in windows explorer right click menu using this link. .NET-Shell-Extension, It works fine. But my problem is I want to target XML file, If I right click on that file it will load that XML file and open fileDialog to choose folder and create folder and sub-folder according to the structure of the XML file. It looks fine when I tasted it on shell server. I tried to register with this following code but its not appearing when I click on any XML file.
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using SharpShell.Attributes;
using SharpShell.SharpContextMenu;
using System.Xml;
namespace ClassLibrary1
{
[ComVisible(true)]
[COMServerAssociation(AssociationType.ClassOfExtension, ".xml")]
public class Class1 : SharpContextMenu
{
protected override bool CanShowMenu()
{
return true;
}
protected override ContextMenuStrip CreateMenu()
{
var menu = new ContextMenuStrip();
var createFolder = new ToolStripMenuItem
{
Text = "Create Folder",
};
createFolder.Click += (sender, args) => myFunction();
menu.Items.Add(createFolder);
return menu;
}
private void myFunction()
{
var ofd = new OpenFileDialog();
foreach (var filePath in SelectedItemPaths)
{
if (ofd.ShowDialog() != DialogResult.Cancel)
{
string fullPath = ofd.FileName;
using (XmlTextReader reader = new XmlTextReader(fullPath))
{
var basePath = filePath + "/";
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
var baseDirPath = Path.Combine(basePath + reader.Name);
Directory.CreateDirectory(baseDirPath);
break;
case XmlNodeType.Text:
Directory.CreateDirectory(basePath + reader.Name + "/" + reader.Value);
break;
}
}
}
}
}
}
}
}
I wanted to avoid Excel ole calls through my c++ code to launch excel. I also wanted to wait for excel to be closed before proceeding. For that I implemented following C# program and I use system call to execute it. It works but any changes I make to the excel are not getting saved. I am not sure whats happening.
Can you please help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace excelHandler
{
class Program
{
private static bool isClosed = false;
private static void app_WorkbookBeforeClose(Excel.Workbook wb, ref bool cancel)
{
if (!wb.Saved)
{
DialogResult result = MessageBox.Show("Do you want to save the " +
"changes you made to " + wb.FullName + "?", "Blizzard Excel",
MessageBoxButtons.YesNoCancel,MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button1,
MessageBoxOptions.DefaultDesktopOnly);
switch (result)
{
case DialogResult.Yes:
wb.Save();
break;
case DialogResult.Cancel:
cancel = true;
break;
// The following code ensures that the default Save File
// dialog is not displayed.
case DialogResult.No:
wb.Saved = true;
break;
}
}
isClosed = !cancel;
// wb.Parent
}
static int Main(string[] args)
{
int returnValue = 0;
if (args.Length != 1)
{
Console.WriteLine("-E- excelHandler takes single XLXS as input");
return -1;
}
string inputFile = args[0];
if (!File.Exists(inputFile))
{
Console.WriteLine("-E- Input File doesn't exist: {0}", inputFile);
return -1;
}
Excel.Application xlApp = new Excel.Application();
try
{
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(inputFile);
xlApp.Visible = true;
Excel.AppEvents_WorkbookBeforeCloseEventHandler Event_BeforeBookClose;
Event_BeforeBookClose = new Excel.AppEvents_WorkbookBeforeCloseEventHandler(app_WorkbookBeforeClose);
xlApp.WorkbookBeforeClose += Event_BeforeBookClose;
// ||
while (!isClosed)
{
System.Threading.Thread.Sleep(300);
}
//xlWorkBook.Close(true);
Marshal.ReleaseComObject(xlWorkBook);
}
catch
{
}
finally
{
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
}
return returnValue;
}
}
}
I found the issue. It was with MessageBoxOptions.DefaultDesktopOnly option in
DialogResult result = MessageBox.Show("Do you want to save the " +
"changes you made to " + wb.FullName + "?", "Blizzard Excel",
MessageBoxButtons.YesNoCancel,MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button1,
MessageBoxOptions.DefaultDesktopOnly);
I changed it to following to get it working.
NativeWindow nw = new System.Windows.Forms.NativeWindow();
nw.AssignHandle(new IntPtr(wb.Parent.Hwnd));
DialogResult result = MessageBox.Show(nw,"Do you want to save the " +
"changes you made to " + wb.FullName + "?", "Blizzard Excel",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button1);
I am still not sure what was wrong with my initial code.
I have created a C sharp project in which i have added a ShockwaveFlashObject to play my swf file.
The problem i am facing is when i create an installer for my project it works correctly on my machine on installation, but on my laptop the swf loads correctly but doesn't respond to the _FSCommand. I cannot use a try and catch block as it is not entering the FSCommand handle. Do i need to bundle something with my installation?
The laptop i am using is brand new and i wanted it that way so that i know what all stuff is needed for things to work correctly so that i can add prerequisites to my installer.
Also idk if this information is of any use but I am using advanced installer to build and exe for my project.
PS i have added things like the below code to know if FSCommand gets executed.
MessageBox.Show("step 1/2/3");
Here is the entire code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Globalization;
namespace WindowsFormsApplication1
{
public partial class frmFlashIntro : Form
{
public Form FormfrmMainRef { get; set; }
public frmFlashIntro()
{
InitializeComponent();
axShockwaveFlash1.Playing = true;
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
string currentPath = Directory.GetCurrentDirectory();
axShockwaveFlash1.Movie = "file://\\" + currentPath + "\\intro.swf";
}
private void axShockwaveFlash1_FSCommand(object sender, AxShockwaveFlashObjects._IShockwaveFlashEvents_FSCommandEvent e)
{
MessageBox.Show("step 1");
string btn = e.command.ToString();
MessageBox.Show("step 2");
if (btn == "play")
{
MessageBox.Show("step 3");
try
{
MessageBox.Show("step 4");
var form2 = new frmMain();
MessageBox.Show("step 5");
this.Hide();
MessageBox.Show("step 6");
form2.Show();
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
}
if (btn == "syllabus")
{
MySqlConnection con = new MySqlConnection(Properties.Settings.Default.conString);
con.Open();
Syllabus_usageInformation syl = new Syllabus_usageInformation(this);
MySqlCommand cmd = new MySqlCommand("SELECT ImageFiles FROM misc WHERE id=1", con);
byte[] img = (byte[])cmd.ExecuteScalar();
string strFn = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream(strFn, FileMode.CreateNew, FileAccess.Write);
fs.Write(img, 0, img.Length);
fs.Flush();
fs.Close();
con.Close();
syl.kpImageViewer1.OpenButton = false;
syl.kpImageViewer1.ImagePath = strFn;
syl.Show();
this.Hide();
}
if (btn == "usageInformation")
{ }
}
}
}
Is flash player ActiveX control installed on your laptop? You have to install it, otherwise there's nothing that can play your .swf file.