UIScreen.MainScreen.Brightness not changing Xamarin Forms - c#

I was trying to change the brightness of my iOS app using a text entry box, and I found some stuff online which showed me how to create a dependency service and use UIScreen to set the brightness of the app so that is what I did.
Here is the interface:
public interface IBrightnessService
{
void SetBrightness(float factor);
}
Here is the code for actually calling the setBrightness, where I'm doing it based on a Xamarin Entry form(text is inputted, and when enter is pressed this method is called).
void Entry_Completed(object sender, EventArgs e) {
var text = ((Entry)sender).Text; //cast sender to access the properties of the Entry
float value = float.Parse(text);
var brightnessService = DependencyService.Get<IBrightnessService>();
brightnessService.SetBrightness((float)value);
}
Here is the implementation in iOS. I tested some stuff, and the value is being sent correctly and the method is being reached, but the line of code UIScreen.MainScreen.Brightness = brightness; doesn't actually change UIScreen.MainScreen.Brightness, and I can't seem to figure out why, so was looking for help for this.
using Xamarin.Forms;
using UIKit;
[assembly: Dependency(typeof (iOSBrightnessService))]
public class iOSBrightnessService : IBrightnessService
{
public void SetBrightness(float brightness)
{
UIScreen.MainScreen.Brightness = brightness;
}
}

The iPhone simulator brightness is not adjustable, you have to try in a real device!

Related

C# RLNET/OPENTK System.MissingMethodException during run-time

I am trying to make a small 2d game in c# using the RLNET library. The RLNET library has OpenTK as a dependency, so I added the latest versions of both RLNET and OpenTK to my project using the NuGet packages manager in Visual Studio. I was following along with a tutorial explaining how to work with these libraries. But, when I got to running the code I ran into a MissingMethodException at run-time.
The tutorial I was following along with is here: https://roguesharp.wordpress.com/2016/03/02/roguesharp-v3-tutorial-creating-the-project/
The Solution Explorer shows both libraries included in the project under the References dropdown. And I also included them in my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RLNET;
using OpenTK;
namespace Rouge_Game
{
class Program
{
private static readonly int _screenWidth = 100;
private static readonly int _screenHeight = 70;
private static RLRootConsole _rootConsole;
static void Main(string[] args)
{
// This must be the exact name of the bitmap font file we are using or it will error.
string fontFileName = "terminal8x8.png";
// The title will appear at the top of the console window
string consoleTitle = "RougeSharp V3 Tutorial - Level 1";
// Tell RLNet to use the bitmap font that we specified and that each tile is 8 x 8 pixels
_rootConsole = new RLRootConsole(fontFileName, _screenWidth, _screenHeight,
8, 8, 1f, consoleTitle);
// Set up a handler for RLNET's Update event
_rootConsole.Update += OnRootConsoleUpdate;
// Set up a handler for RLNET's Render event
_rootConsole.Render += OnRootConsoleRender;
// Begin RLNET's game loop
_rootConsole.Run();
}
// Event handler for RLNET's Update event
private static void OnRootConsoleUpdate(object sender, UpdateEventArgs e)
{
_rootConsole.Print(10, 10, "It worked!", RLColor.White);
}
// Event handler for RLNET's Render event
private static void OnRootConsoleRender(object sender, UpdateEventArgs e)
{
// Tell RLNET to draw the console that we set
_rootConsole.Draw();
}
}
}
The part of the code that has a run time error is this:
// Event handler for RLNET's Render event
private static void OnRootConsoleRender(object sender, UpdateEventArgs e)
{
// Tell RLNET to draw the console that we set
_rootConsole.Draw();
}
When I run the project it compiles with no errors and the program launches, but then throws this exception:
System.MissingMethodException
HResult=0x80131513
Message=Method not found: 'Void
OpenTK.Graphics.OpenGL.GL.BlendFunc(OpenTK.Graphics.OpenGL.BlendingFactorSrc, OpenTK.Graphics.OpenGL.BlendingFactorDest)'.
Source=RLNET
StackTrace:
at RLNET.RLRootConsole.Draw()
at Rouge_Game.Program.OnRootConsoleRender(Object sender, UpdateEventArgs e) in C:\Users\pjmul\source\repos\Rouge Game\Rouge Game\Program.cs:line 45
at RLNET.RLRootConsole.window_RenderFrame(Object sender, FrameEventArgs e)
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at OpenTK.GameWindow.OnRenderFrame(FrameEventArgs e)
at OpenTK.GameWindow.RaiseRenderFrame(Double elapsed, Double& timestamp)
at OpenTK.GameWindow.DispatchRenderFrame()
at OpenTK.GameWindow.Run(Double updates_per_second, Double frames_per_second)
at OpenTK.GameWindow.Run(Double updateRate)
at RLNET.RLRootConsole.Run(Double fps)
at Rouge_Game.Program.Main(String[] args) in
C:\Users\pjmul\source\repos\Rouge Game\Rouge Game\Program.cs:line 32
I don't understand this error however as when I use the object viewer built into Visual Studio I can find the "missing" function when I open OpenTK.dll. Any suggestions as to how I might fix this error are greatly appreciated. I would also like to thank anyone who takes the time to help me in advance.
There is something wrong with the 3.x branch of OpenTK. Try downgrading your OpenTK package back to 2.x and it will work.

Build works, but media play doesn't seem to load

i'm working on an android app at the moment that has the purpose of playing a particular song at exactly midnight. I know that there might already be apps in the appstore that serve that purpose, but I'm new to coding and wanted to try to program the app myself.
So now I reached the point where I don't know what to do anymore. I tried debugging the App on my LG H818P running Android 6.0. It posted, The Icon, the Name and everything were correct, but i didn't play the song, even when i set the time when it should've played it to two minutes after the start if the building.
So that's the code of the MainActivity.cs in Visual Studio 2017, can anyone find any errors?
using Android.App;
using Android.Widget;
using Android.OS;
using System;
using Android.Media;
namespace Name of the App
{
[Activity(Label = "Name of the App", MainLauncher = true)]
public class MainActivity : Activity
{
string text = "status";
protected void onCreate(Bundle savedInstanceState)
{
}
public void main()
{
try
{
string systemtime = DateTime.Now.ToString();
for (int i = 0; i > 0; i++)
{
if (systemtime == "09:07:00 pm")
{
StartPlayer();
player.Start();
}
}
}
catch
{
text = "Error!";
}
}
protected MediaPlayer player;
public void StartPlayer()
{
if (player == null)
{
player = new MediaPlayer();
player.SetDataSource("Ressources.raw.file2beplayed.mp3");
player.Prepare();
player.Start();
text = "Playing!";
}
else
{
player.Reset();
player.SetDataSource("Ressources.raw.file2beplayed.mp3");
player.Prepare();
player.Start();
}
}
}
}
As I said, I'm a Noob in coding, so sorry for the maybe ugly code :)
Thanks for your replies!
The default format for ToString in a DateTime is MM/dd/yyyy, so your comparation systemtime == "09:07:00 pm" will never be true.
You can use a TimeSpan and the property TimeOfDay from DateTime;
if(DateTime.Now.TimeOfDay == new Timespan(21,7,0))
//...
Also, your loop will never be executed as you initialize i as 0, so at the first check i will not be greater than 0 so the loop isn't executed.
Finally, Android does not use the main function, is an special type of program, your initialization code should be in the OnCreate function, but if you create an infinite loop in that function Android will close the application as it will not finish it's initialization, you need to use a timer and check the condition each second.

Capture Camera Feed from EasyCap 4ch USB DVR Device using DirectShow and DirectX.Capture C#

I'm trying to capture the camera feed from an EasyCap 4 Channel USB DVR Device that i got recently
and i have bought a super Mimi Monochrome/Color Camera and connected it to the DVR Device and managed to correctly setup the device with the driver "SMI Grabber" and installed the software that comes with the Device "SuperViewer"
and i have wrote a simple windows form application that contains a PictureBox to priview the camera feed
(There is an edit in the bottom)
The Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DirectX.Capture;
namespace DirectShowWithCrossbar
{
public partial class Form1 : Form
{
private CrossbarSource crossbar;
private Filters filters;
private Capture capture;
public Form1()
{
InitializeComponent();
filters = new Filters();
capture = new Capture(filters.VideoInputDevices[0], filters.AudioInputDevices[0]);
foreach (Filter device in filters.VideoInputDevices)
{
comboBox1.Items.Add(device);
}
if (comboBox1.Items.Count > 0)
comboBox1.SelectedIndex = 0;
foreach (Filter device in filters.AudioInputDevices)
{
comboBox2.Items.Add(device);
}
if (comboBox2.Items.Count > 0)
comboBox2.SelectedIndex = 0;
foreach (Source source in capture.VideoSources)
{
comboBox3.Items.Add(source);
}
if (comboBox3.Items.Count > 0)
comboBox3.SelectedIndex = 0;
ShowPropertPagesInMenuStrip();
crossbar = (CrossbarSource)capture.VideoSource;
crossbar.Enabled = true;
capture.PreviewWindow = pictureBox1;
}
private void ShowPropertPagesInMenuStrip()
{
foreach (PropertyPage pro in capture.PropertyPages)
{
menusToolStripMenuItem.DropDownItems.Add(new ToolStripMenuItem(pro.Name));
}
}
private void button1_Click(object sender, EventArgs e)
{
capture.Cue();
capture.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
capture.Stop();
capture.Dispose();
}
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
capture.VideoSource = (Source)comboBox3.SelectedItem;
}
}
}
and i got a black screen in the picture box ??
and by mistake after closing my application i ran the SuperViewer application that comes with the DVR device and then open my application then my picture box began to show me the feed from the camera, strange!!! and the feed from the original software freezes !!
DirectX.Capture Example and Sources tried with the same result http://www.codeproject.com/Articles/3566/DirectX-Capture-Class-Library
and i have also used OpenCV and Touchless and i got the same result :(
Edit:
I have been searching and found that i need to get the filter (IAMCrossbar) i think that is the problem DirectShow USB webcam changing video source and after appling the changes in this link in the DirectX.Capture Wrapper i still get the same results :(
Thanks for any help in advance Yaser
If your capture device has option, to select one from multiple input interfaces, then yes, you are right about, that you needed to use IAMCrossbar.
If you want to stick to Directshow( as others have suggested OpenCV), then I would suggest,
Try building all capturing related code in a C++/CLI dll,
Build all your UI in C#.
You can take this MP3 Player Sample Project as starting point for your dll.
For capturing, AmCap is a detailed example.
What I mean is that you need to get the capturing code out of AmCap into above MP3 Player Sample dll, and expose it to your C# application.

Display a WebPage using System.Windows.Controls.WebBrowser(LightSwitch, VS2012)

I have followed;
http://dotnettim.wordpress.com/2011/04/17/lightswitchdisplaying-web-pages-html-on-a-screen/
But instead of a webpage im left with;
Im using VS2012 and the example is in VS2010. The diffrence in code that i have encounterd is the following;
Original;
private void WebPage_Activated()
Mine;
partial void WebPage_Activated()
I have checked the debugger and the event fires smoothly, is there any major changes made in beteween the versions or is there anything else that i have overlooked.
I include all code an a picture of where i have put the custom control (im abit uncertain about that part);
public partial class WebPage
{
partial void WebPage_Activated()
{
// Write your code here.
this.FindControl("prpWebPage").ControlAvailable += webControlAvailable;
}
private void webControlAvailable(object sender, ControlAvailableEventArgs e)
{
((System.Windows.Controls.WebBrowser)e.Control).Navigate(new Uri("http://news.bbc.co.uk"));
}
}
I solved it, the size is set to 0 initally. So;
fixed it :)

Why can't you bind the Size of a windows form to ApplicationSettings?

Update: Solved, with code
I got it working, see my answer below for the code...
Original Post
As Tundey pointed out in his answer to my last question, you can bind nearly everything about a windows forms control to ApplicationSettings pretty effortlessly. So is there really no way to do this with form Size? This tutorial says you need to handle Size explicitly so you can save RestoreBounds instead of size if the window is maximized or minimized. However, I hoped I could just use a property like:
public Size RestoreSize
{
get
{
if (this.WindowState == FormWindowState.Normal)
{
return this.Size;
}
else
{
return this.RestoreBounds.Size;
}
}
set
{
...
}
}
But I can't see a way to bind this in the designer (Size is notably missing from the PropertyBinding list).
I finally came up with a Form subclass that solves this, once and for all. To use it:
Inherit from RestorableForm instead of Form.
Add a binding in (ApplicationSettings) -> (PropertyBinding) to WindowRestoreState.
Call Properties.Settings.Default.Save() when the window is about to close.
Now window position and state will be remembered between sessions. Following the suggestions from other posters below, I included a function ConstrainToScreen that makes sure the window fits nicely on the available displays when restoring itself.
Code
// Consider this code public domain. If you want, you can even tell
// your boss, attractive women, or the other guy in your cube that
// you wrote it. Enjoy!
using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing;
namespace Utilities
{
public class RestorableForm : Form, INotifyPropertyChanged
{
// We invoke this event when the binding needs to be updated.
public event PropertyChangedEventHandler PropertyChanged;
// This stores the last window position and state
private WindowRestoreStateInfo windowRestoreState;
// Now we define the property that we will bind to our settings.
[Browsable(false)] // Don't show it in the Properties list
[SettingsBindable(true)] // But do enable binding to settings
public WindowRestoreStateInfo WindowRestoreState
{
get { return windowRestoreState; }
set
{
windowRestoreState = value;
if (PropertyChanged != null)
{
// If anybody's listening, let them know the
// binding needs to be updated:
PropertyChanged(this,
new PropertyChangedEventArgs("WindowRestoreState"));
}
}
}
protected override void OnClosing(CancelEventArgs e)
{
WindowRestoreState = new WindowRestoreStateInfo();
WindowRestoreState.Bounds
= WindowState == FormWindowState.Normal ?
Bounds : RestoreBounds;
WindowRestoreState.WindowState = WindowState;
base.OnClosing(e);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (WindowRestoreState != null)
{
Bounds = ConstrainToScreen(WindowRestoreState.Bounds);
WindowState = WindowRestoreState.WindowState;
}
}
// This helper class stores both position and state.
// That way, we only have to set one binding.
public class WindowRestoreStateInfo
{
Rectangle bounds;
public Rectangle Bounds
{
get { return bounds; }
set { bounds = value; }
}
FormWindowState windowState;
public FormWindowState WindowState
{
get { return windowState; }
set { windowState = value; }
}
}
private Rectangle ConstrainToScreen(Rectangle bounds)
{
Screen screen = Screen.FromRectangle(WindowRestoreState.Bounds);
Rectangle workingArea = screen.WorkingArea;
int width = Math.Min(bounds.Width, workingArea.Width);
int height = Math.Min(bounds.Height, workingArea.Height);
// mmm....minimax
int left = Math.Min(workingArea.Right - width,
Math.Max(bounds.Left, workingArea.Left));
int top = Math.Min(workingArea.Bottom - height,
Math.Max(bounds.Top, workingArea.Top));
return new Rectangle(left, top, width, height);
}
}
}
Settings Bindings References
SettingsBindableAttribute
INotifyPropertyChanged
The reason why the Form.Size property is not available in the settings binding UI is because this property is marked DesignerSerializationVisibility.Hidden. This means that the designer doesn't know how to serialise it, let alone generate a data binding for it. Instead the Form.ClientSize property is the one that gets serialised.
If you try and get clever by binding Location and ClientSize, you'll see another problem. When you try to resize your form from the left or top edge, you'll see weird behaviour. This is apparently related to the way that two-way data binding works in the context of property sets that mutually affect each other. Both Location and ClientSize eventually call into a common method, SetBoundsCore().
Also, data binding to properties like Location and Size is just not efficient. Each time the user moves or resizes the form, Windows sends hundreds of messages to the form, causing the data binding logic to do a lot of processing, when all you really want is to store the last position and size before the form is closed.
This is a very simplified version of what I do:
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.MyState = this.WindowState;
if (this.WindowState == FormWindowState.Normal)
{
Properties.Settings.Default.MySize = this.Size;
Properties.Settings.Default.MyLoc = this.Location;
}
else
{
Properties.Settings.Default.MySize = this.RestoreBounds.Size;
Properties.Settings.Default.MyLoc = this.RestoreBounds.Location;
}
Properties.Settings.Default.Save();
}
private void MyForm_Load(object sender, EventArgs e)
{
this.Size = Properties.Settings.Default.MySize;
this.Location = Properties.Settings.Default.MyLoc;
this.WindowState = Properties.Settings.Default.MyState;
}
Why is this a very simplified version? Because doing this properly is a lot trickier than it looks :-)
One of the reason I imagine size binding is not allowed is because the screen may change between sessions.
Loading the size back when the resolution has reduced could result in the title bar being beyond the limits of the screen.
You also need to be wary of multiple monitor setups, where monitors may no longer be available when you app next runs.
Well I have had a quick play with this and you are correct, while there is no way to directly bind the size of the form to AppSettings, you can add your own values and change the size on load.
I would perhaps recommend that if this is a common feature, you subclass Form and make it automatically prob the App.Config for the forms size settings.
(Or you could roll your own file.. Get it to query an Xml file "formname.settings.xml" or something? - thinking out loud!)..
Heres what I had (very rough, no error checking etc).
App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="FormHeight" value="500" />
<add key ="FormWidth" value="200"/>
</appSettings>
</configuration>
Form Code
private void Form1_Load(object sender, EventArgs e)
{
string height = ConfigurationManager.AppSettings["FormHeight"];
int h = int.Parse(height);
string width = ConfigurationManager.AppSettings["FormWidth"];
int w = int.Parse(width);
this.Size = new Size(h, w);
}
I agree with Rob Cooper's answer. But I think Martin makes a very good point. Nothing like having users open your application and the app is off-screen!
So in reality, you'll want to combine both answers and bear in mind the current screen dimensions before setting your form's size.

Categories