I thought that code is pretty good, bu it isn't. I'm trying to add something text to my notepad, which look like:
string text = "TESTTESTTESTTEST";
[DllImport("user32.dll")]
private static extern int SetForegroundWindow(IntPtr hWnd);
public void EditTxtFile(string text)
{
Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
IntPtr handle = p.MainWindowHandle;
SetForegroundWindow(handle);
SendKeys.SendWait(text);
p.Kill(); //also process doesn't shoutdown
}
}
When i try to debug this function (actually SendKeys), that message is showing up:
Changes are not allowed while code is runnig.
If it's important i try to edit this from web page/application.
The problem is, that Visual Studio catches Focus when it hits the break point, and then SendKeys is send to Visual Studio instead of notepad, and this produces the error.
What you can do ist the following:
Right Click on the Breakpoint and select "When Hit..."
There you can output whatever you want without Notepad losing Focus
Problem was in function which was responsible for opening that notepad (not enough time to start and open him). I've just add wait function for 4s.
To mine, it's about I use a reference value text from the source WinForms's control, call SendKeys' function while the source form is not yet close or hide before (still the active form). This can produce a similar result: SendKeys.Send() or SendKeys.SendWait() does not send a desired text to the target application.
The steps to workaround this:
1. transfer the text value from the active form to a new temporary variation or a Clipboard,
2. close or hide the active form,
3. activate the target application's form,
4. wait a bit to ensure the target application's form to become active 5. and give the temporary text variation or Clipboard to SendKeys. Works.
PS: Please make sure your application has runtime permission equals or more than the target application.
Related
Currently I'm opening files from my C#/WPF application using
System.Diagnostics.Process.Start("C:\ .... ");
Whether the application window is in full screen etc depends on the state the previous instance of the application was in when it was closed (e.g. If it was closed when full screen, it opens a new instance full screen)
What I'm trying to do is open a file in Excel and make it full screen. I looked into command line switches for Excel, seemed fairly limited since I can't modify the excel files by adding Application.DisplayFullScreen = True into a VBA module.
Edit: Was unclear, but I meant to open it in Full Screen mode (no ribbon etc), not maximized.
Edit2: The key sequence would be alt+v,u. Looking for a way to use SendKeys to send the key sequence to the excel window
Looks like you can use SendKeys.
http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.send.aspx
Edit: This code worked for me
Be sure to #include System.Windows.Forms and everything else that's needed.
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
public void Go()
{
Process excel = new Process();
excel.StartInfo.FileName = #"C:\Test.xlsx";
excel.Start();
// Need to wait for excel to start
excel.WaitForInputIdle();
IntPtr p = excel.MainWindowHandle;
ShowWindow(p, 1);
SendKeys.SendWait("%(vu)");
}
See this SO post:
How to open a PDF file by using Foxit/Adobe in full screen mode?
Excel interop might work for you... it's rather nasty to code with but you can do pretty much anything with it that the user can do in excel itself.
This is an overview of how to use it
http://www.dotnetperls.com/excel
This says you can use the property Application.DisplayFullScreen to get it to go full screen
http://msdn.microsoft.com/en-us/library/office/aa168292(v=office.11).aspx
Can we hide window populated due to following code,
IntPtr updatedHandle = new IntPtr();
UInt32 openVal = MsiInteract.MsiOpenPackage("C:\\MSIGet.MSI", out updatedHandle); //get handle for the MSI
I have one C# application that read some information from .MSI file for that i used above code. Which work great for me but one window get populated on MsiOpenPackage function call.As this function is in loop so it is fustrated for me when multiple window gets open.Please provide me any way to hide "preparation to install" window on function call MsiOpenPackage .
To suppress the UI shown when opening a package, you need to call MsiSetInternalUI or, if you wanted to show something else instead, MsiSetExternalUI. However if all you're doing is reading information from the Property table or Summary Information Stream, you can just call MsiOpenDatabase instead of MsiOpenPackage as that will not begin an installation session and thus will not show UI.
Using the quiet installer You can avoid any window opening for user confirmation or dialog.
string installer = _installer;
System.Diagnostics.Process FProcess = new System.Diagnostics.Process();
FProcess.StartInfo.FileName = "MsiExec.exe";
FProcess.StartInfo.Arguments = "/quiet /i " + installer;
FProcess.StartInfo.UseShellExecute = false;
FProcess.Start();
FProcess.WaitForExit();
How can I get the number of times a program has previously run in c# without keeping a file and tallying. Is there a Application class or something in c# to check the count.
Please give a detailed explantion as i know nothing about it.This is A windows console application not windows forms.
You can do that my creating an Entry in the Registry. And another way is by using an Application Settings.
But I prefer Application Settings because it has less task to do.
See HERE: Creating an Application Settings.
Tutorial From Youtube
Recent versions of Windows automatically maintain this information in the registry under HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist.
The data is obfuscated with ROT13, but that's easy to "decrypt". A free utility (with source code) is available and can serve as your starting point.
You could send a message to a database or webservice every time the program starts up (assuming there's a network connection).
You could keep a count on some form of hardware thet's not a standard storage device (therefore not technically being a file).
You could make a registry entry that you keep the count in (if you ignore the fact that the registry entry is, at some level, persisted into a file somewhere).
You could just have a file somewhere that keeps track of the count. Not sure why you're so opposed to this one in the first place....
If you are running a Winforms application, the you can easily use the Application Settings. Right click on your Solution Name --> Properties --> Settings Tab. More info and tutorial here.
Then, every time your program starts, increment this setting and save it.
Ref: Count the number of times the Program has been launched
In my knowledge Windows does not keep this information for you. You would have to tally the value somewhere (file, database, registry setting).
Better way is Application Settings as:
Create setting in app.config and then use it as:
Properties.Settings.Default.FirstUserSetting = "abc";
then, you usually do this in the Closing event handler of the main form. The following statement to Save settings method.
Properties.Settings.Default.Save();
Implementation using Registry:
static string AppRegyPath = "Software\\Cheeso\\ApplicationName";
static string rvn_Runs = "Runs";
private Microsoft.Win32.RegistryKey _appCuKey;
public Microsoft.Win32.RegistryKey AppCuKey
{
get
{
if (_appCuKey == null)
{
_appCuKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(AppRegyPath, true);
if (_appCuKey == null)
_appCuKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(AppRegyPath);
}
return _appCuKey;
}
set { _appCuKey = null; }
}
public int UpdateRunCount()
{
int x = (Int32)AppCuKey.GetValue(rvn_Runs, 0);
x++;
AppCuKey.SetValue(rvn_Runs, x);
return x;
}
If it's a WinForms app, you can hook the Form's OnClosing event to run UpdateCount.
Then Check tutorial to Read, write and delete from registry with C#
I am writing a simple C# program with some outputs (Console.WriteLine("...");). The problem is, each time I run it, I cannot see the program's output in the output window.
The "program output" tag is already checked, and I already redirected all outputs to the intermediate window but to no avail.
How do I enable seeing the program's output?
I don't think the problem lies with my code. I tried running a simple program that just outputs a string and readline "ala hello world" and I am still unable to see any output. The problem is either with me looking for the output in the wrong location or Visual Studio acting out.
The debug.write method also doesn't work.
Using debug.Write, it all works, though it didn't before. Either something bugged out with me before I restarted or I just need to take a break, either way it's all good now. Thanks all for the helpful comments =)
You can use the System.Diagnostics.Debug.Write or System.Runtime.InteropServices method to write messages to the Output Window.
Here are a couple of things to check:
For console.Write/WriteLine, your app must be a console application. (right-click the project in Solution Explorer, choose Properties, and look at the "Output Type" combo in the Application Tab -- should be "Console Application" (note, if you really need a windows application or a class library, don't change this to Console App just to get the Console.WriteLine).
You could use System.Diagnostics.Debug.WriteLine to write to the output window (to show the output window in VS, got to View | Output) Note that these writes will only occur in a build where the DEBUG conditional is defined (by default, debug builds define this, and release builds do not)
You could use System.Diagnostics.Trace.Writeline if you want to be able to write to configurable "listeners" in non-debug builds. (by default, this writes to the Output Window in Visual Studio, just like Debug.Writeline)
Add a Console.Read(); at the end of your program. It'll keep the application from closing, and you can see its output that way.
This is a console application I just dug up that stops after processing but before exiting:
class Program
{
static void Main(string[] args)
{
DummyObjectList dol = new DummyObjectList(2);
dol.Add(new DummyObject("test1", (Decimal)25.36));
dol.Add(new DummyObject("test2", (Decimal)0.698));
XmlSerializer dolxs = new XmlSerializer(typeof(DummyObjectList));
dolxs.Serialize(Console.Out, dol);
Console.WriteLine(string.Empty);
Console.WriteLine(string.Empty);
List<DummyObject> dolist = new List<DummyObject>(2);
dolist.Add(new DummyObject("test1", (Decimal)25.36));
dolist.Add(new DummyObject("test2", (Decimal)0.698));
XmlSerializer dolistxs = new XmlSerializer(typeof(List<DummyObject>));
dolistxs.Serialize(Console.Out, dolist);
Console.Read(); // <--- Right here
}
}
Alternatively, you can simply add a breakpoint on the last line.
Press Ctrl + F5 to run the program instead of F5.
System.Diagnostics.Debug.WriteLine() will work, but you have to be looking in the right place for the output. In Visual Studio 2010, on the menu bar, click Debug -> Windows -> Output. Now, at the bottom of the screen docked next to your error list, there should be an output tab. Click it and double check it's showing output from the debug stream on the dropdown list.
P.S.: I think the output window shows on a fresh install, but I can't remember. If it doesn't, or if you closed it by accident, follow these instructions.
To keep open your windows console and to not use other output methods rather than the standard output stream cout go to Name-of-your-project -> Properties -> Linker -> System.
Once there, select the SubSytem Tab and mark Console (/SUBSYSTEM:CONSOLE). Once you have done this, whenever you want to compile use Ctrl + F5 (Start without debugging) and your console will keep opened. :)
I run into this frequently for some reason, and I can't fathom why this solution hasn't been mentioned:
Click View → Output (or just hold Ctrl and hit W > O)
Console output then appears where your Error List, Locals, and Watch windows are.
Note: I'm using Visual Studio 2015.
Visual Studio is by itself covering the console window, try minimizing Visual Studio window they are drawn over each other.
In Program.cs, between:
static int Main(string[] agrs)
{
and the rest of your code, add:
#if DEBUG
int rtn = Main2(args);
Console.WriteLine("return " + rtn);
Console.WriteLine("ENTER to continue.");
Console.Read();
return rtn;
}
static int Main2(string[] args)
{
#endif
You could create 2 small methods, one that can be called at the beginning of the program, the other at the end. You could also use Console.Read(), so that the program doesn't close after the last write line.
This way you can determine when your functionality gets executed and also when the program exists.
startProgram()
{
Console.WriteLine("-------Program starts--------");
Console.Read();
}
endProgram()
{
Console.WriteLine("-------Program Ends--------");
Console.Read();
}
I have put some Console.WriteLine calls in to test, but they aren't appearing in the output box?
public static ArrayList myDeliveries = new ArrayList();
public mainForm(){
InitializeComponent();
}
private void mainForm_Load(object sender, EventArgs e){
if (!File.Exists("../../MealDeliveries.txt")){
MessageBox.Show("File not found!");
return;
}
using (StreamReader sr = new StreamReader("../../MealDeliveries.txt")){
//first line is delivery name
string strDeliveryName = sr.ReadLine();
Console.WriteLine("Test content");
while (strDeliveryName != null){
//other lines
Delivery d = new Delivery(
strDeliveryName,
sr.ReadLine(),
sr.ReadLine(),
sr.ReadLine(),
sr.ReadLine(),
sr.ReadLine(),
sr.ReadLine()
);
mainForm.myDeliveries.Add(d);
//check for further values
strDeliveryName = sr.ReadLine();
}
}
displayDeliveries();
}
private void displayDeliveries(){
lstDeliveryDetails.Items.Clear();
Console.WriteLine("Test content");
Console.WriteLine(mainForm.myDeliveries.Count);
foreach (Delivery d in mainForm.myDeliveries){
lstDeliveryDetails.Items.Add(d.DeliveryName);
}
}
Can anyone help??
Console outputs to the console window and Winforms applications do not show the console window. You should be able to use System.Diagnostics.Debug.WriteLine to send output to the output window in your IDE.
Edit: In regards to the problem, have you verified your mainForm_Load is actually being called? You could place a breakpoint at the beginning of mainForm_Load to see. If it is not being called, I suspect that mainForm_Load is not hooked up to the Load event.
Also, it is more efficient and generally better to override On{EventName} instead of subscribing to {EventName} from within derived classes (in your case overriding OnLoad instead of Load).
If you intend to use this output in production, then use the Trace class members. This makes the code portable, you can wire up different types of listeners and output to the console window, debug window, log file, or whatever else you like.
If this is just some temporary debugging code that you're using to verify that certain code is being executed or has the correct values, then use the Debug class as Zach suggests.
If you absolutely must use the console, then you can attach a console in the program's Main method.
If you want Console.WriteLine("example text") output to show up in the Debug Output window, temporarily change the Output type of your Application from Console Application to Windows Application.
From menus choose Project + Properties, and navigate to Output type: drop down, change to Windows Application then run your application
Of course you should change it back for building a console application intended to run outside of the IDE.
(tested with Visual Studio 2008 and 2010, expect it should work in latter versions too)
Using Console.WriteLine( "Test" ); is able to write log messages to the Output Window (View Menu --> Output) in Visual Studio for a Windows Forms/WPF project.
However, I encountered a case where it was not working and only System.Diagnostics.Debug.WriteLine( "Test" ); was working. I restarted Visual Studio and Console.WriteLine() started working again. Seems to be a Visual Studio bug.
If you are developing a command line application, you can also use Console.ReadLine() at the end of your code to wait for the 'Enter' keypress before closing the console window so that you can read your output. However, both the Trace and Debug answers posted above are better options.
Try to uncheck the CheckBox “Use Managed Compatibility Mode” in
Tools => Options => Debugging => General
It worked for me.
Try to uncheck the CheckBox “Redirect all Output Window text to the Immediate Window” in
Tools => Options => Debugging => General
I had it checked and everything was written in the Immediate Window and not in the Output Window
When issue happening on Mac VS 2017 (Which I faced).
Go to Project >> "Your Project name" options.
An option window will pop up
Go to RUN >> Default menu option
Tick the "Run on external console" option TRUE and say OK
Run your application code now.
Old Thread, But in VS 2015 Console.WriteLine does not Write to Output Window If "Enable the Visual Studio Hosting Process" does not Checked or its Disabled in Project Properties -> Debug tab