I would like help to create a Windows service that can listen for Multi-touch event occurances, intercept them and then just do something with them (not important).
I also need to know how to send Windows Messages to this service and the code to be able to receive those messages from within the service.
Anyone have any idea's at all please?
I've been cutting code for 15 years but have never written a Windows Service before and use a little help to get on my way :(
By definition, Windows Services are not supposed to be user-interactive, therefore, if you want to get the multi-touch data, you will have to hook directly into the operating system input messages using a WM_TOUCH windows hook and interpreting that data yourself.
For those interested, I decided to go down the route of a normal Windows Form application, and when the time comes to put it live the for will be invisible so will run in the 'background' when the other application I need it to communicate with starts.
I managed to get WndProc(ref Message m) working and messages are being received by my app and its doing what it needs to do according to the instructions it's sent.
For example, the visible App has a GUI Slider for volume control. When the slider is moved the value of that slider is sent to my 'background' app via a Windows Message, and the 'background' App does the necessaries to change the Volume level of the device/PC, and when the volume level is requested, a Postback Message is sent to the requesting App to tell it what the Volume level is currently set at.
Some sample code below:-
public const int UI_VOLUME_SET = 1101;
public const int UI_VOLUME_GET = 1100;
public const int UI_VOLUME_SET_MUTE_STATUS = 1102;
public const int UI_BRIGHT_GET = 1201;
public const int UI_BRIGHT_SET = 1202;
public const int UI_TERMINATE = 9999;
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]Protected override void WndProc(ref Message m)
{
int _exoUI = MessageHelper.FindWindow(null, "MY UI");
EXOxtenderLibrary.VolumeControl _vol;
switch (m.Msg)
{
case UI_TERMINATE:
this.Close();
break;
case UI_BRIGHT_GET:
//ADD CODE HERE
break;
//case UI_BRIGHT_SET:
// //ADD CODE HERE
// break;
case UI_VOLUME_GET:
_vol = new EXOxtenderLibrary.VolumeControl();
MessageHelper.PostMessage(_exoUI, 32773, _vol.GetVolume(), _vol.isMute);
_vol = null;
break;
case UI_VOLUME_SET:
_vol = new EXOxtenderLibrary.VolumeControl();
_vol.SetVolume(m.WParam.ToInt32());
MessageHelper.PostMessage(_exoUI, 32773, _vol.GetVolume(), _vol.isMute);
_vol = null;
break;
case UI_VOLUME_SET_MUTE_STATUS:
_vol = new EXOxtenderLibrary.VolumeControl();
if (m.WParam == new IntPtr(1))
{ _vol.Mute = true; }
else
{ _vol.Mute = false; }
MessageHelper.PostMessage(_exoUI, 32773, _vol.GetVolume(), _vol.isMute);
_vol = null;
break;
}
base.WndProc(ref m);
}
Related
When you close the app by swiping it in recent apps, it will cancel any services and terminate most aspects of the app gracefully. However, if there are any notifications that were SetOngoing(true), then these will remain if the app suddenly is closed, and there aren't any services that listen for the app's termination.
What is the right way to deal with this problem?
Recently, I coded a music player, and I arranged it such that in the OnStop for my activities, the notification is canceled (and so is the thread updating the progress bar within it). Then, OnResume, I trigger the notification again.
If they "recent apps swipe" it away, or click away, the notification goes away now, as long as the music isn't playing. So to get rid of the notification, you have to pause it, and then swipe away. Otherwise, there is a leak memory if the app is closed by swipe, where the notification remains open and is buggy afterwards if the app is reopened, and the app crashes if you click the notification (though maybe that's because I can't figure out how to get started with saved state bundles). Likewise, there is a problem if you let the app close the notification every OnStop, as then it will be closed as the user does other things with their phone, even though the music is playing (which sort of defeats the point of it right?)
Are there other better ways to handle this? Who has a good saved state bundle if that is indeed relevant to my issue?
Thanks for the discussion
You can cancel the notification when android App is closed by swipe with the following code:
[Service]
public class ForegroundServiceDemo : Service
{
public override void OnTaskRemoved(Intent rootIntent)
{
//this.StopSelf();
//this.StopForeground(StopForegroundFlags.Remove);
this.StopService(new Intent(this,typeof(ForegroundServiceDemo)));
base.OnTaskRemoved(rootIntent);
}
}
By overriding the OnTaskRemoved method of the service, the system will call this method when user closes the app by swipe. And each of the three lines code can cancel the notification and stop the service when the app is closed by swipe.
I found this, finally, after trying every search terms imaginable, and wow there is a whole section on this. I do not have it working yet, but I can report back with code when I do. Here is the solution: https://developer.android.com/guide/topics/media-apps/media-apps-overview
Seems you have to implement the media player service as a specific kind of service that registers to the notification. I am in the process of refactoring the heart of my code, which perhaps should be terrifying, but feels more like the final algorithm on a Rubix's cube... I will report back in like 10 work hours with some working code (I hope).
Thanks to everyone contributing on this discussion!
OK, so, after much dabbling and dozens of work hours... I have found the best way to handle this issue is to create a MediaBrowserService with a MediaSession. In the notification creation code, it is very particular about how you start that notification (which has to be in the Foreground and bound to the MediaSession). Once this is done, the notification will stay open, even if you close the app, and clicking it will always bring you back to the activity bound to the service (see the supplied code below). Then, you just have a button on the notification to close itself and the app. Voila, a notification that does NOT remain open if the app is closed from the recent apps, etc.
public static void CancelNotificationBreadCrumb()
{
if (cts != null)
{
cts.Cancel();
Thread.Sleep(250);
// Cancellation should have happened, so call Dispose
cts.Dispose();
MyLogger.Debug("MyMediaPlayer: CloseEntireApp: Notification should have been disposed.");
}
}
public static void NotificationNowPlayingBreadCrumb()
{
try
{
Intent intent = MenuManager.GetGoToNowPlayingIntent(context, GetCurrentlyPlaying());
manager = (NotificationManager)context.GetSystemService(NotificationService);
PendingIntent pendingIntent = PendingIntent.GetActivity(context, 1, intent, PendingIntentFlags.Immutable);
NotificationChannel notificationChannel = new NotificationChannel(ChannelId, ChannelId, NotificationImportance.Low);
notificationChannel.EnableLights(false);
notificationChannel.EnableVibration(false);
notificationChannel.SetSound(null, null);
//notificationChannel.SetVibrationPattern(new long[] { 10, 20 });
manager.CreateNotificationChannel(notificationChannel);
Notification notification = NowPlayingAdapter.InflateNotification(context, currentFile, ChannelId, pendingIntent);
service.StartForeground(MY_MEDIA_NOTIFICATION_ID, notification);
manager.Notify(MY_MEDIA_NOTIFICATION_ID, notification);
// Then trigger the thread to update the real-time features
if (cts == null || cts.IsCancellationRequested)
cts = new CancellationTokenSource();
ThreadPool.QueueUserWorkItem(new WaitCallback(RunInBackground), cts.Token);
} catch(Exception e)
{
string message = "MyMediaPlayer: NotificationNowPlayingBreadCrumb: Could not create now playing breadcrumb notification; message: " + e.Message;
MyLogger.Error(message);
}
}
public static void CloseEntireApp()
{
MyLogger.Trace("MyMediaPlayer: Entering CloseEntireApp...");
if (player != null)
player.Release();
CancelNotificationBreadCrumb();
MediaReceiver.Dispose();
MediaSession.Dispose();
MyLogger.Trace("MyMediaPlayer: CloseEntireApp is Killing App. Good bye!");
service.StopSelf();
Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
}
Here is the OnCreate method for my service:
public class MyMediaPlayer : MediaBrowserServiceCompat
{
private static MediaPlayer? player;
private static MusicAppFile? currentFile;
private static List<MusicAppFile>? allFilesInCurrentContext;
private static Context? context;
private static List<int> recentIndexes = new List<int>();
private static int maxRecentIndexes = 30;
private static bool shuffleMode = false;
private static ViewGroup? Parent;
private static NotificationManager? manager;
private static CancellationTokenSource? cts;
public static MediaButtonReceiver? MediaReceiver;
public static MediaSessionCompat? MediaSession;
private static PlaybackStateCompat.Builder stateBuilder;
private static MediaBrowserServiceCompat service;
public IBinder Binder { get; private set; }
public const string ActionPlay = "com.xamarin.action.PLAY";
public const string ActionPause = "com.xamarin.action.PAUSE";
public const string ActionNext = "com.xamarin.action.NEXT";
public const string ActionStop = "com.xamarin.action.STOP";
public const string ActionBack = "com.xamarin.action.BACK";
public const string ActionCloseApp = "com.xamarin.action.CLOSEAPP";
public static string ChannelId = "NowPlayingNote";
public static string MY_MEDIA_ROOT_ID = "media_root_id";
public static int MY_MEDIA_NOTIFICATION_ID = 1111111;
public static string MY_MEDIA_TAG = "media_tag";
public override void OnCreate()
{
base.OnCreate();
// Create a MediaSessionCompat
MediaSession = new MediaSessionCompat(context, MY_MEDIA_TAG);
// Enable callbacks from MediaButtons and TransportControls
MediaSession.SetFlags(
MediaSessionCompat.FlagHandlesMediaButtons |
MediaSessionCompat.FlagHandlesTransportControls);
// Set an initial PlaybackState with ACTION_PLAY, so media buttons can start the player
stateBuilder = new PlaybackStateCompat.Builder()
.SetActions(
PlaybackStateCompat.ActionPlay |
PlaybackStateCompat.ActionPlayPause |
PlaybackStateCompat.ActionSkipToNext |
PlaybackStateCompat.ActionSkipToPrevious |
PlaybackStateCompat.ActionStop);
MediaSession.SetPlaybackState(stateBuilder.Build());
// MySessionCallback() don't do this. C# isn't as good at doing callbacks because you can't define them inline
// MediaSession.SetCallback(new MediaSessionCallback(this));
service = this;
// Set the session's token so that client activities can communicate with it.
SessionToken = MediaSession.SessionToken;
}
...
I create this service when they click to select a file in one of the menu activities (so in a method called by a method called by an OnClick delegate):
if (musicMenu != null)
{
bool stillPlayingSameFile = MyMediaPlayer.UpdateCurrentContext(c, musicMenu, mf);
if (cts == null)
{
// Start the service and tell it to call play
InitiateMediaBrowserService(c);
} else
{
MyMediaPlayer.Play(stillPlayingSameFile);
}
}
GoToNowPlaying(c, mf);
and the inner service there:
public static void InitiateMediaBrowserService(Context c)
{
// Start the service and tell it to call play
Intent intent = new Intent(c, typeof(MyMediaPlayer));
intent.SetAction(MyMediaPlayer.ActionPlay);
cts = new CancellationTokenSource();
Platform.AppContext.StartForegroundService(intent);
}
Ok, so now the play service, which is triggered from the action play intent here, and makes the call to start the notification, which is where the StartForeground call is made (see the first snippet at the top):
public static void Play(bool stillPlayingSameFile)
{
// If the player has not been created before, or it is a new track, then it needs to be recreated
if (player == null || !stillPlayingSameFile)
{
// If we're here to recreate the player, destroy the old one in memory first
if (player != null)
player.Release();
// Then add the new player
if (currentFile != null)
{
Uri uri = Android.Net.Uri.Parse(currentFile.FilePath);
MediaPlayer media = MediaPlayer.Create(context, uri);
media.Completion += OnCompletion;
if (MediaReceiver == null)
MediaReceiver = new MediaButtonReceiver(context);
media.RoutingChanged += MediaReceiver.OnRoutingChanged;
player = media;
player.SetWakeMode(context, WakeLockFlags.Partial);
}
// Finally, add this file to the list of those recently played
int indexToPlay = allFilesInCurrentContext.IndexOf(currentFile);
if (indexToPlay >= 0)
recentIndexes.Add(indexToPlay);
if (recentIndexes.Count > maxRecentIndexes)
recentIndexes.RemoveAt(0);
}
// Finally start the player, which picks up where left off if this is the same track
if (!IsPlaying() || !stillPlayingSameFile)
{
player.Start();
NotificationNowPlayingBreadCrumb();
}
}
The MediaButtonReceiver and MediaBroadcastReceiver classes are pretty straightforward, so comment if you really need that code. One other thing to note is that you do have to bind the service to an activity (I suggest the now playing activity):
protected override void OnStart()
{
base.OnStart();
//Config.ConfigureBluetoothIntegration(this); TODO remove this
Intent serviceToStart = new Intent(this, typeof(MyMediaPlayer));
//serviceToStart.SetAction(MyMediaPlayer.ActionPlay);
BindService(serviceToStart, new ServiceConnection(this), Bind.AutoCreate);
}
So there, now there IS an example of how to use the MediaSession and MediaSessionCompat and MediaBrowserServiceCompat online somewhere. Even ChatGPT could not find an example or tell me how to do this. You are welcome, internet. Enjoy your coding!
My goal is to disable all DoubleClick() events in my application. Just simply unsubscribing from those events is not possbile, because those are external custom controls. So I am aiming for disabling either the DoubleClick() for those controls or my whole application, it doesn't really matter.
What I am trying to do is to intervene once the window gets a WindowsMessage WM and the ID number Message.Msg is the code of e.g. a Button.Click() event.
private const int WM_COMMAND = // ???
if (m.Msg == WM_COMMAND)
...
But no matter which WindowsMessage notification code I use, I don't get the correct one which gets fired once a control gets clicked. But I was abel to intervene on a DoubeClick() on the Form.
private const int WM_NCLBUTTONDBLCLK = 0x00A3;
private const int WM_LBUTTONDBLCLK = 0x0203;
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_NCLBUTTONDBLCLK || m.Msg == WM_LBUTTONDBLCLK)
{
m.Result = IntPtr.Zero;
return;
}
base.WndProc(ref m);
}
This works totally fine and disabels a DoubleClick on the client area and non client area of the Form. But in which area do I locate when I am hovering a control? Because those WindowsMessages referred to either the client area and non client area dont' get fired when I am on a control.
Sent when the user clicks a button.
The parent window of the button receives this notification code through the WM_COMMAND message.
MSDN doc about a button click notifaction message
The WM_COMMAND message has this notfication code:
private const int WM_COMMAND = 0x0111;
So when I try to react to this message being sent I can't, because this message doesn't get fired.
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_COMMAND)
MessageBox.Show("foo"); // nothing happens
base.WndProc(ref m);
}
What do I miss or missunderstand about this WindowsMessage?
Since no one posted an answer yet and I found a well working solution here is my attempt to disable all DoubleClick()s or just for one/a few desired Control/s.
The problem is that WndProc() doesn't filter or respond to all WMs that are being sent. Therefore the WM for a default doubleClick on the non client area 0x0203 can't get detected. So I went deeper to already filter the WMs before they reach WndProc(). One way is to use a MessageFilter that is being assigned to my Application.
private MessageFilter msgFilter = new MessageFilter();
Application.AddMessageFilter(msgFilter);
The method Param is an object of my own class MessageFilter, which needs to implement the IMessageFilter Interface in order to use it's PreFilterMessage(). This method gets invoked for each single WM that gets send to your application.
class MessageFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == 0x0203)
{
m.Result = IntPtr.Zero;
return true;
}
else
return false;
}
}
So basically once there is a WM with the desired Message.Msg ID, I set the Result to zero so the DoubleClick() is completely disabled for the whole application.
Later on it turned out it would be better to disable the DoubleClick() only from one Control. Since every Control in Windows has a unique Handle HWnd, which is part of the Message, I can use it to scan if the certain Message aims to my specific single Control.
When you create your Control either subscribe in the .Designer.cs to the event:
this.yourControl.HandleCreated += new System.EventHandler(this.yourControl_HandleCreated);
Or if it's a custom Control subscribe to the event after it's creation. In the event you assign the value of the created Handle to any instance your MessageFilter has access to, like a Property in this class.
private void yourControl_HandleCreated(object sender, EventArgs e)
{
msgFilter.OwnHandle = yourControl.Handle;
}
After that simply add a second condition to the if statement:
if (m.Msg == 0x0203 && OwnHandle == m.HWnd)
...
I would like to use this menu through C# or F# in Win7. I even couldn't find how to call it.
In Introducing The Taskbar APIs on the MSDN magazine, it describes about how to use the Thumbnail Toolbars.
The managed equivalent does not currently appear in the Windows API
Code Pack, but it is planned to appear in a future release. In the
meantime, you can use the Windows 7 taskbar Interop Sample Library. It
contains the ThumbButtonManager class with the corresponding
CreateThumbButton and AddThumbButtons methods for controlling the
thumbnail toolbar, and also the ThumbButton class for modifying the
thumbnail button state at runtime. To receive notifications, you
register for the ThumbButton.Clicked event and override your window
procedure to dispatch the messages to the ThumbButtonManager class,
which does the dispatching magic for you. (For more details, see the
blog article Windows 7 Taskbar: Thumbnail Toolbars.)
ITaskbarList3* ptl;//Created earlier //In your window procedure:
switch (msg) {
case g_wmTBC://TaskbarButtonCreated
THUMBBUTTON buttons[2]; buttons[0].dwMask = THB_ICON|THB_TOOLTIP|THB_FLAGS; buttons[0].iId = 0;
buttons[0].hIcon = GetIconForButton(0); wcscpy(buttons[0].szTip, L"Tooltip 1"); buttons[0].dwFlags = THBF_ENABLED;
buttons[1].dwMask = THB_ICON|THB_TOOLTIP|THB_FLAGS;
buttons[1].iId = 1; buttons[1].hIcon = GetIconForButton(1);
wcscpy(buttons[0].szTip, L"Tooltip 2"); buttons[1].dwFlags = THBF_ENABLED; VERIFY(ptl->ThumbBarAddButtons(hWnd, 2,buttons));
break;
case WM_COMMAND:
if (HIWORD(wParam) == THBN_CLICKED) {
if (LOWORD(wParam) == 0)
MessageBox(L"Button 0 clicked", ...);
if (LOWORD(wParam) == 1) MessageBox(L"Button 1 clicked", ...);
}
break;
.
.
And in the second link it shows a C# sample using a wrapper library:
As always, the managed wrappers come to the rescue. The
ThumbButtonManager class (in the Windows7.DesktopIntegration project)
_thumbButtonManager = this.CreateThumbButtonManager();
ThumbButton button2 = _thumbButtonManager.CreateThumbButton(102, SystemIcons.Exclamation, "Beware of me!");
button2.Clicked += delegate
{
statusLabel.Text = "Second button clicked";
button2.Enabled = false;
};
ThumbButton button = _thumbButtonManager.CreateThumbButton(101, SystemIcons.Information, "Click me");
button.Clicked += delegate
{
statusLabel.Text = "First button clicked";
button2.Enabled = true;
};
_thumbButtonManager.AddThumbButtons(button, button2);
Note that you have tooltips and icons at your disposal to personalize the thumbnail toolbar to your application’s needs. All you need to do now is override your windows’ window procedure and call the DispatchMessage method of the ThumbButtonManager, so that it can correctly route the event to your registered event handlers (and of course, don’t forget to call the default window procedure when you’re done!):
if (_thumbButtonManager != null)
_thumbButtonManager.DispatchMessage(ref m);
base.WndProc(ref m);
I'm trying to write an application that senses when someone taps and holds something. I am using windows forms. I tried using the mouse down even but it doesn't appear to fire all the time. This is also going to be a multi touch application. I'm going to have two buttons , and the user can tap and hold one button, while they press on the other button. Or Just press one button. I'm not even sure how a windows form app can handle that.
All the examples inhave seen for a windows touch app use xaml. Is this really the only way to capture tap and hold ??
I'm essentially making an onscreen keyboard here, and I don't think that isnpossible WITHOUT windows forms. Correct me if I am wrong here.
Any help or guidance in this is greatly appreciated. Thanks.
If your program is running on Windows 8, you can use the WM_POINTER API to get the input you need. Override WndProc to capture the messages. You will have to do some P/Invoke to get it working, but it's not terribly hard. Here's some incomplete code to get you started, you'll need to add cases for up, down, and update events for each type of pointer you want to track. Keep track of the pointer IDs to process multi touch. To handle the press-and-hold you'll need to track the time yourself from WM_POINTERDOWN to WM_POINTERUP and act accordingly. Hope this helps.
public const int WM_POINTERDOWN = 0x0246;
public const int WM_POINTERUP = 0x0247;
public const int WM_POINTERUPDATE = 0x0245;
public enum POINTER_INPUT_TYPE : int
{
PT_POINTER = 0x00000001,
PT_TOUCH = 0x00000002,
PT_PEN = 0x00000003,
PT_MOUSE = 0x00000004
}
public static uint GET_POINTERID_WPARAM(uint wParam) { return wParam & 0xFFFF; }
[DllImport("User32.dll")]
public static extern bool GetPointerType(uint pPointerID, out POINTER_INPUT_TYPE pPointerType);
protected override void WndProc(ref Message m)
{
bool handled = false;
uint pointerID;
POINTER_INPUT_TYPE pointerType;
switch(m.Message)
{
case WM_POINTERDOWN:
pointerID = User32.GET_POINTERID_WPARAM((uint)m.WParam);
if (User32.GetPointerType(pointerID, out pointerType))
{
switch (pointerType)
{
case POINTER_INPUT_TYPE.PT_PEN:
// Stylus Down
handled = true;
break;
case POINTER_INPUT_TYPE.PT_TOUCH:
// Touch down
handled = true;
break;
}
}
break;
}
if (handled)
m.Result = (IntPtr)1;
base.WndProc(ref m);
}
This question has been around for a while and might benefit from a simple approach. You can simulate the "tap and hold" (or click and hold) by measuring the time between the MouseDown event and the Click event (which fires before MouseUp). If the time is greater than some value then you cancel the Click and (perhaps) fire your own TapAndHold event. I have created a test control that anyone can use to try this approach out. Just add a UserControl to your test app (I called mine TestTapAndHold) and then paste in the following:
public partial class TestTapAndHold : UserControl
{
private string showText = "Tap Me";
private DateTime mouseDown;
private const int holdTime = 500;
public TestTapAndHold()
{
InitializeComponent();
this.Paint += drawText;
}
public delegate void OnTapAndHold(EventArgs e);
public event OnTapAndHold TapAndHold;
private void drawText(object sender, PaintEventArgs e)
{
using (var drawBrush = new SolidBrush(Color.Black))
{
e.Graphics.DrawString(showText, Font, drawBrush, new Point(5,3));
}
}
protected override void OnClick(EventArgs e)
{
if (DateTime.Now.Subtract(mouseDown).Milliseconds >= holdTime)
{
showText = "Tap Hold";
TapAndHold?.Invoke(e);
} else
{
base.OnClick(e);
showText = "Tapped";
}
Invalidate();
}
private void TestTapAndHold_MouseDown(object sender, MouseEventArgs e)
{
mouseDown = DateTime.Now;
}
}
Build the app and then pop one of the test controls onto a form. You can then add an event handler to your form like:
private void testTapAndHold1_TapAndHold(EventArgs e)
{
MessageBox.Show("You tapped and Held");
}
This general approach enabled me to add "Tap and Hold" functionality to a Windows Forms app running on a Microsoft Surface 4
i have been developing an application and i want to detect usb devices(MASS STORAGE) now that i have done but what i need to do is to capture that message and dont pass it to the windows. i want to ask a password and if that's ok then i want to pass the message to the windows otherwise discard it,,,how can i accomplish that,,,>
protected override void WndProc(ref Message m)
{
switch(m.Msg)
{
case Win32.WM_DEVICECHANGE: OnDeviceChange(ref m); break;
}
base.WndProc (ref m);
}
void OnDeviceChange(ref Message msg)
{
int wParam = (int)msg.WParam;
if (wParam == Win32.DBT_DEVICEARRIVAL)
{
label1.Text = "Arrival";
//MessageBox.Show("" + wParam);
//msg = Message.Create(new IntPtr(),1,new IntPtr(),new IntPtr());
}
else if (wParam == Win32.DBT_DEVICEREMOVECOMPLETE) label1.Text =
"Remove";
}
You can't prevent windows to detect the hardware, unless your software is running under the ring 0 (or 1, can't remember) protection level as a low level application.
This can only be achieved with a low level programming (C, ASM), not C#. The IL language will never be capable of doing things like you want to do.
Anyway, the thing you are doing is nothing but skipping the message to the base class of the Form, not more. The system will continue anyway to send messages like this to other applications no matter if you want it or not.