I have the following code and cant figure out how to call the function (GetPageCount), which by way i found here. I have tried more than several methods how ever none have worked. Would appreciated some assistance with the line the calls the function and information on what i need to brush up on, i though I had preformed this previously. Thank you in advance.
using System;
using System.Drawing;
using System.Drawing.Printing;
namespace ConsoleApp1
{
class Program
{
public static int GetPageCount(PrintDocument printDocument)
{
int count = 0;
printDocument.PrintController = new PreviewPrintController();
printDocument.PrintPage += (sender, e) => count++;
printDocument.Print();
return count;
}
static void Main(string[] args)
{
var testPrint = GetPageCount (#"c:\temp\test.msg");
Console.WriteLine(testPrint);
}
}
}
You’re trying to pass a string to a method that is expecting a PrintDocument object.
I’d also check out the MSDN documentation on this, available here: PrintDocument
Related
I wrote a small WF program which caculates some condensators and the ohmic law. I now want to tidy up a little bit. I ran across a issue where I use 2 doubles which both got assigned the value 0. I can remove the value from the voltage double. But not the current one. And I can't figure out why. Is there anything I am missing? Error Message is CS0165 Use of unassigned local variable 'current' and occurs in the line where the CalcResistance Method gets called
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Kondensator_Ohmsches_Gesetz_Calc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void calcResistance_Click(object sender, EventArgs e)
{
double voltage;
double current;
bool ok = double.TryParse(textBox1.Text, out voltage) && double.TryParse(textBox2.Text, out current);
if (ok)
{
textBox3.Text = Formulacollection.CalcResistance(voltage, current);
}
else
{
textBox3.Text = "Error Format not found";
}
textBox4.Text = Formulacollection.ConvertMicro(textBox3.Text);
textBox5.Text = Formulacollection.ConvertMilli(textBox3.Text);
textBox6.Text = Formulacollection.ConvertKilo(textBox3.Text);
textBox7.Text = Formulacollection.ConvertMega(textBox3.Text);
}
}
Formulacollection Class works like this:
using System;
using System.Collections.Generic;
using System.Text;
using static System.Math;
using System.Numerics;
using System.Globalization;
namespace Kondensator_Ohmsches_Gesetz_Calc
{
public static class Formulacollection
{
public static string CalcResistance(double voltage, double current)
{
var resistance = voltage / current;
return resistance.ToString();
}
}
The second part won't always be evaluated when you use the && operator. Try to use & instead of it, or set a default value to current when you declare it.
Firstly CS0165 is the error occurs when using the uninitialized variable.
But here the error occurs for the variable current which is initialized correctly. The brief about the error is here
So try the variable initialization globally in the class and then try to compile it.
Then there is a probability of the ok variable holding the value of two TryParse simultaneously, and also replace the && with &.
is it possible to read keyboard inputs without always having my console application focused?
I would like to do something with a button without always going to the console.
Doesn't that somehow work with events? Unfortunately I only found unsightly solutions with Forms.
This solution from #Siarhei Kuchuk didn't help me either:
Global keyboard capture in C# application
The OnKeyPressed event is activated but is not triggered.
Does somebody has any idea?
That's possible. You may google "keyloggers" and find many examples but I'm gonna give you a very rough bare boned one.
But first you have to add a refrence to System.Windows.Forms.dll for this to work
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
[DllImport("User32.dll")]
private static extern short GetAsyncKeyState(System.Int32 vKey);
static void Main(string[] args)
{
while (true)
{
Thread.Sleep(500);
for (int i = 0; i < 255; i++)
{
int state = GetAsyncKeyState(i);
if (state != 0)
{
string pressedKey= ((System.Windows.Forms.Keys)i).ToString();
switch (pressedKey)
{
default:
Console.WriteLine("You have pressed: " + pressedKey);
break;
}
}
}
}
}
}
}
This is the full error:
Error 1 Could not resolve COM reference "f8937e53-d444-4e71-9275-35b64210cc3b" version 1.0. The specified image file did not contain a resource section. (Exception from HRESULT: 0x80070714) UsingAutoIt
Never had it before google didn't find anything with this reference long number and letters.
This is my form1 complete code not that long. Maybe the DllImport make the problem ? But it didn't before. Strange error.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using AutoItX3Lib;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace UsingAutoIt
{
public partial class Form1 : Form
{
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
static AutoItX3Lib.AutoItX3Class au3;
static Thread thread;
static bool threadshouldexecute = true;
static int i = 0;
string processName = "GameCapture";
string existingProcessName = "Game Capture HD";
string processFileName = #"C:\Program Files (x86)\Elgato\GameCapture\GameCapture.exe";
IntPtr windowHandle;
public Form1()
{
InitializeComponent();
au3 = new AutoItX3Lib.AutoItX3Class();
au3.AutoItSetOption("WinTitleMatchMode", 4);
if (au3.WinExists(existingProcessName, "") == 0) // Window not found
{
int processId = au3.Run(processFileName, "", au3.SW_SHOW);
BringToFront(processId);
Thread.Sleep(10000);
au3.MouseClick("LEFT", 358, 913, 1, -1);
}
else
{
Process[] processes = Process.GetProcessesByName(processName);
BringToFront(processes[0].Id);
au3.MouseClick("LEFT", 358, 913, 1, -1);
}
}
public static void BringToFront(int processId)
{
Process process = Process.GetProcessById(processId);
IntPtr handle = process.MainWindowHandle;
if (handle == IntPtr.Zero)
return;
SetForegroundWindow(handle);
}
private void Form1_Load(object sender, EventArgs e)
{
System.Windows.Forms.Timer t1 = new System.Windows.Forms.Timer();
t1.Interval = 50;
t1.Tick += new EventHandler(timer1_Tick);
//t1.Enabled = true;
t1.Enabled = false;
}
public static Point GetMousePosition()
{
var position = System.Windows.Forms.Cursor.Position;
return new Point(position.X, position.Y);
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = string.Format("X={0}, Y={1}", GetMousePosition().X, GetMousePosition().Y);
}
}
}
But to do that I had first to register using regsrv32 only after register it I could add as reference the dll file.
This is normal, Visual Studio stores the guid of the type library in the project file. A type library is a description of the types exported by the COM component. Very similar to metadata in a .NET assembly. Finding the library back from the "f8937e53-d444-4e71-9275-35b64210cc3b" guid in the project file requires Visual Studio to look in the registry, HKCR\TypeLib key. It is not going to be there until after the COM component is registered. Yes, Regsvr32.exe, in general it is better to use the component's installer.
I had to change the property Embed Interop Types to false
That is because you used AutoItX3Lib.AutoItX3Class in your source code. This is a synthetic class that is generated from the type library, it makes COM components that implement multiple interfaces a bit easier to use. Such a synthetic class however cannot be embedded, that's why you had to set the property to false. The simple workaround for that is to omit "Class" from the type name so you only use the interface. Fix:
static AutoItX3Lib.AutoItX3 au3;
....
au3 = new AutoItX3Lib.AutoItX3();
I'm creating an app in winforms c# using vs 2013.
In the app I have a textfile to which I'm saying the time in int format using a custom format from a time select dropdown list.
I then want to display what is in that text file on a selectable listview from where I can remove it from the textfile etc. I'm almost there however at the moment when I try to add the items into the listbox they do seem to add however they do not display correctly.
For example say in my text file there is
22102210
19101610
17182218
10272227
Then that is how it should be displayed in the listview as selectable ready to be deleted.
At the moment it isn't showing correctly, it's showing up as 1.. 2.. 1..
Could someone help me out and point me in the right direction as to why this might be happening? Any help much appreciated. This is my class.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Chronos
{
public partial class Interface : Form
{
private string[] getTimes = System.IO.File.ReadAllLines(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt");
public Interface()
{
InitializeComponent();
}
private void Interface_Load(object sender, EventArgs e)
{
PopulateList();
}
private void PopulateList()
{
int size = getTimes.Length;
lstTime.Items.Clear();
GetTimes();
for (int i = 0; i < size; i++)
{
lstTime.Items.Add(getTimes[i]);
}
}
private void GetTimes()
{
string[] getTimes = System.IO.File.ReadAllLines(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt");
}
private void btnAdd_Click(object sender, EventArgs e)
{
string time = pickerTimeStart.Value.Hour.ToString() + pickerTimeStart.Value.Minute.ToString() + pickerTimeEnd.Value.Hour.ToString() + pickerTimeEnd.Value.Minute.ToString();
System.IO.File.AppendAllText(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt", time + Environment.NewLine);
PopulateList();
MessageBox.Show("Time added", "Ok");
//PopulateList();
}
}
}
As currently written, GetTimes does nothing except read the file:
private void GetTimes()
{
// "string[]" here overrides the outer scope
string[] getTimes = System.IO.File.ReadAllLines(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt");
}
If you change it to this, it becomes more useful:
private string[] GetTimes()
{
return File.ReadAllLines(#"G:\Dropbox\University\Chronos\Application\Chronos\Chronos\AdminAccount\Times.txt");
}
... and then PopulateList can simply become:
lstTime.Items.Clear(); //so you aren't getting a bunch of dupes
lstTime.Items.AddRange(GetTimes().Select(t => new ListViewItem(t)).ToArray());
You can also remove this line because you don't need to keep a copy of the data in the class:
private string[] getTimes = ...
Note: If you decide to keep the data source local and not work solely against the file, much of this would change.
Okay. For the iLab my class and I are doing this week, we are working with GUIs. The second program we must design is a guessing game. The program is supposed to randomly generate a number, 0 through 100, and pass that number on to be used later. Here is the code I already have.
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;
namespace Guessing_game
{
public partial class Form1 : Form
{
int target();
public Form1()
{
InitializeComponent();
Random r = new Random();
int target = r.Next(0, 100);
}
private void btnEvaluate_Click(object sender, EventArgs e)
{
if (txtGuess.Text == target)
{
}
}
}
}
}
Mind you, the "btnEvaluate_Click" area is not done. This is because the variable "Target" that should be accessible by the program is unable to be read later on.
After reading through some of the comments, I was able to tweak the code so I get one more error: "Field 'Guessing_game.Form1.target' is never assigned to, and will always have its default value 0" IF anyone is going to try and replicate this, I can tell you exactly how to write it. The GUI should have a label, a text box, and a button. The button needs to get the value given to "target" so it can check the user's guess against target's value. I'm using Visual Studio 2010, if it helps.
Try this, You need to declare target public
Random r = new Random();
int target = r.Next(0, 100);
public Form1()
{
InitializeComponent();
}
private void btnEvaluate_Click(object sender, EventArgs e)
{
if (txtGuess.Text == target)
{
}
}
You have to put int target outside of the public Form(). Inside your event, change target to target.ToString().
The parentheses {} define a scope. You've declared the target variable within the scope of the constructor (Form1). Therefore, in order to make it accessible throughout the class, you can make it a class level variable. For example
int target;
public Form1()
{
InitializeComponent();
Random r = new Random();
target = r.Next(0, 100);
}
(Although if you plan to use the Random object again, you'd want to make that a class level variable as well). Also, you're trying to compare an int to a string. It should be
if (txtGuess.Text == target.ToString())
{
}
That's because target is local to the constructor and therefore can't be seen anywhere else. Make target a field in Form1 instead. Because this is homework, I'll let you try that out on your own; let us know if you're still stumped.