c# select Folders or Files in the same method - c#

Okay, so please don't flame me too much, this is my 1st question here, and maybe what I am trying to do is not even possible. Obviously I am not an expert; that's why I am coming to you. :)
I have searched all over here, MSDN, and the rest of the internet (most of which points back here) without any luck. I did see one question asking about using the OpenFileDialog to select a folder instead of a file. I am almost certain that I have seen this in mainstream applications, but the question was marked as being too vague, and that particular caveat was unaddressed in the responses.
I have some text boxes that need file/folder paths. I want to simplify the two methods that handle this, into one. The only difference, is that once selects a file, and the other selects a folder. For simplicity and readability, I'd like to consolidate them.
Is this possible, without literally putting the contents of each code method into a big IF ?
Here are the two methods:
private void FolderBrowser(object sender, EventArgs e)
{
TextBox SenderBox = sender as TextBox;
if (SenderBox.Text != "")//if the text box is not empty
{
//set the selected path to the text box's current contents (incase of accidental entry)
FileBrowserDialog.FileName = SenderBox.Text;
}
if (FileBrowserDialog.ShowDialog() == DialogResult.OK)
{
SenderBox.Text = FileBrowserDialog.FileName;
}
}
private void FileBrowser(object sender, EventArgs e)
{ //basically the same as the folder browser above, but for selecting specific files
TextBox SenderBox = sender as TextBox;
if (SenderBox.Text != "")//if the text box is not empty
{
//set the selected path to the text box's current contents (incase of accidental entry)
FileBrowserDialog.FileName = SenderBox.Text;
}
if (FileBrowserDialog.ShowDialog() == DialogResult.OK)
{
SenderBox.Text = FileBrowserDialog.FileName;
}
}
I have added a Tag to each TextBox, indicating if it needs a file or a folder. I'd like to use the Tag as the condition by which I determine if I should be using a file or folder browser. This is where my ignorance shows; I had envisioned something like this NONWORKING code:
private void browser(object sender, EventArgs e)
{
//cast sender as a textbox
TextBox tBox = (TextBox)sender;
object browser = null;
if (tBox.Tag.ToString().Equals("Folder"))
{
browser = new FolderBrowserDialog();
}
else
{
browser = new OpenFileDialog();
}
if (tBox.Text != "")//if the text box is not empty
{
//set the selected path to the text box's current contents (incase of accidental entry)
browser.FileName = tBox.Text;
}
if (browser.ShowDialog() == DialogResult.OK)
{
tBox.Text = browser.FileName;
}
}
Am I crazy, or is there a way to accomplish what I have in mind? To be clear, I want to know if there is:
An existing Object/Method that would allow for the selection of a file or a folder, or
A way to dynamically re-define an object as a different type of object
Any other way to use 1 Method to dynamically allow for the use of OpenFileDialog or FileBrowserDialog based on some Tag defined on the calling object.

This is the easiest way I've found of solving this problem without relying on third party code, but you'll need to add some sanity checks, in case the user goofs around with the input:
OpenFileDialog ofd = new OpenFileDialog();
ofd.CheckFileExists = false;
string defaultFilename = "Select this folder";
ofd.FileName = defaultFilename;
if (ofd.ShowDialog().Value)
{
// Check if the user picked a file or a directory, for example:
if (!ofd.FileName.Contains(defaultFilename))
{
// File code
}
else // You should probably turn this into an else if instead
{
// Directory code
}
// Alternatively, but still as unsafe
if (File.Exists(ofd.FileName))
{
// File code
}
else
{
// Directory code
}
}
Basically, the "trick" here is to set OpenFileDialog's CheckFileExists to false.

Try using FolderBrowserDialogEx.
See detailed answers here:
How do you configure an OpenFileDialog to select folders?

Both dialogs (FileOpenDialog and FolderBrowserDialog) inherit from CommonDialog; however, this base class has no property to retrieve the result. Moreover, the property is named differently in both dialogs.
You can solve the problem by creating a wrapper. Inheritance is the proper way of re-defining an object as different type.
public abstract class FileFolderDialogBase
{
public abstract bool ShowDialog();
public string Result { get; protected set; }
}
public class FileDialog : FileFolderDialogBase
{
public override bool ShowDialog()
{
var ofd = new OpenFileDialog();
if ofd.ShowDialog() == DialogResult.OK) {
Result = ofd.FileName;
return true;
}
return false;
}
}
public class FolderDialog : FileFolderDialogBase
{
public override bool ShowDialog()
{
var fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
Result = fbd.SelectedPath;
return true;
}
return false;
}
}
Usage:
var dialog = textBox.Tag == "Folder" ? new FolderDialog() : new FileDialog;
if (dialog.ShowDialog()) {
textBox.Text = dialog.Result;
}
You can push it further by creating a factory class
public static class FileFolderDialog
{
public static FileFolderDialogBase Create(string type)
{
swich (type.ToLowerInvariant()) {
case "folder":
case "dir":
case "directory":
return new FolderDialog();
default:
return new FileDialog();
}
}
}
Usage
var dialog = FileFolderDialog.Create(textBox.Tag);
if (dialog.ShowDialog()) {
textBox.Text = dialog.Result;
}

why you not try extending the TextBox Class?
It's easy and reusable and you only need to drag and drop your custom control to the WinForm
class FileTextBox : System.Windows.Form.TextBox{
//===>This enumeration is more readable insted of a string XD
public enum DialogType{
File,Folder
}
//===>This property we will handle what kind of Dialog to show
public DialogType OpenDialogType{
get;
set;
}
//===>This is where Object Oriented Programming a& Design do his magic
public System.Windows.Forms.DialogResult ShowDialog(string Title =""){
//===>This function is where we define what kind of dialog to show
System.Windows.Forms.DialogResult Result = System.Windows.Forms.DialogResult.None ;
object Browser=null;
switch(this.OpenDialogType){
case DialogType.File:
Browser = new OpenFileDialog();
((Browser)OpenFileDialog).Title= Title;
if(this.Text.Trim() !="" && this.Text != null ){
((Browser)OpenFileDialog).FileName = this.Tex;
}
Result = ((Browser)OpenFileDialog).ShowDialog();
break;
case DialogType.Folder:
Browser = new FolderBrowserDialog ();
((Browser)FolderBrowserDialog).Description = Title;
if(this.Text.Trim() !="" && this.Text != null ){
((Browser)FolderBrowserDialog).RootFolder = this.Text;
}
Result = ((Browser)FolderBrowserDialog).ShowDialog();
break;
}
return Result;//===>We return thi dialog result just if we want to do something else
}
}
/*
Create a class and copy/paste this code, I think is going to work because
I didn't compiled then go to ToolBox window find this control and Drag & Drop
to your WinForm and in the property window find OpenDialogType property
and this is where you kind define the behavior of OpenDialog();
I'm currently working in a little project in Vs where I create a custom
UI Control downloaded from my git repository
https://github.com/MrAlex6204/GYMSystem
*/

Related

Visual Studio C# Controls not working (sometimes)

I'm really confused so I'm hoping someone can help me out here. I'm working on a programming assignment for uni but there's one part that's really been bugging me and I can't move on until it is fixed. I have created two classes. The problems in each are shown here:
class Login : Form1
{
Form1 f = new Form1();
public void LoginCorrect()
{
Form1.attempts = 3;
MessageBox.Show("Correct Credentials Entered!");
f.loginScreenVar = false;
f.mainScreenVar = true;
f.ChangeScreen();
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void ChangeScreen()
{
//Login Screen
txtUsername.Visible = loginScreenVar;
txtPassword.Visible = loginScreenVar;
btnLogin.Visible = loginScreenVar;
lblLoginCaption.Visible = loginScreenVar;
lblUsername.Visible = loginScreenVar;
lblPassword.Visible = loginScreenVar;
//Main Screen
lblWelcomeUser.Visible = mainScreenVar;
btnViewDetails.Visible = mainScreenVar;
btnViewAccounts.Visible = mainScreenVar;
btnLogout.Visible = mainScreenVar;
MessageBox.Show(loginScreenVar.ToString());
}
}
I have some controls on screen in my design which consist of text boxes, labels, and buttons, and these are meant to show and hide at diffferent times. I have created some booleans which can be set to true and false which will also set the visibility of these controls to true and false.
My problem is when accessing ChangeScreen() from my Login class, for some reason the controls don't hide when they're meant to. I've literally got a message box in the ChangeScreen() method which outputs the result of 'loginScreenVar' and this is false. Please can someone tell me why my 'Login Screen' controls are NOT hiding even though 'loginScreenVar' = false.
Another thing to note is when calling this code from a button in the Form1 class, it does work. However, due to the brief of my assignment I need to use multiple classes.
I really hope this isn't a bug and someone can help me here because I literally can't move on until this is fixed, thanks!
The issue is that, as noted in the comments, you create a new instance of Form1.
A whole new object, with own states.
Why can't I see this new instance? - well, if you did f.show() THEN you'd see it.
As it stands, you're still looking at the old instance.
So, what you need is a publicly accessible instance of Form1 which your two classes access, without creating a new instance.
OR
you could also work with two different windows. For example:
Form1_loaded(object sender, EventArgs e)
{
LoginWindow lw = new LoginWindow();
var result = lw.ShowDialog();
if(result == DialogResult.Cancel)
{
Application.Quit();
}
}
Let's assume you have a button for login. When clicked, it checks whether password and user name are correct. If not, the incorrect count gets increased by one. If the incorrect count is >= 3, then you just close the LoginWindow. (Default DialogResult is DialogResult.Cancel). The code might look like this:
LoginBtn_Click(object sender, EventArgs e)
{
if(UserNameInput.Text == userName && PasswordInput.Text == password)
{
failedAttempts = 0;
this.DialogResult = DialogResult.OK;
this.Close();
}
else
{
failedAttempts++;
if(failedAttempts >= 3)
{
MessageBox.Show("Wrong password. Shutting down the application...");
this.Close();
}
else
{
MessageBox.Show("Wrong password. " + (3-failedAttempts) + " tries left.");
}
}
}
This way, if login isn't successful, app quits. Otherwise the main screen appears.
Note: This is a basic solution. In a more complex app, you'd want more sophisticated output (not hard-coded strings) and comparisions using VariableName.Equals();
Let's keep it simple (and in the style you've started) for now:
public partial class Form1 : Form //Change the default "form1" "Button1" etc names as soon as possible
{
private bool loginScreenVar = true; //when naming booleans, use "truth test" sounding names like isLoginScreenMode
private bool mainScreenVar = true;
public Form1() //this is a constructor, a method that is always called when a new instance of this object is created
{
InitializeComponent();
//use the constructor to set things up
loginScreenVar = true;
mainScreenVar = false;
ChangeScreen();//make sure loginscreen is showing
}
public void ChangeScreen()
{
//Login Screen
txtUsername.Visible = loginScreenVar;
txtPassword.Visible = loginScreenVar;
btnLogin.Visible = loginScreenVar;
lblLoginCaption.Visible = loginScreenVar;
lblUsername.Visible = loginScreenVar;
lblPassword.Visible = loginScreenVar;
//Main Screen
lblWelcomeUser.Visible = mainScreenVar;
btnViewDetails.Visible = mainScreenVar;
btnViewAccounts.Visible = mainScreenVar;
btnLogout.Visible = mainScreenVar;
MessageBox.Show(loginScreenVar.ToString());
}
//call this method when the login is correct
public void LoginCorrect()
{
loginScreenVar = false;
mainScreenVar = true;
ChangeScreen();
}
//double click your login button in the forms designer to add this click event handler
public void LoginButton_Clicked(object sender, ClickEventArgs e){
if(txtUsername.Text == "user" && txtPassword.Text == "pass"){
LoginCorrect();
} else {
MessageBox.Show("Login incorrect");
}
}
}
Forget the class Login:Form stuff unless you're really trying to explore object instantiation and making your own classes for things. Your Form1 will be on show when your app starts, do all the logic inside it
A better way to change screens in winforms is by creating two separate panels each one contains the desired controls to be shown and hide so that you can switch between them
Code example:
Form1_loaded(object sender, EventArgs e)
{
LogInPanel.Visible=true;
}
private void ConnectBtn_Click(object sender, EventArgs e)
{
// Do your checking here
// IF conditions met
MainPanel.Visible=true;
}
private void DisconnectBtn_Click(object sender, EventArgs e)
{
// Do your checking here
// IF conditions met
LogInPanel.Visible=true;
}
If you want to keep you methadologie make sure your program.cs runs Login class instead of Form1 class

Validate multiple forms without having to have validation code in each form

I am developing an app in C# which has forms that takes simillar inputs from users at different states.
I need to be able to validate them and for that reason I am using errorproviders
The code is working fine but I notice that with my current knowledge if I wanted to validate multiple forms then I will have to keep copy pasting the validation code for similar forms all over in each of them, I am wondering if there is a simpler way of reusing the validation code by having it in a central location that can be accessed by all of the forms instead of having to code it for each of them.
Below is a snippet of the validation code, in C#
//Methods to verify and user inputs
private bool ValidateName()
{
bool bStatus = true;
if (name.Text == string.Empty)
{
errorProvider2.SetError(name, "");
errorProvider1.SetError(name, "Please Enter Name");
bStatus = false;
}
else
{
errorProvider1.SetError(name, "");
errorProvider2.SetError(name, "Good");
bstatus = true;
}
return bStatus;
}
private void name_Validating(object sender, CancelEventArgs e)
{
ValidateName();
}
What I want to be able to do is have the method ValidateName() defined in such a way that I could just call it in the name_Validating() function of forms which has a textbox called name to validate it.
You'll want something along these lines. Not in front of a project so don't have the precise syntax though. It should point you in the right direction though
//Methods to verify and user inputs
private bool ValidateName(string aName)
{
bool bStatus = true;
// You'll need to fill this bit
// cast or instatiate a textbox here, let's call it txt_box_name
//
// cast : if you pass an object that you know is a textbox
//
// instantiate : you can create an instance of a textbox with Activator.CreateInstance
// more on that here: http://msdn.microsoft.com/en-us/library/system.activator.createinstance%28v=vs.110%29.aspx
//
// and then continue as normal with your generic text box field
if (txt_box_name.Text == string.Empty)
{
// do something
}
else
{
// do something else
}
return bStatus;
}
private void name_Validating(object sender, CancelEventArgs e)
{
ValidateName("name");
// or :
//ValidateName("username");
}

How do you access the name of the image in a picturebox in Visual Studio using C#

I have a program which has 16 grid tiles using picturebox but only uses 5 images, the rest of the tiles are just a black image.
I would like to be able to tell which image the 'user' clicks on.
I have a method called image_Click(object sender, EventArgs e)
I have an if statement inside this method that states:
if (peckedSquare.BackColor == Color.Black)
{
System.Diagnostics.Debug.WriteLine("Pecked a black square");
return;
}
This sends a String that lets me know when a black square has been clicked.
Is there an easy way to perhaps say:
//pseudo code:
if (peckedSquare.ImageName == pigeon1.png)
{
System.Diagnostics.Debug.WriteLine("Pecked Pigeon number 1");
}
I have googled my query but I have not found any suitable answers.
//EDIT
I have just re-read my code.
I was assigning each picture to a picturebox square using a randomnumber.
I had this random number as a variable, so I can just use that variable to determine which image was clicked.
ie.
if (randomNumber == 1)
{
System.Diagnostics.Debug.WriteLine("Pecked Pigeon number 1");
}
or better than that
pigeonSelected = randomNumber + 1 //as I am using an array to store the images
System.Diagnostics.Debug.WriteLine("Pecked Pigeon Number {0}", pigeonSelected);
As quick & dirty solution I would use Tag property for that, null for black tiles and file path for the others (and it's always available, even if your image comes from resources), something like this:
if (peckedSquare.Tag == null)
{
Debug.WriteLine("Pecked a black square");
}
else
{
switch (Path.GetFileName(peckedSquare.Tag.ToString()))
{
case "pigeon1.png":
break;
}
}
Of course when you create tiles you have to store file path in Tag:
PictureBox tile = new PictureBox();
tile.Image = Image.FromFile(path); // Or another source, of course
tile.Tag = path;
As alternative you may even use Name property for this, each control is named (primary for designer-code integration) but if you create controls at run-time you can set that value to anything you want (not only valid identifiers). Same usage as above just no need to call ToString().
How to Improve?
Please let me say this solution is not very OOP. Even without a big refactoring we can do little bit better. Note that you can store whatever you want in Tag property. A number, a simple string unrelated to file name or even (maybe better) a class or an enum that represents that image (to delegate action to that object). This is a very raw example:
abstract class Tile {
public abstract void Activate();
}
sealed class EmptyTile : Tile {
public virtual void Activate() {
Debug.WriteLine("Pecked a black square");
}
}
sealed class ImageTile : Tile {
public ImageTile(string content) {
_content = content;
}
public virtual void Activate() {
Debug.WriteLine(_content);
}
private string _content;
}
In this way in your click event handler you can do this:
((Tile)peckedTile.Tag).Activate();
No need to check what's inside or to compare with null. No if and no switch, just don't forget to put proper object (ImageTile or BlackTile) when you create tiles.
Use PictureBox.Load(string) method to load images from file. Then the file path will be stored in the
PictureBox.ImageLocation property:
A call to the Load method will overwrite the ImageLocation property, setting ImageLocation to the URL value specified in the method call.
So you can write for example:
if (peckedSquare.ImageLocation.EndsWith("pigeon1.png"))
{
System.Diagnostics.Debug.WriteLine("Pecked Pigeon number 1");
}
I think you could do something like the following:
private List<PictureBox> pictures = null;
string[] ImageNames = new string[]
{
"images\\test_1.jpg",
"images\\test_2.jpg"
};
private void Form1_Load(object sender, EventArgs e)
{
pictures = new List<PictureBox>();
for (var idx = 0; idx < ImageNames.Length; idx++)
{
pictures.Add(new PictureBox());
pictures[idx].Image = new Bitmap(ImageNames[idx]);
pictures[idx].Click += OnClick;
// you'll want to set the offset and everything so it shows at the right place
Controls.Add(pictures[idx]);
}
}
private void OnClick(object sender, EventArgs eventArgs)
{
// you'll definitely want error handling here
var ImageName = ImageNames[pictures.IndexOf((PictureBox) sender)];
}
You can see that in the click method you will be able to get the image name, which is what you are looking for I believe.
As others have said, you can also use the "Tag" property assuming you weren't already using this for some other purpose. The nice thing about tag is you can probably also edit it through the form designer which allows you to lay things out a little more nicely than the automatic layout I used above. Good luck!
You can do something like this using the Tag property like #Adriano suggested:
public Form1()
{
InitializeComponent();
pictureBox1.Click += pictureBox_Click;
pictureBox2.Click += pictureBox_Click;
pictureBox3.Click += pictureBox_Click;
// ...
pictureBox1.Tag = "picture1.png";
pictureBox2.Tag = "picture2.png";
pictureBox3.Tag = "picture3.png";
}
void pictureBox_Click(object sender, EventArgs e)
{
PictureBox pb = sender as PictureBox;
if (pb.BackColor != Color.Black)
Debug.WriteLine(pb.Tag.ToString());
else
Debug.WriteLine("Black image");
}

open new winform

i have treeview which each node tag contain form name , when i click on node i open the form
my code is as follows
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
NodeClick(Convert.ToString(e.Node.Tag));
}
public void NodeClick(string formName)
{
switch (formName)
{
case "frmPartMaster":
frmPartMaster partMaster = null;
if ((partMaster =
(frmPartMaster)Globale.IsFormAlreadyOpen(typeof(frmPartMaster)))
== null)
{
partMaster = new frmPartMaster();
partMaster.Show(this);
}
else
{
partMaster.Activate();
partMaster.WindowState = FormWindowState.Normal;
partMaster.BringToFront();
}
break;
}
}
this code is working fine but i have 1000's of form , for each for form i have to right case the code.
is it possible if i passed the form it open it open like in single case?
You can create instance of a form class by the call of Activator.CreateInstance
public void OpenOrActivateForm(string formType)
{
var formType = Type.GetType(formType);
var form = Globale.IsFormAlreadyOpen(formType);
if(form == null)
{
form = Activator.CreateInstance(formType);
from.Show(this);
}
else
{
form.Activate();
form.WindowState = FormWindowState.Normal;
form.BringToFront();
}
}
Why don't you just put a reference to a form in the Node's Tag and then use that directly
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
NodeClick(e.Node.Tag as Form);
}
public void NodeClick(Form theForm)
{
if(theForm == null) return;
if(theForm.Visible == false)
{
theForm .Show(this);
}
theForm .Activate();
theForm .WindowState = FormWindowState.Normal;
theForm .BringToFront();
}
You should be able to add the form to the node, the node should have a field, tag i think it is that is of type object. Add your form there then extract it from the tag. That way you will not have to use a case statement but 1 single statement that works for all forms.
Instead of using switch case for every form, you can use Activator.CreateInstance method.
Refer this MSDN Article.
You can store Fully Qualified Name in the tag and use it to instantiate appropriate form.
You could use this approach:
Define a Dictionary of strings and actions like this
Dictionary<string, Action> dic = new Dictionary<string,Action>();
dic.Add("frmPartMaster", OpenPartMaster);
.....
add the appropriate action
private void OpenPartMaster()
{
frmPartMaster partMaster = null;
if ((partMaster =
(frmPartMaster)Globale.IsFormAlreadyOpen(typeof(frmPartMaster)))
== null)
{
partMaster = new frmPartMaster();
partMaster.Show(this);
}
else
{
partMaster.Activate();
partMaster.WindowState = FormWindowState.Normal;
partMaster.BringToFront();
}
}
and when you need to call that form instead of an infinite switch use
dic[formName].Invoke();
in this way you have a centralized point where you add the specific action to execute when a particular form is requested and you keep all the functionality already written.
Of course you need to refactor the switch cases in separate methods.
This approach is interesting if you have different actions (cases) for your form and not a always the same sequence of repeating code.

Making the second and third OpenFileDialog appear above the console in .NET/C#?

I'm writing a console program that can accept 1 to 3 files. I'm using OpenFileDialog three times to accept the files, but the second and third time the file dialog is behind the console window, making it hard to notice. Any way to get it to appear above?
An image of the problem:
The relevant code is:
static bool loadFile(ref List<string> ls)
{
OpenFileDialog f = new OpenFileDialog();
if (f.ShowDialog() == DialogResult.OK)
{
Console.WriteLine("Loaded file {0}", f.FileName);
ls.Add(f.FileName);
return true;
}
else
{
return false;
}
}
[STAThread]
static void Main(string[] args)
{
// sanity check
if (args.Length > 3)
{
Console.WriteLine("Sorry, this program currently supports a maximum of three different reports to analyze at a time.");
return;
}
else if (args.Length == 0)
{
List<string> fL = new List<string>();
for (int k = 0; k < 3; k++)
{
if (!loadFile(ref fL)) break;
}
if (fL.Count == 0)
{
InfoDisplay.HelpMessage();
return;
}
else
{
args = fL.ToArray();
}
}
// main program
...
}
I know this doesn't directly answer the question, but the OpenFileDialog has a property called "MultiSelect" which indicates whether or not the user can select more than one file. Once the user does select the file(s), the property FileNames (string[]) gets populated with all the file names. You can then just do a check like this:
if(dialog.FileNames.Length > 3)
{
//only 3 are allowed
}
I encountered the same problem in a console application.
OpenFileDialog.ShowDialog can be called with a "parent window" handle argument. I create a dummy Form and use that as parent window argument (the dummy form is invisible, since I don't call Show() on it).
The following code works for me:
Form dummyForm = new System.Windows.Forms.Form();
OpenFileDialog myOpenFileDialog1 = new OpenFileDialog();
if (myOpenFileDialog1.ShowDialog(dummyForm) == DialogResult.OK) {
fileName1 = myOpenFileDialog1.FileName;
}
OpenFileDialog myOpenFileDialog2 = new OpenFileDialog();
if (myOpenFileDialog2.ShowDialog(dummyForm) == DialogResult.OK) {
fileName2 = myOpenFileDialog2.FileName;
}
For me, dummy forms and label still didn't solve the problem. CodeProject has a partial solution at http://www.codeproject.com/KB/WPF/MessageBox.aspx
You can then use Process.GetCurrent.Process.MainWindowHandle in the constructor to the class in the article above, then pass the instance to the file dialog, and it seems to work well (for me at least).
Process p = Process.GetCurrentProcess();
WindowWrapper w = new WindowWrapper(p.MainWindowHandle);
OpenFileDialog ofd = new OpenFileDialog();
var ret = ofd.ShowDialog(w);
...
Found a similar post here. Not tested, but give it a shot and let me know.
foreach(Process p in Process.GetProcesses)
{
if(p.MainWindowTitle = <the main UI form caption>)
{
if(IsIconic(p.MainWindowHandle.ToInt32) != 0)
{
ShowWindow(p.MainWindowHandle.ToInt32, &H1);
ShowWindow(f.Handle.ToInt32, &H1);
}
else
{
SetForegroundWindow(p.MainWindowHandle.ToInt32);
SetForegroundWindow(f.Handle.ToInt32);
}
}
}
OpenFileDialog.ShowDialog can be
called with a "parent window" handle
argument. I create a dummy Form and
use that as parent window argument
(the dummy form is invisible, since I
don't call Show() on it).
The Form is a bit heavy-weight, perhaps a label instead, since it just takes a IWin32Window?
OpenFileDialog.ShowDialog(new Label());
It seems to work.
If someone could come up with a reasonable solution to this (now-) resurrected question, that would be great.
Aaron

Categories