Delay Sleep or Power Off mode to execute a method c# - c#

I am using these system notifications to detect a power off or power on event for windows. Now I am trying to delay power off event and execute one function before that So how is that possible.
[DllImport(#"User32", EntryPoint = "RegisterPowerSettingNotification",
CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr RegisterPowerSettingNotification(
IntPtr hRecipient,
ref Guid PowerSettingGuid,
Int32 Flags);
[DllImport(#"User32", EntryPoint = "UnregisterPowerSettingNotification",
CallingConvention = CallingConvention.StdCall)]
private static extern bool UnregisterPowerSettingNotification(
IntPtr handle);

Related

View a type within a dll to use in a function used by that Dll

I've got a COM interface dll, and some documentation about the methods within the dll, however from what I can tell with the documentation, the method requires a custom struct be passed in as an out parameter, but the documentation doesn't provide any information about the struct itself.
The function I'm calling from c# is as follows:
API
UINT OpenRequest ([out] PHCOMS phComs,
[in] PCHAR pEndPointName,
[in] UINT fBlockingMode,
[in] UINT fOpenMode,
[in] UINT fDataType,
[in] HINSTANCE hInstance)
My issue is that PHCOMS is a type described in the documentation as:
The address of a variable of type HCOMS. The communications handle to be used by the other API calls, is returned in this variable. If an error occurs this will be NULL.
This function starts by allocating a comms handle (hComs), if
available, to the application. This handle is used for creating a new
connection object. The parameters of this function are assigned to the
relevant members. For this object, a pointer instance is created for
connecting to the interface, as well as the PC Headerpched
interface
I've had a look at various dll inspectors and other posts on SO but can't find anything that helps with how I can actually create a struct that's going to be validly accepted by the function.
I am also unsure if I'm misinterpreting what I need to do - is it possible that I just need to pass a standard handle through to the function or something similar? Is the PHComs type a non custom type that I just can't find info on in google?
Right now I'm attempting to call the function through c# using the DLLImport attribute over an extern function which seems to be ok except that the handle I get back is never valid, which I'm blindly (I've never done something like this before) trying to do like this
[DllImport("MyDll.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern uint OpenRequest(ref SafeProcessHandle hComs, string host, uint fBlockingMode, uint fOpenMode, uint fDataType, SafeProcessHandle hInstance);
static void Main(string[] args)
{
IntPtr h = new IntPtr();
var handle = new SafeProcessHandle(h, true);
uint test = 0;
test = OpenRequest(ref handle, "Host01", 0, 0, 0, handle);
handle.Dispose();
}
Any assistance on how to setup my test properly would help too since I'm blindly guessing about the IntPtr and use of whatever Safe*Handle Classes.
Edit
I've changed it to be like this following Hans' comment:
As you said, there are other methods that use that handle, for example the ConnectRequest added below.
Any suggestion as to what the HInstance parameter refers to? I doubt it's correct that I'm just passing the same handle/IntPtr in again?
The documentation says:
hInstance HINSTANCE Windows programs must pass their instance handle.
[DllImport("MyDll.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern uint OpenRequest(out IntPtr hComs, string host, uint fBlockingMode, uint fOpenMode, uint fDataType, IntPtr hInstance);
[DllImport("MyDll.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern uint ConnectRequest(IntPtr hComs, uint cTimeOut);
static void Main(string[] args)
{
IntPtr hComs = new IntPtr();
uint test_OpenRequest = 0;
test_OpenRequest = OpenRequest(out hComs, "Host01", 0, 0, 0, hComs);
}
Edit 2
[DllImport("WinCom32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
public static extern uint OpenRequest(out IntPtr hComs, string host, uint fBlockingMode, uint fOpenMode, uint fDataType, IntPtr hInstance);
static void Main(string[] args)
{
IntPtr hComs = new IntPtr();
uint test_Request = 0;
string hostName = ConfigurationManager.AppSettings["HostName"];
IntPtr hInstance = Marshal.GetHINSTANCE(Assembly.GetEntryAssembly().GetModules()[0]);
test_Request = OpenRequest(out hComs, hostName, 0, 0, 1, hInstance);
Console.WriteLine("Request response value: " + test_Request.ToString());
}
There's a test application I can run that shows that this is supposed to work because it's able to connect to the host, so I've got to be doing something wrong.

Repeat FindWindow function everytime the window appears/opens

The title says it all, I have this code:
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
const UInt32 WM_CLOSE = 0x0010;
and here's what I added to Form1_Load:
IntPtr windowPtr = FindWindowByCaption(IntPtr.Zero, "Untitled - Notepad");
if (windowPtr == IntPtr.Zero)
{
MessageBox.Show("Window not found");
return;
}
SendMessage(windowPtr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
so I added the code above to the Form1_Load function, and it actually works, it closes notepad when I open my program, but my question is, how to make the function repeat, like close notepad whenever it opens and not only on Form1_Load ?
You have to enumerate the windows yourself: EnumWindows and in the return procedure check if the title is the same as what you want (hardcoding 'Untitled' might not be the best way by the way). Alternatively traverse the window graph yourself with GetWindow, starting at the first desktop child and iterate the siblings from there.
Also you don't need the IntPtr version of FindWindow, you can pass null as a string parameter and it accomplishes the same.

C# console application lose focus

I have about 15 different console apps on my local PC and they are running with different time periods as scheduled tasks.
Since I am using this computer as personal usage (such as surfing on YouTube or Watching Movies)
They are jumping on my screen but I have to always minimize them manually.
My goal is, I want them to first appear (which is already doing) and lose automatically focus after a couple of seconds.
Is it possible with console apps on Windows?
If you want to minimize console window, you can use WinApi
const Int32 SW_MINIMIZE = 6;
[DllImport("Kernel32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern IntPtr GetConsoleWindow();
[DllImport("User32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ShowWindow([In] IntPtr hWnd, [In] Int32 nCmdShow);
private static void MinimizeConsoleWindow()
{
IntPtr hWndConsole = GetConsoleWindow();
ShowWindow(hWndConsole, SW_MINIMIZE);
}
Usage:
static void Main(string[] args)
{
Console.WriteLine("Starting foo...");
Thread.Sleep(1000); // hold console for a second on the screen
MinimizeConsoleWindow();
Console.ReadKey();
}

Using kernel32 CreateThread/TerminateThread inside Azure Worker Role

I have this code that I need to use, but what holds me back is that here it says that TerminateThread Applies to: desktop apps only.
I wonder if I can use this code inside azure Worker role, specifically inside waiishost.exe process that I use to run the Worker thread in?
[DllImport("Library.dll")]
public static extern void InfiniteLoop();
[DllImport("kernel32")]
private static extern int CreateThread(
IntPtr lpThreadAttributes,
UInt32 dwStackSize,
IntPtr lpStartAddress,
IntPtr param,
UInt32 dwCreationFlags,
UInt32 lpThreadId
);
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern int TerminateThread(int hThread);
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetLastError();
private delegate int InvokeInfiniteLoop(IntPtr args);
static void Main(string[] args)
{
InvokeInfiniteLoop invokeInfiniteLoop = (args1) =>
{
InfiniteLoop();
return 0;
};
IntPtr infiniteLoopPtr = Marshal.GetFunctionPointerForDelegate(invokeInfiniteLoop);
int handle = CreateThread(IntPtr.Zero, 0, infiniteLoopPtr, IntPtr.Zero, 0, 0);
Thread.Sleep(TimeSpan.FromSeconds(5));
int terminated = TerminateThread(handle);
Console.WriteLine(terminated);
}
EDIT:
After further research looks like(as I suspected from the beginning) that this workaround is completely wrong. Creating and Terminating the unmanaged code will leak the stack. I will have to create a separate executable that will be terminated by Process.Kill();
The "Applies to: desktop apps only" refers to the difference between Windows 8 Desktop application and Windows 8 Metro applications.

Need to use win32 api to copy files in c# - how do I do this?

I'm trying to copy some files around, and occasionally the lengths of the names exceeds the length that the System.IO.File.Copy method can accept (260 chars according to the exception that is getting thrown)
According to the research I've done, I should be able to use the win32 api's file methods in conjunction with \?\ prepended to paths to get a 32,000 character limit, but I'm not sure witch methods I need to import.
Can someone help me with this? I'm looking for something like (obviously a different function, but you get the idea):
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern SafeFileHandle CreateFileW(string lpFileName, uint dwDesiredAccess,
uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
uint dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll",
CharSet = CharSet.Unicode,
CallingConvention = CallingConvention.StdCall,
SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CopyFile(
[MarshalAs(UnmanagedType.LPWStr)] string lpExistingFileName,
[MarshalAs(UnmanagedType.LPWStr)] string lpNewFileName,
[MarshalAs(UnmanagedType.Bool)] bool bFailIfExists);
http://www.pinvoke.net/default.aspx/kernel32/CopyFile.html
Try using CopyFile.
For PInvoke syntax, you can check pinvoke.net.

Categories