Prevent Pocket PC device from Shutting down application on power off - c#

How can I prevent the pocket PC device from shutting down from my application when the power button pressed? I am using C#.

You could use the Microsoft.WindowsCE.Form.MessageWindows class to intercept the Power Button event. This solution will not be portable, as the hardware key will be different in different machines.
I recommend however that you don't disable power down completely. Have a look at my answer in another question here. You could also use openetcf to easily create power down events handlers and register wake up events. You should implement the application logic based on what you are trying to achieve, for instance wake up every one minute to run a process.

You can try changing the power requirements for the device "BLK1:", which is the blacklight device. Be aware that the behavior may not be the same on all devices and version of the OS or Vendor specific Extensions.
To do this, you can write something like :
[DllImport("coredll")]
private extern static IntPtr SetPowerRequirement(string pvDevice, int deviceState,
int deviceFlags, IntPtr pvSystemState, int stateFlags);
[DllImport("coredll")]
private extern static int ReleasePowerRequirement(IntPtr handle);
and call it this way :
IntPtr handle = SetPowerRequirement("BLK1:", 0 /* D0, Full On */, 1, IntPtr.Zero, 0);
// Do something that requires the device to stay on ...
ReleasePowerRequirement(handle);
But this is generally not a good practice, leaving a device with the backlight on for extended periods might reduce dramatically its autonomy.

Related

How to interrupt Screen-saver under windows 8

I would like know how to interrupt Screen-saver under the Windows 8(Embedded version) or Windows 10, Because a window(C#) of my project only run under the normal status, otherwise it will be error if run under Screen-saver. so I want to interrupt the Screen-saver before this window pop-up.
I have researched some solution and idea that included as below,
a. Move mouse(used the user32's mouse_event api)
b. Send keys(also used the user32's api)
c. Kill screen-saver process.
Both of a & b are ways I have tried them and worked well on the windows 10, but not worked on the Windows 8(Embedded version), so currently I only focus on the c way, about way of c I searched the as below link,
https://support.microsoft.com/en-us/help/140723/how-to-force-a-screen-saver-to-close-once-started-in-windows-nt,-windows-2000,-and-windows-server-2003
https://www.codeproject.com/Articles/17067/Controlling-The-Screen-Saver-With-C
but above links still aren't work on the windows 10 and Windows 8(Embedded version), which expert give me some suggestion? thanks in advance.
Have a look at the unmanaged API functions GetSystemPowerStatus and SetThreadExecutionState. Using a (thread) timer, you can periodically update the status, e.g. from a class property, and inform the system about your requirements. This is useful, if your application may allow or disallow the screensaver, depending on it's operating state.
public class PowerManager : IDisposable
{
[Flags]
public enum ExecutionStateEnum : uint
{
LetTheSystemDecide = 0x00,
SystemRequired = 0x01,
SystemDisplayRequired = 0x02,
UserPresent = 0x04,
Continuous = 0x80000000,
}
[DllImport("kernel32")]
private static extern uint SetThreadExecutionState(ExecutionStateEnum esFlags);
public PowerManager() {}
public Update(ExecutionStateEnum state)
{
SetThreadExecutionState(state);
}
}
Update:
Then call PowerManager.Update(ExecutionStateEnum.SystemDisplayRequired) to disable the screensaver or call PowerManager.Update(ExecutionStateEnum.LetTheSystemDecide) to restore the default system behaviour (allow the screensaver).
If the method is called periodically from a timer callback, adjust the timer interval according to the configured screensaver timeout.

How to prevent Windows from entering idle state?

I am working on a C# application which runs in the background without any Windows control.
I want to notify Windows that my application is still alive to prevent Windows from going into the idle state.
Are there any APIs available to call from my application which notify the Windows OS that my application is still alive?
Thanks in advance.
You've to use SetThreadExecutionState function. Something like this:
public partial class MyWinForm: Window
{
private uint fPreviousExecutionState;
public Window1()
{
InitializeComponent();
// Set new state to prevent system sleep
fPreviousExecutionState = NativeMethods.SetThreadExecutionState(
NativeMethods.ES_CONTINUOUS | NativeMethods.ES_SYSTEM_REQUIRED);
if (fPreviousExecutionState == 0)
{
Console.WriteLine("SetThreadExecutionState failed. Do something here...");
Close();
}
}
protected override void OnClosed(System.EventArgs e)
{
base.OnClosed(e);
// Restore previous state
if (NativeMethods.SetThreadExecutionState(fPreviousExecutionState) == 0)
{
// No way to recover; already exiting
}
}
}
internal static class NativeMethods
{
// Import SetThreadExecutionState Win32 API and necessary flags
[DllImport("kernel32.dll")]
public static extern uint SetThreadExecutionState(uint esFlags);
public const uint ES_CONTINUOUS = 0x80000000;
public const uint ES_SYSTEM_REQUIRED = 0x00000001;
}
You have a couple of options:
Use SetThreadExecutionState, which:
Enables an application to inform the system that it is in use, thereby preventing the system from entering sleep or turning off the display while the application is running.
Where you could use the ES_SYSTEM_REQUIRED flag to
Forces the system to be in the working state by resetting the system idle timer.
Use SendInput to fake keystroke, mouse motion/clicks
Another alternative would be to change your app to be a Windows service.
SetThreadExecutionState example
// Television recording is beginning. Enable away mode and prevent
// the sleep idle time-out.
SetThreadExecutionState(
ES_CONTINUOUS |
ES_SYSTEM_REQUIRED |
ES_AWAYMODE_REQUIRED);
// Wait until recording is complete...
// Clear EXECUTION_STATE flags to disable away mode and allow the system
// to idle to sleep normally.
SetThreadExecutionState(ES_CONTINUOUS);
You can use SetThreadExecutionState described here:
SetThreadExecutionState Function
Since it is a Win32 API function, to use it from C# you'll need to PInvoke it. The steps are described here, including a sample method PreventSleep to temporarily disable sleep mode:
PInvoke.net: setthreadexecutionstate (kernel32)
I don't think there's any way to do this directly in managed code.
A quick search reveals this post from 2 years ago. Basically you'd need to do some interop to call a raw windows API.
Here is SetThreadExecutionState C# implementation

Detecting that the user is away from the PC with .NET

I have a desktop application in which I would like to know two things:
Is the user currently on the PC (more specifically, is he giving any input to the PC), so I can change his state to "away" if needed; and
Is the screensaver running right now, so I can perform more CPU intensive work during that time.
I'm using C#/.NET. How would you suggest to tackle these two tasks?
NOTE: WIN32 invocation will be just as good, as well as any unmanaged code solution.
http://dataerror.blogspot.com/2005/02/detect-windows-idle-time.html
^ Detect Windows Idle Time. :)
The enabler for this feature is the GetLastInputInfo() Win32 API and the LASTINPUTINFO Win32 structure.
Here is the code to detect if a screen saver is running. See this for more details
const int SPI_GETSCREENSAVERRUNNING = 114;
[DllImport( "user32.dll", CharSet = CharSet.Auto )]
private static extern bool SystemParametersInfo(
int uAction, int uParam, ref bool lpvParam,
int flags );
// Returns TRUE if the screen saver is actually running
public static bool GetScreenSaverRunning( )
{
bool isRunning = false;
SystemParametersInfo( SPI_GETSCREENSAVERRUNNING, 0,
ref isRunning, 0 );
return isRunning;
}
Rather than figuring out when to run more intensive work... Consider doing your "intensive work" as early as you can, but at a lower thread priority.
I don't think your questions have an answer in pure C#, unless you poll the mouse position and observe movements... Or something like that.
You could use a global keyboard/mouse hook and just reset your "counter" to 0 when you receive an event from either. When your counter reaches the idle time that you're looking for, perform your background actions.
There is some code here that allows you to easily do the hooking in .NET: http://www.codeproject.com/KB/cs/globalhook.aspx

How to prevent my program to open more than one time (Windows mobile)

How to prevent my program to open more than one time (Windows mobile) ?
and how I can make reset to my program (Windows mobile) ?
thank's
First, to check if your program is already running, create a named object on WinMain (ie. a named Mutex), if the create succeeds, then there are no other instances of your program running, if it fails because it exists, then you know that there is another instance of your program running. In that case use FindWindow (http://msdn.microsoft.com/en-us/library/aa929233.aspx) to search for the window of your application and then just bring it to the foreground via SetForegroundWindow (http://msdn.microsoft.com/en-us/library/aa923858.aspx)
hope this helps...
If you have a .Net CF framework appplication, this how to video walks you through, step by test how to do this. link text
Thanks,
Mike
To prevent running multiple instances of you program you could use a named Mutex.
See this question. The same should apply to Windows Mobile.
I'm not sure what you mean by make reset to your program, but if you mean rebooting the device - you may want to take a look at the KernelIoControl function. Here's more information about how to p/invoke KernelIoControl.
[DllImport("coredll.dll")]
public static extern int KernelIoControl(int dwIoControlCode,
IntPtr lpInBuf,
int nInBufSize,
IntPtr lpOutBuf,
int nOutBufSize,
ref int lpBytesReturned);
//.. and the invocation..
int retBytes = 0;
// Reboot device
KernelIoControl(((0x101 << 16) | (15 << 2)), IntPtr.Zero, 0, IntPtr.Zero, 0, ref retBytes);

.NET Minimize to Tray AND Minimize required resources

I have a WinForms application (I'm using VB) that can be minimized to the system tray. I used the "hackish" methods described in multiple posts utilizing a NotifyIcon and playing with the Form_Resize event.
This all works fine aesthetically, but the resources and memory used are unaffected. I want to be able to minimize resources when minimizing to system tray, just like Visual Studio does. If you are coding in Visual Studio, the memory usage can creep up (depending on project size) to above 500 MB, but when minimizing Visual Studio to the taskbar, the memory drastically decreases to (what I'm assuming) is the minimal amount.
Does anyone have any clue as to how to accomplish this?
Here's a short description of the application, if anyone finds it relevant: I have a windows form with a ListView that contains Work Orders for my IT department. The application has a "listener" that notifies when a new Work order is submitted. So, when the application is running in the system tray, all I really do is compare the count of items in the ListView to a count of rows in a SQL table every couple of minutes.
EDIT: To be more specific, a windows form intrinsically has threads and resources being used by means of the controls, when the form is invisible (in the system tray) these resources are still being used. What can I do to minimize these resources, short of killing all the controls and redrawing them when the form is restored.
Calling MiniMizeMemory() will do a garbage collection, trim the process working size, then compact the process' heap.
public static void MinimizeMemory()
{
GC.Collect(GC.MaxGeneration);
GC.WaitForPendingFinalizers();
SetProcessWorkingSetSize(
Process.GetCurrentProcess().Handle,
(UIntPtr)0xFFFFFFFF,
(UIntPtr)0xFFFFFFFF);
IntPtr heap = GetProcessHeap();
if (HeapLock(heap))
{
try
{
if (HeapCompact(heap, 0) == 0)
{
// error condition ignored
}
}
finally
{
HeapUnlock(heap);
}
}
}
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetProcessWorkingSetSize(
IntPtr process,
UIntPtr minimumWorkingSetSize,
UIntPtr maximumWorkingSetSize);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr GetProcessHeap();
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool HeapLock(IntPtr heap);
[DllImport("kernel32.dll")]
internal static extern uint HeapCompact(IntPtr heap, uint flags);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool HeapUnlock(IntPtr heap);
You're probably looking for this function call: SetProcessWorkingSetSize
If you execute the API call SetProcessWorkingSetSize with -1 as an argument, then Windows will trim the working set immediately.
However, if most of the memory is still being held by resources you haven't released minimizing the working set will do nothing. This combined with the suggestion of forcing Garbage Collection might be your best bet.
From your application description, you might want to also verify how much memory the ListView is consuming as well as the database access objects. I'm also not clear on how you're making those monitoring database calls. You might want to isolate that into a separate object and avoid touching any of the forms while minimized, otherwise the program will be forced to keep the controls loaded and accessible. You could start a separate thread for monitoring, and pass the ListView.Count as a parameter.
Some sources:
.NET Applications and the Working Set
How much memory does my .Net Application use?
To clean up unused memory, use GC.Collect()... though you should read up on why to do it and why its usually a bad idea to use it often.
If you mean other resources, you will need to be more specific.
While this is in C#, look at the source code, it will solve any issues you have:
http://www.codeproject.com/KB/cs/NotifyIconExample.aspx

Categories