I have a form in C# that has some buttons. I want that when the button is pressed, make the text bold.
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 System.Diagnostics;
using System.Net;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// string str = #"C:\windows\system32\notepad.exe";
// string str = #"C:\windows\system32\winamp.exe";
string str = #"C:\priority\bin.95\WINMENU.exe";
Process process = new Process();
process.StartInfo.FileName = str;
process.Start();
}
private void button2_Click(object sender, EventArgs e)
{
// string str = #"C:\windows\system32\notepad.exe";
// string str = #"C:\windows\system32\winamp.exe";
string str = #"C:\Program Files\UltraVNC\vncviewer.exe";
Process process = new Process();
process.StartInfo.FileName = str;
process.Start();
}
private void button3_Click(object sender, EventArgs e)
{
}
private void button3_Click_1(object sender, EventArgs e)
{
// string str = #"C:\windows\system32\notepad.exe";
// string str = #"C:\windows\system32\winamp.exe";
string str = #"C:\Program Files\UltraVNC\vncviewer.exe";
Process process = new Process();
process.StartInfo.FileName = str;
process.Start();
}
private void button4_Click(object sender, EventArgs e)
{
// string str = #"C:\windows\system32\notepad.exe";
// string str = #"C:\windows\system32\winamp.exe";
string str = #"C:\Windows\system32\mstsc.exe";
Process process = new Process();
process.StartInfo.FileName = str;
process.Start();
}
private void button5_Click(object sender, EventArgs e)
{
// string str = #"C:\windows\system32\notepad.exe";
// string str = #"C:\windows\system32\winamp.exe";
string str = #"C:\Program Files\Microsoft Office\Office14\winword.exe";
Process process = new Process();
process.StartInfo.FileName = str;
process.Start();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
}
}
what should I do now ?
Use the Click event for the button, something like this:
private void button_Click(object sender, EventArgs e)
{
Button b = ((Button)sender);
b.Font = new Font(b.Font, FontStyle.Bold);
}
#hyprsleepy - i dont think that your answer can work because the property Button.Font.Bold is read only so you can only read the value to see what it is currently set as.
#asher - where you have these events:
private void button5_Click(object sender, EventArgs e)
{
// string str = #"C:\windows\system32\notepad.exe";
// string str = #"C:\windows\system32\winamp.exe";
string str = #"C:\Program Files\Microsoft Office\Office14\winword.exe";
Process process = new Process();
process.StartInfo.FileName = str;
process.Start();
}
use similar syntax to this:
private void button5_Click(object sender, EventArgs e)
{
// string str = #"C:\windows\system32\notepad.exe";
// string str = #"C:\windows\system32\winamp.exe";
string str = #"C:\Program Files\Microsoft Office\Office14\winword.exe";
Process process = new Process();
process.StartInfo.FileName = str;
process.Start();
Button b = ((Button)sender);
b.Font = new Font(b.Font, FontStyle.Bold);
}
Here is the code:
private void button1_Click(object sender, EventArgs e)
{
button1.Font = new Font(this.Font, FontStyle.Bold);
}
Related
I'm trying to build a GUI for my application. I'm stuck on one problem. I try to use timer "OnTImedEvent" to call my function to update the chart. Unfortunately, MVS gives me a "Cross-thread operation not valid". I've came across some tips, regarding something called delegate but I can't manage to get it working. Since I'm nooby in windowsFormsApp (started today) I'm asking for your help. Here's my code:
using System;
using System.IO.Ports;
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.Timers;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
bool state = false;
private static System.Timers.Timer timer;
public Form1()
{
InitializeComponent();
timer = new System.Timers.Timer(10);
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.WriteLine("a\n");
}
else
MessageBox.Show("Brak połączenia z urządzeniem");
}
private void button4_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
Form2 form2 = new Form2(serialPort1);
form2.Show();
}
else
MessageBox.Show("Brak połączenia z urządzeniem");
}
private void Form1_Load(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
comBoxPort.Items.AddRange(ports);
}
private void btnCon_Click(object sender, EventArgs e)
{
if (state)
{
state = false;
btnCon.ForeColor = Color.Red;
try
{
serialPort1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw;
}
}
else
{
state = true;
btnCon.ForeColor = Color.Green;
try
{
serialPort1.PortName = comBoxPort.Text;
serialPort1.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw;
}
}
}
private void btnRoll_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.WriteLine("s\n");
}
else
MessageBox.Show("Brak połączenia z urządzeniem");
}
private void btnYAW_Click(object sender, EventArgs e)
{
drawChart();
if (serialPort1.IsOpen)
{
serialPort1.WriteLine("d\n");
}
//else
//MessageBox.Show("Brak połączenia z urządzeniem");
}
private void drawChart()
{
chart1.Series["PITCH"].Points.AddY(21);
chart1.Series["ROLL"].Points.AddY(122);
chart1.Series["YAW"].Points.AddY(13);
}
public delegate void drawChartCallback();
private void chart1_Click(object sender, EventArgs e)
{
}
private void OnTimedEvent(Object source, ElapsedEventArgs e)
{
drawChart();
}
}
}
Thanks in advance for your help.
While its not the best way to do it, for a beginner the easist way to avoid the problem is to use the following variable form.CheckForIllegalCrossThreadCalls = false;
I need some help with error..
Error 2 The type 'AForge.Video.NewFrameEventArgs' exists in both 'c:\Users\anton\OneDrive\Документы\Visual Studio 2013\Projects\WindowsFormsApplication4\packages\Accord.Video.3.0.2\lib\net45\Accord.Video.dll' and 'c:\Users\anton\OneDrive\Documents\Visual Studio 2013\Projects\WindowsFormsApplication4\packages\AForge.Video.2.2.5\lib\AForge.Video.dll' C:\Users\anton\onedrive\Documents\visual studio 2013\Projects\WindowsFormsApplication4\WindowsFormsApplication4\Form1.cs 50 42 WindowsFormsApplication4
this is my code:`
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 AForge.Video;
using AForge.Video.DirectShow;
using AForge.Video.FFMPEG;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private VideoCaptureDevice FinalVideo = null;
private VideoCaptureDeviceForm captureDevice;
private Bitmap video;
private VideoFileWriter FileWriter = new VideoFileWriter();
private SaveFileDialog saveAvi;
private FilterInfoCollection webcam;
private VideoCaptureDevice cam;
private void Form1_Load(object sender, EventArgs e)
{
webcam = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo VideoCaptureDevice in webcam)
{
comboBox1.Items.Add(VideoCaptureDevice.Name);
comboBox1.SelectedIndex = 0;
}
pictureBox1.Anchor = (AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Bottom);
comboBox1.Anchor = (AnchorStyles.Bottom);
button1.Anchor = (AnchorStyles.Bottom);
button2.Anchor = (AnchorStyles.Bottom);
button3.Anchor = (AnchorStyles.Bottom);
}
private void button1_Click(object sender, EventArgs e)
{
cam = new VideoCaptureDevice(webcam[comboBox1.SelectedIndex].MonikerString);
cam.NewFrame += new NewFrameEventHandler(cam_NewFrame);
cam.Start();
}
void cam_NewFrame(object sender, NewFrameEventArgs EventArgs)
{
Bitmap bit = (Bitmap)EventArgs.Frame.Clone();
pictureBox1.Image = bit;
}
private void button3_Click(object sender, EventArgs e)
{
if (cam.IsRunning)
{
cam.Stop();
}
}
private void button2_Click(object sender, EventArgs e)
{
saveFileDialog1.InitialDirectory = #"C:\picture";
saveFileDialog1.Filter = "Images|*.png;*.bmp;*.jpg";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image.Save(saveFileDialog1.FileName);
}
}
private void button4_Click(object sender, EventArgs e)
{
saveAvi = new SaveFileDialog();
saveAvi.Filter = "Avi Files (*.avi)|*.avi";
if (saveAvi.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
int h = captureDevice.VideoDevice.VideoResolution.FrameSize.Height;
int w = captureDevice.VideoDevice.VideoResolution.FrameSize.Width;
FileWriter.Open(saveAvi.FileName, w, h, 25, VideoCodec.Default, 5000000);
FileWriter.WriteVideoFrame(video);
//AVIwriter.Open(saveAvi.FileName, w, h);
//FinalVideo = captureDevice.VideoDevice;
//FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
//FinalVideo.Start();
}
}
}
}
public static bool WriteBeamDataToFile(string Filename, List<Part> Parts)
{
// Open a Streamwriter to write data to the specified Filename
using (StreamWriter TeklaDataWriter = new StreamWriter(Filename))
{
// Connect to the Currently Open Tekla Model
Model Model = new Model();
foreach (Part CurrentPart in Parts)
{
if (CurrentPart != null)
{
string Name = CurrentPart.Name;
string Profile = CurrentPart.Profile.ProfileString;
string Material = CurrentPart.Material.MaterialString;
string Finish = CurrentPart.Finish;
TeklaDataWriter.WriteLine(Name + "," + Profile + "," + Material + "," + Finish);
}
}
}
return File.Exists(Filename);
}
Example:
private void button1_Click(object sender, EventArgs e)
{
How to call above method here?
}
private void button1_Click(object sender, EventArgs e) {
private bool isFileExists;
List<Parts> partsList = new List<Parts>();
isFileExists = WriteBeamDataToFile("example.txt",partsList)
if(isFileExists){
//do something..
}
}
Method above is mark as static. That's why you faced some issue.
Static method could be call from Class it' self.
While non static methods could be called from class instance.
See example:
class MyClass {
//static method
public static void Method1() {}
//non static method
public void Method2() {}
}
class MyForm:Form {
...
private void button1_Click(object sender, EventArgs e)
{
//here we call static method of MyClass
MyClass.Method1();
}
//or
private void button1_Click(object sender, EventArgs e)
{
// Here we create an instance of MyClass
var class = new MyClass();
// and call non static Method
class.Method2();
}
}
}
using System.Data.OleDb;
namespace ConnectingToMS_Access1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OleDbDataAdapter da;
DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
da = new OleDbDataAdapter("Select * from Record", "Provider=Microsoft.Ace.oledb.12.0;data source='D:\\mydb.accdb'");
ds = new DataSet();
da.Fill(ds);
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = ds.Tables[0];
}
private void button2_Click(object sender, EventArgs e)
{
DataRow dr = ds.Tables[0].NewRow();
dr[0] = "abc";
dr[1] = "def";
dr[2] = "ghi";
dr[3] = "jkl";
ds.Tables[0].Rows.Add(dr);
}
private void button3_Click(object sender, EventArgs e)
{
OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
da.Update(ds.Tables[0]);
MessageBox.Show("Saved in Database");
}
}
}
You need to explicitly define the named columns in your query.
The problem is that you can't update columns based on column position. It might have been reasonable to expect that calling the Fill method would return both records and column-names, but it probably won't. After all, running that select query will return only data, not schema.
Hi I want to do something like on screen keyboard. I want user to click a button on inactive application and then key press will be sent to active application while keeping active application active. I wrote the code for hover event of the button in inactive application and it is working. But what I want is to do it in click event. It is not working because inactive application becomes active. The code is below for hover event. Thank you.
private void button1_MouseHover(object sender, EventArgs e)
{
SendKeys.Send("{TAB}");
}
Finally I could figure out a way to do it.
Refer the code below.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Timers;
using tmr = System.Timers;
using System.Threading;
namespace KeyPressTest
{
public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern int GetForegroundWindow();
[DllImport("user32")]
private static extern UInt32 GetWindowThreadProcessId(Int32 hWnd, out Int32 lpdwProcessId);
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
tmr.Timer tm = new tmr.Timer();
Int32 hwnd = 0;
private Int32 GetWindowProcessID(Int32 hwnd)
{
Int32 pid = 1;
GetWindowThreadProcessId(hwnd, out pid);
return pid;
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
tm.Elapsed += Timer_Elapsed;
tm.Interval = 100;
tm.Start();
}
private void button1_Click(object sender, EventArgs e)
{
SetForegroundWindow((IntPtr)hwnd);
Thread.Sleep(40);
SendKeys.Send("{TAB}");
}
private void Timer_Elapsed(object sender, System.EventArgs args)
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(delegate
{
if (this.Handle.ToInt32() != GetForegroundWindow())
{
hwnd = GetForegroundWindow();
}
}));
}
else
{
if (this.Handle.ToInt32() != GetForegroundWindow())
{
hwnd = GetForegroundWindow();
}
}
if (hwnd == 0)
{
return;
}
string appProcessName = "";
string appExePath = "";
string appExeName = "";
try
{
appProcessName = Process.GetProcessById(GetWindowProcessID(hwnd)).ProcessName;
appExePath = Process.GetProcessById(GetWindowProcessID(hwnd)).MainModule.FileName;
appExeName = appExePath.Substring(appExePath.LastIndexOf(#"\") + 1);
}
catch (Exception ex)
{
}
if (textBox1.InvokeRequired)
{
textBox1.Invoke(new MethodInvoker(delegate
{
textBox1.Text = appProcessName + " | " + appExePath + " | " + appExeName;
}));
}
else
{
textBox1.Text = appProcessName + " | " + appExePath + " | " + appExeName;
}
}
}
}
I have never done something similar, but here is what I found in this forum:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern int GetForegroundWindow();
[DllImport("user32")]
private static extern UInt32 GetWindowThreadProcessId(Int32 hWnd, out Int32 lpdwProcessId);
private int teller = 0;
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (teller == 1)
{
setTextje();
}
teller++;
}
private Int32 GetWindowProcessID(Int32 hwnd)
{
Int32 pid = 1;
GetWindowThreadProcessId(hwnd, out pid);
return pid;
}
private void setTextje()
{
Int32 hwnd = 0;
hwnd = GetForegroundWindow();
string appProcessName = Process.GetProcessById(GetWindowProcessID(hwnd)).ProcessName;
string appExePath = Process.GetProcessById(GetWindowProcessID(hwnd)).MainModule.FileName;
string appExeName = appExePath.Substring(appExePath.LastIndexOf(#"\") + 1);
textBox1.Text = appProcessName + " | " + appExePath + " | " + appExeName;
}
}
}
It doesn't answer exactly to your question but it will give you a hint. You need to DllImport "User32.dll". After that you can get the id of the foreground window and play with that.
There is also a very interesting article about application switch tracking written in C#