我已经这么久了,我找不到解决办法。我想在计算机解锁时更改表单的背景颜色。我正在努力从Program.cs文件中访问表单BackColour属性。
我已经在form.cs中创建了一个方法,我可以从program.cs中引用。但是,我不知道如何从我的方法中更改背景颜色。
这是我的代码。任何想法都会非常感激。
// Program.cs中
namespace Lums_Status_Client
{
static class Program
{
public static Form statusform = new Form1();
public static string status = "available";
private static SessionSwitchEventHandler sseh;
[STAThread]
static void Main()
{
ThreadStart job = new ThreadStart(ThreadJob);
Thread thread = new Thread(job);
thread.Start();
sseh = new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
SystemEvents.SessionSwitch += sseh;
while (true) { }
}
static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
//get the username
string get_userName = Environment.UserName;
Debug.WriteLine(e.Reason);
Form1.colourchanger();
}
static void ThreadJob()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(statusform);
}
}
}
和我的form.cs
namespace Lums_Status_Client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.BackColor = System.Drawing.Color.Green;
System.Drawing.Rectangle workingRectangle =
Screen.PrimaryScreen.WorkingArea;
this.Left = workingRectangle.Width - 120;
}
private void Status_Change(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && Program.status == "available")
{
this.BackColor = System.Drawing.Color.Orange;
Program.status = "Busy";
MessageBox.Show("You status has been updated to " + Program.status);
}
else if (e.Button == MouseButtons.Left && Program.status == "Busy")
{
this.BackColor = System.Drawing.Color.Green;
Program.status = "Available";
MessageBox.Show("You status has been updated to " + Program.status);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
public static void colourchanger()
{
//Debug.WriteLine("This class is working");
this.BackColor = System.Drawing.Color.Aqua;
}
}
}
答案 0 :(得分:1)
你必须引用你已经声明的Form1
实例,并使其成为实例方法,而不是static
:
public void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
//get the username
string get_userName = Environment.UserName;
Debug.WriteLine(e.Reason);
statusform.colourchanger(); //access instance object
}
答案 1 :(得分:0)
假设您只需要一个Form1实例,您可以更改Program.cs以准备好Form1
引用:
using System.Drawing;
//...
//...
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
F1 = new Form1();
Application.Run(F1);
}
static Form1 F1;
public static void ChangeColor(Color newColor)
{
F1.BackColor = newColor;
}
}
现在您可以将ChangeColor方法称为:
Program.ChangeColor(Color.Aqua);