[英]C# calling function from other class
我正在嘗試在“公共靜態void Main()”中運行“ progr.SetMonitorState(MonitorState.OFF)”,但是在嘗試編譯時出現錯誤:
我只是想制作一個程序,該程序將關閉我的電腦並關閉顯示器(我想檢查它是否會關閉通過HDMI與PC連接的電視)
碼:
using System;
using System.Diagnostics;
using System.Runtime;
using System.Data;
using System.Runtime.InteropServices;
using System.Timers;
using System.Windows.Forms;
namespace progr
{
public class MonitorSht
{
public int SC_MONITORPOWER = 0xF170;
public uint WM_SYSCOMMAND = 0x0112;
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
public enum MonitorState
{
ON = -1,
OFF = 2,
STANDBY = 1
}
public void SetMonitorState(MonitorState state)
{
Form frm = new Form();
SendMessage(frm.Handle, WM_SYSCOMMAND, (IntPtr)SC_MONITORPOWER,(IntPtr)state);
}
}
public class Shut
{
public static void Main()
{
progr.SetMonitorState(MonitorState.OFF);
Console.Write("Jestem jebanym leniem :)\n\n");
int t=0;
for (int i=0;i<7;i++)
{
Console.WriteLine("[{0}] {1} min", i,t);
t=t+30;
}
Console.Write("[7] Anuluj\n");
Console.Write("\n\nZa ile wyłączyć sprzęcior?");
int n = int.Parse(Console.ReadLine());
switch (n)
{
case 0: n=0; break;
case 1: n=1800; break;
case 2: n=3600; break;
case 3: n=5400; break;
case 4: n=7200; break;
case 5: n=9000; break;
case 6: n=10800; break;
}
string sht = "/s /t " + n;
if (n==7) {sht = "/a";}
Console.Write(sht);
var psi = new ProcessStartInfo("shutdown",sht);
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
Process.Start(psi);
Console.ReadLine();
}
}
}
MonitorSht
不是靜態的,因此您需要創建一個實例才能使用其方法。
public static void Main()
{
var monitorSht = new MonitorSht();
monitorSht.SetMonitorState(MonitorSht.MonitorState.OFF);
Console.Write("Jestem jebanym leniem :)\n\n");
/*...*/
}
您還可以通過將枚舉放在類范圍之外(最好放在新文件中)來公開枚舉。
public class MonitorSht
{
/*...*/
}
public enum MonitorState
{
ON = -1,
OFF = 2,
STANDBY = 1
}
然后,您可以編寫:
var monitorSht = new MonitorSht();
monitorSht.SetMonitorState(MonitorState.OFF);
您應該閱讀有關類如何工作的更多信息。
您需要像下面的Main方法那樣從MonitorSht創建實例:
MonitorSht somename = new MonitorSht();
然后通過這樣的實例調用您的方法: somename.SetMonitorState(MonitorState.OFF)
嘗試此操作,因為您是從另一個類調用方法的問題
using [projectName].[classLocation];
例如
using projectX.Models;
然后創建一個對象的實例,例如
SetMonitorState Monitor = new SetMonitorState();
然后要獲取此類中的方法,只需調用Monitor例如
Monitor.ShutDown();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.