PrintDialog shows behind all open windows - c#

I have a simple PrintDialog (code below). My application is a tray application, meaning it has no windows in it and only contains a few simple right click options from the tray icon. Given a file path, the application will open a print dialog and let the user print the item.
I am seeing the following issue...the first time the print works, the dialog pops up to the top, taking precedence over all of my other open programs. After the first, the print dialog is always opened behind everything else that I have opened. For example, I have a web browser open on my screen, the print dialog will open behind that every time after the first print.
PrintDialog pd = new PrintDialog();
if (pd.ShowDialog() == DialogResult.OK)
{
ProcessStartInfo info = new ProcessStartInfo(filename);
info.Arguments = "\"" + pd.PrinterSettings.PrinterName + "\"";
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
info.UseShellExecute = true;
info.Verb = "PrintTo";
try { Process.Start(info); }
catch (Exception e) {
// An exception occured while attempting to print
return false;
}
return true;
}

I was able to find an answer in this post:
Cannot show print dialog on the top of asp.net web control
Leaving the answer here as it took me multiple days to find something that actually worked. Hopefully this can be helpful to someone else.
//initialize a new window form
Form currentForm = new Form();
//show the form
currentForm.Show();
//Activate the form
currentForm.Activate();
//Set its TopMost to true, so it will bring the form to the top
currentForm.TopMost = true;
//Set it to be Focus
currentForm.Focus()
//set the form.visible = false
currentForm.Visible = false;
//start to show the print dialog
printDialog.ShowDialog(currentForm)
//close the new form
currentForm.Close();

Related

How to pass EventHandler to enable button in parent form from a panel?

I have followed this https://rjcodeadvance.com/iu-moderno-temas-multicolor-aleatorio-resaltar-boton-form-activo-winform-c/ to create a Windows Forms user interface for an application I am planning.
I am trying to enable a button in the parent form based on the results of a successful login from a child form.
I have managed to do it, and it works, with this code. When login is successful, the button in the parent form is enabled.
private void OpenChildForm(Form childForm, object btnSender)
{
if (activeForm != null)
activeForm.Close();
ActivateButton(btnSender);
activeForm = childForm;
childForm.TopLevel = false;
childForm.FormBorderStyle = FormBorderStyle.None;
childForm.Dock = DockStyle.Fill;
this.panelDesktopPane.Controls.Add(childForm);
this.panelDesktopPane.Tag = childForm;
childForm.BringToFront();
FormLogin frmlgn = new FormLogin();
frmlgn.DataAvailable += new EventHandler(child_DataAvailable);
frmlgn.Show();
lblTitle.Text = childForm.Text;
btnClose.Visible = true;
btnMaximize.Visible = true;
btnMinimize.Visible = true;
btnClose.BringToFront();
btnMaximize.BringToFront();
btnMinimize.BringToFront();
}
The problem I am facing is that the child form isn't shown inside a panel anymore, which breaks the user interface.
As you can guess, the method performs several modifications to show the form passed as a parameter inside the panel so everything is shown in the same "window".
If I change frmlgn.Show(); to childForm.Show();, I break the EventHandler mechanism, and the button is not enabled, although I keep the user interface as I would like to. When I run the code, as shown above, event handling works but the Login form is shown as a separate window, instead of inside the main window.
I can't figure out how to keep the user interface intact while transferring the data to enable the button.
Everything I try shows some kind of error while compiling. The closest I have been is trying to change frmlgn.DataAvailable += new EventHandler(child_DataAvailable); to childForm.DataAvailable += new EventHandler(child_DataAvailable) but it says *CS1061 'Form' does not contain a definition for 'DataAvailable' and no accessible extension method ... *
Any suggestion?
Thanks.
Update!!
Well I have managed to get it working, although I would like to have a "cleaner" approach, if possible.
I have just created an if loop that executes the modifications to the particular Login form and then shows it in the panel. If the Form to load is different from Login then it executes the code as "is". Thankfully it works, but I don't feel comfortable with this little trick. I am sure there has to be a clean way of doing this.
private void OpenChildForm(Form childForm, object btnSender)
{
if (childForm.Name == "FormLogin")
{
FormLogin frmlgn = new FormLogin();
if (activeForm != null)
activeForm.Close();
ActivateButton(btnSender);
activeForm = childForm;
frmlgn.TopLevel = false;
frmlgn.FormBorderStyle = FormBorderStyle.None;
frmlgn.Dock = DockStyle.Fill;
panelDesktopPane.Controls.Add(frmlgn);
this.panelDesktopPane.Tag = childForm;
frmlgn.BringToFront();
frmlgn.DataAvailable += new EventHandler(child_DataAvailable);
frmlgn.Show();
}
else
{
if (activeForm != null)
activeForm.Close();
ActivateButton(btnSender);
activeForm = childForm;
childForm.TopLevel = false;
childForm.FormBorderStyle = FormBorderStyle.None;
childForm.Dock = DockStyle.Fill;
this.panelDesktopPane.Controls.Add(childForm);
this.panelDesktopPane.Tag = childForm;
childForm.BringToFront();
childForm.Show();
}
lblTitle.Text = childForm.Text;
btnClose.Visible = true;
btnMaximize.Visible = true;
btnMinimize.Visible = true;
btnClose.BringToFront();
btnMaximize.BringToFront();
btnMinimize.BringToFront();
}
Please note that compiling showed a serious exception (not shown in errors tab) that said that Top-level control cannot be added to a control.
I had to change this line this.panelDesktopPane.Controls.Add(childForm); to panelDesktopPane.Controls.Add(frmlgn); and I don't really know what consequences it may have.
Thanks again.

Scanning ProgressIndicatorUI cannot see Cancel button

I have an application which uses Twain driver to scan documents to preview on my application. When I am scanning the documents, it should show a Progress Indicator of the process of scanning the document. And right there, there is a cancel button if I wish to cancel the scan in mid process. However, there the "Cancel" text is not visible but the button is and I would like to make it visible but I am not sure about it.
Below is a screenshot of what I mean:
My code settings:
var settings = new ScanSettings
{
UseDocumentFeeder = ADF,
ShowTwainUI = EnableUI,
ShowProgressIndicatorUI = true,
UseDuplex = EnableDuplex,
Resolution = rs,
Page = pg
};
try
{
TwainHandler.StartScanning(settings);
}
catch (TwainException ex)
{
MessageBox.Show(ex.Message);
//Enabled = true;
//BringToFront();
}
}
I could only figure how to hide or enable the Progress Indicator as a whole but I can't make the cancel text show up.
Does anyone know what do I need to do?

C# OpenFileDialog Thread start but dialog not shown

I am trying to finish my static Prompt class to be able to call it from anywhere. But the problem is couldn't make the dialog show. I am already using [STAThread] and here is my code.
public static string ShowFileDialog()
{
string selectedPath = "";
var t = new Thread((ThreadStart)(() =>
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.RootFolder = System.Environment.SpecialFolder.MyComputer;
fbd.ShowNewFolderButton = true;
if (fbd.ShowDialog() == DialogResult.OK)
{
selectedPath = fbd.SelectedPath;
}
}));
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
return selectedPath;
}
public static class Prompt is my Prompt Class. I am calling it from public partial class Dashboard : Form class
Thank you for your helps.
It surely works just fine when you don't get an exception. But yes, pretty decent odds that you don't see the dialog. Pretty ugly problem, you don't have a taskbar button either. Only way to find it back is by minimizing the other windows on the desktop.
A dialog, any dialog, must have an owner window. You are supposed to pass that owner to the ShowDialog(owner) method overload. If you don't specify one that it goes looking for an owner by itself. Underlying call is GetActiveWindow(). To come up with nothing, the desktop window now becomes the owner. That isn't good enough to ensure that the dialog window is in front.
At a minimum you must create that owner window, you'll now at least have the taskbar button. Like this:
using (var owner = new Form() { Width = 0, Height = 0,
StartPosition = FormStartPosition.CenterScreen,
Text = "Browse for Folder"}) {
owner.Show();
owner.BringToFront();
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.RootFolder = System.Environment.SpecialFolder.MyComputer;
fbd.ShowNewFolderButton = true;
if (fbd.ShowDialog(owner) == DialogResult.OK) {
selectedPath = fbd.SelectedPath;
}
}
Still doesn't guarantee that the dialog is visible, you cannot push a window into the user's face when he's interacting with another window. But at least there's a taskbar button.
I'll very hesitantly show the hack around that, don't use it:
owner.Show();
var pid = System.Diagnostics.Process.GetCurrentProcess().Id;
Microsoft.VisualBasic.Interaction.AppActivate(pid);
The proper way to draw the user's attention and get him to interact with your UI is NotifyIcon.ShowBalloonTip().

C# Query: Command Window does not persist

I have the following code for a button click event. This event should open the command window and execute the application:
private void start_Click(object sender, EventArgs e)
{
if (textBox1.Text == " " || textBox2.Text == " ")
{
MessageBox.Show("Header File or Executable Missing");
}
else
{
Process.Start(textBox1.Text);
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = textBox1.Text;
string filename = textBox1.Text;
int found = filename.LastIndexOf("\\");
int end = filename.Length;
string temp = filename.Substring(found);
startInfo.Arguments = temp + textBox2.Text;
Process.Start(startInfo);
}
}
The problem that I'm facing out here is that when I click the button, the command window does not persist and I don't know whether the command window displays an error message or not because it opens & closes in a flash. Can anybody tell me what is going wrong here and give me a few hints how to go about solving the issue?
If you want to start a new console application from your Windows Forms application you need to either pass in the path to such an application or to cmd.exe + the run command for that application. Make sure the code in your console application halts by asking for a Console.ReadKey(true) or similar.

C# process start focus issue

When I start a new process, it automatically gets the focus. how can I prevent it from getting the focus or instead get back the focus to my application?
here is the code I'm using:
string path = #"c:\temp\myprocess.exe";
ProcessStartInfo info = new ProcessStartInfo(path);
info.WorkingDirectory = path;
Process p = Process.Start(info);
I just need the executed process not to get the focus.
Thank you very much,
Adi Barda
Maybe setting the WindowStyle property to Minimized can help.
If you don't need to show the process at all, try this:
string path = #"c:\temp\myprocess.exe";
ProcessStartInfo info = new ProcessStartInfo(path);
info.WorkingDirectory = path;
info.WindowStyle = ProcessWindowStyle.Hidden;
Or set WindowStyle to ProcessWindowStyle.Minimized if you want it visible but minimized, as Uwe Keim said.
can you do
myForm.Focus();
where myForm is the form on your main application
What i´ve done was to wait a little delay until the other application was succesfully loaded, then focus my application window.
//Test window
const string strCmdText = "/C cd C:\\sqlcipher";
Process.Start("CMD.exe", strCmdText);
//Delay
int liMilliseconds = 50;
Thread.Sleep(liMilliseconds);
//Code to bring window to front
this.WindowState = FormWindowState.Minimized;
this.Show();
this.WindowState = FormWindowState.Normal;

Categories

Resources