I know if I used a view controller I can use this:
var scanner = new MobileBarcodeScanner(this.NavigationController);
How do I know what navigation I am using inside of button I need use?
public class BarReaderButtonRenderer : ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
// I tried this but don't worked
var scanner = new MobileBarcodeScanner(this.NavigationController);
// I tried this but do
var scanner = new MobileBarcodeScanner(this);
Element.Clicked += async(s_, e_) => {
// Setup our button
// Tell our scanner to use the default overlay
scanner.UseCustomOverlay = false;
//We can customize the top and bottom text of the default overlay
scanner.TopText = "Hold camera up to barcode to scan";
scanner.BottomText = "Barcode will automatically scan";
//Start scanning
var result = await scanner.Scan ();
HandleScanResult(result);
};
}
}
I can't use this code inside a button render. Or did someone this before?
The project is a shared application for iOS and Android.
The code for creating the scanner should stay inside the view controller/activity/page. You can still use the custom button and add the code you need to the Clicked event handler.
var myCustomButton = new BarReaderButton();
myCustomButton.Clicked += async(s, e) => {
var scanner = new MobileBarcodeScanner();
scanner.UseCustomOverlay = false;
//Start scanning
var result = await scanner.Scan ();
//Do something with the result
};
If this is Xamarin.Forms you will also have to use platform specific code inside the Page code as the barcode reader requires a Context on Android:
#if __IOS__
var scanner = new MobileBarcodeScanner();
#elif __ANDROID__
var scanner = new MobileBarcodeScanner(Forms.Context);
#endif
Related
This Question is In reference with my previous question Embedding VLC player in WInform Application in .Net Core. Core.Intialize() Giving Exception
I want to run the player for certain time and during that time video should be on repeat. Currently code looks like this ...
Core.Initialize();
var libvlc = new LibVLC();
// Make VideoView control
VideoView vv = new VideoView();
vv.MediaPlayer = new MediaPlayer(libvlc);
vv.Dock = DockStyle.Fill;
// Add it to the form
Controls.Add(vv);
var uri = new Uri(#"C:\vid.3gp");
// Use command line options as Options for media playback (https://wiki.videolan.org/VLC_command-line_help/)
var media = new Media(libvlc, uri, ":input-repeat=65535");
vv.MediaPlayer.Play(media);
//Set fullscreen
this.FormBorderStyle = FormBorderStyle.None;
this.Size = Screen.PrimaryScreen.Bounds.Size;
this.Location = Screen.PrimaryScreen.Bounds.Location;
How I can close the player after certain time. currently even if I close the form with the player video keeps playing in background till I close the whole application.
Just to inform the this winform application is created in .netcore3.1.
Regards.
Create MediaPlayer as class field and call it to start/pause/stop it in you WinForm application.
private LibVLC _libVlc;
private MediaPlayer _mediaPlayer;
...
// Call this method in your constructor/initializer
private void StartMediaPlayer(string videoUrl)
{
using var media = new Media(_libVlc, new Uri(videoUrl), ":input-repeat=65535");
_mediaPlayer = new MediaPlayer(_libVlc)
{
Media = media
};
_mediaPlayer.Play();
}
// Method to stop media player
private void button1_Click(object sender, EventArgs e)
{
_mediaPlayer.Stop();
}
i m trying to suppot an app, that uses cefsharp(v79.1.360).
There are list of things I need to implement:
1) ChromiumWebBrowser in WPF (using CefSharp.Wpf minimum example)
2) This browser can go offscreen(with collapsing window or closing it)
3) Work with JavaScriptObjectRepository, and launch some code, that will be do work with web pages(click buttons, change text of elements). Pages may use frameworks, websockets, Http requests and the other stuff
web pages usually do.
After pages work is done, i send results to C# by calling Methods of object, i bounded in jsObjectRepository/
Expectations:
Offscreen prefomance(time delay) should be as well as With opened window/
Reality:
Offscreen perfomance sometimes is really bad, it take time to do work up to 10 seconds(when wpf is only 1-5).
My code:
Initialization
CefSharpSettings.LegacyJavascriptBindingEnabled = true;
CefSharpSettings.WcfEnabled = true;
CefSettings cefSettings = new CefSettings
{
LocalesDirPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "locales"),
Locale = appsettings.CurrentChromeLanguage.ToLocal(),
AcceptLanguageList = appsettings.CurrentChromeLanguage.ToAcceptList(),
};
if (!cefSettings.CefCommandLineArgs.ContainsKey("disable-gpu"))
{
cefSettings.CefCommandLineArgs.Add("disable-gpu", "1");
}
if (cefSettings.CefCommandLineArgs.ContainsKey("enable-system-flash"))
{
cefSettings.CefCommandLineArgs.Remove("enable-system-flash");
}
if (cefSettings.CefCommandLineArgs.ContainsKey("enable-media-stream"))
{
cefSettings.CefCommandLineArgs.Remove("enable-media-stream");
}
cefSettings.CefCommandLineArgs.Add("enable-begin-frame-scheduling", "1");
cefSettings.CefCommandLineArgs.Add("disable-gpu-vsync", "1");
cefSettings.CefCommandLineArgs.Add("mute-audio", "true");
cefSettings.CefCommandLineArgs.Add("enable-media-stream", "0");
cefSettings.CefCommandLineArgs.Add("disable-3d-apis", "1");
cefSettings.CefCommandLineArgs.Add("renderer-process-limit", "10");
cefSettings.CefCommandLineArgs.Add("js-flags", "--lite_mode");
if (!appsettings.IsLoadImage)
{
cefSettings.CefCommandLineArgs.Add("disable-image-loading", "1");
}
cefSettings.LogFile = Path.Combine(ClientConfig.ChromeDataPath, "Log.txt");
cefSettings.LogSeverity = LogSeverity.Error;
cefSettings.IgnoreCertificateErrors = true;
cefSettings.SetOffScreenRenderingBestPerformanceArgs();
Browser creating and usage:
ChromiumWebBrowser browser = new ChromiumWebBrowser();
//xaml window with <ContentControl> with browser
//need hide means when window is closing, we cancel it, and using Hide()
NewBrowserView view = new NewBrowserView(new ChromeTabViewModel(browser));
view.Closing += BrowserView_Closing;
Browser.FrameLoadStart += _browser_FrameLoadStart;
var options = new BindingOptions { CamelCaseJavascriptNames = false };
browser.JavascriptObjectRepository.Register("resultController", this, false, options);
//we can just hide window
void BrowserView_Closing(object sender, CancelEventArgs e)
{
if (_needHide)
{
e.Cancel = true;
Hide();
}
}
//on page load
void _browser_FrameLoadStart(object sender, FrameLoadStartEventArgs e) {
string code = "";
code += "(async function(){ " +
"await CefSharp.BindObjectAsync('resultController'); " +
code += TestJsCode;
code += " })();";//AddWorker
e.Frame.ExecuteJavaScriptAsync(code, $"about:blank/myCode");
Consol.WriteLine(DateTime.Now);
}
public void OnGoodResult()
{
Consol.WriteLine(DateTime.Now);
}
public void OnBadResult()
{
Consol.WriteLine(DateTime.Now);
}
//then i just go by differnet pages and await results
As i mentioned before, when i hide wnd, its taking too long time to print result
I really depended on Layouts and other visuals, so i figured this out. I should just set this code, when window is collapsing:
GetBrowser().GetHost().WasHidden(false);
I am trying to setup an app on SM-R800 tizen-wearable app 4.0 (Samsung Galaxy watch) that will display a tap when it registers in addition to displaying ambient light and ambient pressure. (This is done in C#)
I've tried using the Window class to try to pass my touch event arguments because it doesn't seem like the "View" class is capable of doing that according to the Tizen documentation available.
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
// using ElmSharp; can't be used because it is redundant with Xamarin forms namespace
using Xamarin.Forms;
using Tizen.Wearable.CircularUI.Forms;
using Tizen.Sensor;
using Tizen.NUI;
namespace TizenWearableApp6
{
public class App : Application
{
LightSensor sensor;
Label textlabel;
PressureSensor sensor2;
Label barometer_label;
//Touch touch;
public Vector2 startPos;
public Vector2 direction;
//Label m_Text;
protected override void OnStart()
{
//base.OnCreate();
//Initialize();
}
public App()
{
/*
Window window = Window.Instance;
window.TouchEvent += WindowTouched;
//touch = new Touch(); //this line has to be in a method like "public App()"
m_Text = new Label
{
HorizontalTextAlignment = TextAlignment.Center
};
void WindowTouched(object sender, Window.TouchEventArgs e)
{
m_Text.Text = "I have been touched!";
} */
if (PressureSensor.IsSupported)
{
sensor2 = new PressureSensor(); //instantiate HERE
barometer_label = new Label
{
HorizontalTextAlignment = TextAlignment.Center
};
sensor2.Start(); //Barometer sensor
sensor2.DataUpdated += OnDataUpdated2; //Subscribed event handler (OnDataUpdated2) to event (DataUpdated)
void OnDataUpdated2(object sender, PressureSensorDataUpdatedEventArgs e) // event handler for humidity
{
barometer_label.Text = "Ambient pressure Level: " + e.Pressure;
}
}
else
{
barometer_label = new Label()
{
HorizontalTextAlignment = TextAlignment.Center,
Text = "Does not exist"
};
}
//-----------------Light Sensor------------------------
sensor = new LightSensor(); //"new" because I'm instantiaing a new object of the light sensor class
textlabel = new Label
{
HorizontalTextAlignment = TextAlignment.Center
};
sensor.Start(); //Light sensor
sensor.DataUpdated += OnDataUpdated1; //Subscribed event handler (OnDataUpdated1) to event (DataUpdated)
void OnDataUpdated1(object sender, LightSensorDataUpdatedEventArgs e) //event handler
{
textlabel.Text = "Light level: " + e.Level;
}
// The root page of your application
MainPage = new CirclePage
{
Content = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Children = {
textlabel,
barometer_label,
//m_Text
}
}
};
}
/* protected override void OnStart()
{
// Handle when your app starts
} */
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
With the above code, I commented out the stuff I was trying (unsuccessfully) and just left the portions of my code that works. I expect to see real time updates of ambient light, pressure and expect a string that says "I have been touched!" each time I tap the watch.
What I actually get, (assuming I just use what I have above) is the real time update of ambient light and ambient pressure but the moment I uncomment my Window class stuff then I get a "Out of frame" error and if I ONLY uncomment my label m_Text in both the Children of the VerticalOptions and when I declare "Label m_Text" then I get a segmentation fault error.
Please note that some of the comments might seem arbitrary because I had left some stuff I had tried previously and does NOT necessarily mean I had EVERYTHING uncommented at one time.
Lastly, it might be good to know that I am a complete newbie in C#, Tizen, and Microsoft Visual Studio so I will definitely ask a lot of very beginner level questions.
To start with what would have been misunderstood, there are quite a number of different APIs available when building Tizen .NET applications UI. Some of those are not documented very well so far. To name a few (what we can see in the VisualStudio new project window):
Xamarin.Forms: A rich set of cross-platform APIs available for Android, iOS, UWP, and Tizen as well.
Tizen.Wearable.CircularUI: An extension of Xamarin.Forms which is only available when developing for Tizen Wearables.
ElmSharp-Beta: A C# wrapper of the traditional Tizen native framework (Elementary) which comes with limited support and is widely used for internal implementation.
Tizen.NUI: A new C# GUI framework built on top of Tizen DALi (native graphics library).
So let's get back to the question. Since your project is based on Xamarin.Forms (and Tizen.Wearable.CircularUI), you may want to refer to this guide from the official website to handle user gestures. For example you can simply register a TapGestureRecognizer instance to your StackLayout component as follows (instead of having to import Tizen.NUI APIs).
var layout = new StackLayout
{
VerticalOptions = LayoutOptions.Center,
Children = { textlabel, barometer_label, m_Text }
};
TapGestureRecognizer tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += (sender, e) =>
{
m_Text.Text = "I have been touched!";
};
layout.GestureRecognizers.Add(tapGestureRecognizer);
MainPage = new CirclePage
{
Content = layout
};
I hope it helps and enjoy developing wearable applications.
How to get the current location on a button click in android using Xamarin MVVM?
I am trying to use the GPS co-ordinates for background processing, I Need to get the current device location when ever user clicks on a button and I don't want to display this anywhere on my UI, tried couple of stuffs but nothing worked, can anyone help me to solve the problem?
You can get location in a number of ways. The button click aspect of this question is merely an event handler following the respective Command pattern in MVVM that you setup.
Example of Commands in MVVMLight(A popular MVVM library that has Xamarin support):
https://msdn.microsoft.com/en-us/magazine/dn237302.aspx
Let's go over the ways you can get GPS coordinates:
1) Natively via LocationManager:
http://developer.android.com/guide/topics/location/strategies.html
http://developer.android.com/reference/android/location/LocationManager.html
2) In a Xamarin library that already provides this functionality(Which internally uses LocationManager:
https://github.com/jamesmontemagno/Xamarin.Plugins/tree/master/Geolocator
You need to start the location listener and wait for sometime. then onlocation change will fired. Then only we can able to catch user's current location.
I prefer to show progress dialog and start the thread to listen location change.
Don't use any xamarin third party plugin. Use native Location Manager
Integrate following Code.
[Activity(Label = "Location Activity", MainLauncher = false, Icon = "#drawable/icon")]
public class GetLoationActivity : BaseActivity, Android.Locations.ILocationListener
{
Location userLocation;
Button getLocationButton = FindViewById<Button>(Resource.Id.getLocationButton);
getLocationButton.LongClick += (e, d) =>
{
//TODO:Show Progress Dialog
var _LocationManager = LocationContext.GetSystemService(Context.LocationService) as LocationManager;
var LocationChangedCalled = false;
var PublishAwayFenceThread = new Thread(new ThreadStart(delegate
{
StartLocationChangeListener(this);
}
}));
PublishAwayFenceThread.Start();
};
}
public void StartLocationChangeListener(Activity activity)
{
try
{
var locationCriteria = new Criteria();
locationCriteria.Accuracy = Accuracy.Coarse;
locationCriteria.PowerRequirement = Power.Medium;
string locationProvider = Helper.Instance._LocationManager.GetBestProvider(locationCriteria, true);
if (!String.IsNullOrEmpty(locationProvider))
if (activity!= null)
{
activity.RunOnUiThread(() =>
{
var _LocationManager = LocationContext.GetSystemService(Context.LocationService) as LocationManager;
_LocationManager.RequestLocationUpdates(locationProvider, 1000, 1, this);
Console.WriteLine("****---------*****Location Listener Started****---------*****");
});
}
}
catch (Exception e)
{
}
}
public void OnLocationChanged(Location location)
{
try
{
userLocation = location;
//TODO:Hide Loader
StopLocationChangeListener();
Console.WriteLine("****---------*****Location changed fired****---------*****");
Console.WriteLine("****---------*****" + location.Latitude + "," + location.Longitude + "****---------*****");
}
catch (Exception e)
{
}
}
public void StopLocationChangeListener()
{
try
{
Activity _LocationContextAcitivity = (Activity)Helper.Instance.LocationContext;
_LocationContextAcitivity.RunOnUiThread(() =>
{
var _LocationManager = LocationContext.GetSystemService(Context.LocationService) as LocationManager;
_LocationManager.RemoveUpdates(this);
Console.WriteLine("****---------*****Location Listener stopped****---------*****");
});
}
catch (Exception e)
{
}
}
When I use Mail univesal app in windows 10, when i add an account (setting->accounts->add account), it seems popup a modal window to choose an account. I try to use MessageDialog, but i can't put any custom content into it.
EDIT : this is the screenshot
Is someone knows how to implement it or there is some api can do it?
Note: When this window open, you even can't Minimize/Maximize/Close the main Window. So, it is definitely a modal window.
I haven't used it myself yet but i believe you're looking for ContentDialog api.
var dialog = new ContentDialog() {
Title = "Lorem Ipsum",
MaxWidth = this.ActualWidth // Required for Mobile!
Content = YourXamlContent
};
dialog.PrimaryButtonText = "OK";
dialog.IsPrimaryButtonEnabled = false;
dialog.PrimaryButtonClick += delegate {
};
var result = await dialog.ShowAsync();
msdn guidlines for dialogs: link
msdn ContentDialog API: link
You can easily create a new view like this, for example in your App.xaml.cs:
public static async Task<bool> TryShowNewWindow<TView>(bool switchToView)
{
var newView = CoreApplication.CreateNewView();
int newViewId = 0;
await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var frame = new Frame();
frame.Navigate(typeof(TView), null);
Window.Current.Content = frame;
newViewId = ApplicationView.GetForCurrentView().Id;
});
var viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
if (switchToView && viewShown)
{
// Switch to new view
await ApplicationViewSwitcher.SwitchAsync(newViewId);
}
return viewShown;
}
For further information, take a look at those two guides:
Guidelines for multiple windows
Quickstart: Creating multiple windows for an app (XAML)
If you use Template10 project template, you can use the ModalDialog control : https://github.com/Windows-XAML/Template10/wiki/Docs-%7C-Controls#modaldialog