I'm writing an Ad Controller in unity3d. I found strange problem with event handlers related with interstital ads.
Method that I use to request interstitial:
private void GoogleRequestInterstitial(string gameID)
{
if (string.IsNullOrEmpty(gameID))
{
Debug.LogErrorFormat("GoogleAds - Game ID can't be NULL or EMPTY!");
if (WinzebraAdsConsole.Instance != null) WinzebraAdsConsole.Instance.WriteLine(TagGoogleAds, "Game ID can't be NULL or EMPTY!");
}
var interstitial = new InterstitialAd(gameID);
AdRequest request = null;
if (CallbackMethod != null)
{
interstitial.AdFailedToLoad += InterstitialOnAdFailedToLoad;
interstitial.AdClosed += InterstitialOnAdClosed;
interstitial.AdClosing += InterstitialOnAdClosing;
interstitial.AdLeftApplication += InterstitialOnAdLeftApplication;
interstitial.AdLoaded += InterstitialOnAdLoaded;
interstitial.AdOpened += InterstitialOnAdOpened;
}
else
{
Debug.LogWarningFormat("GoogleAds - Don't forget to register callback!");
if (WinzebraAdsConsole.Instance != null) WinzebraAdsConsole.Instance.WriteLine(TagGoogleAds, "Don't forget to register callback!");
}
if (DebugMode)
{
request = new AdRequest.Builder()
.AddTestDevice(AdRequest.TestDeviceSimulator) // Simulator.
.AddTestDevice("2077ef9a63d2b398840261c8221a0c9b") // My test device.
.Build();
}
else
{
request = new AdRequest.Builder().Build();
}
interstitial.LoadAd(request);
controller.StartCoroutine(GoogleShowAdWhenReady(interstitial));
}
Corutine:
private IEnumerator GoogleShowAdWhenReady(InterstitialAd interstitial)
{
while (!interstitial.IsLoaded())
yield return null;
interstitial.Show();
if (WinzebraAdsConsole.Instance != null) WinzebraAdsConsole.Instance.WriteLine(TagGoogleAds, "Interstitial : SHOW");
}
Here is whole event handlers region:
#region EventHandlers - INTERSTITIAL
private void InterstitialOnAdClosed(object sender, EventArgs args)
{
CallbackMethod(WinzebraAdsController.WinzebraShowResult.Finished);
if (WinzebraAdsConsole.Instance != null) WinzebraAdsConsole.Instance.WriteLine(TagGoogleAds, "FINISHED");
var obj = sender as InterstitialAd;
obj.Destroy();
}
private void InterstitialOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
CallbackMethod(WinzebraAdsController.WinzebraShowResult.Failed);
if (WinzebraAdsConsole.Instance != null) WinzebraAdsConsole.Instance.WriteLine(TagGoogleAds, "FAILED !");
var obj = sender as InterstitialAd;
obj.Destroy();
}
private void InterstitialOnAdClosing(object sender, EventArgs eventArgs)
{
if (WinzebraAdsConsole.Instance != null) WinzebraAdsConsole.Instance.WriteLine(TagGoogleAds, "Interstitial On Ad Closing");
}
private void InterstitialOnAdOpened(object sender, EventArgs eventArgs)
{
if (WinzebraAdsConsole.Instance != null) WinzebraAdsConsole.Instance.WriteLine(TagGoogleAds, "Interstitial On Ad Opened");
}
private void InterstitialOnAdLoaded(object sender, EventArgs eventArgs)
{
if (WinzebraAdsConsole.Instance != null) WinzebraAdsConsole.Instance.WriteLine(TagGoogleAds, "Interstitial On Ad Loaded");
}
private void InterstitialOnAdLeftApplication(object sender, EventArgs eventArgs)
{
if (WinzebraAdsConsole.Instance != null) WinzebraAdsConsole.Instance.WriteLine(TagGoogleAds, "Interstitial On Ad Left Application");
}
#endregion
Info:
WinzebraAdsConsole is self-written "console" based on Text component.
CallbackMethod is custom "global" callback and this is allways NOT NULL (checked before).
On first run i can see in self-written console that methods InterstitialOnAdLoaded and InterstitialOnAdOpened runs properly. But problem starts when im close interstitial and event InterstitialOnAdClosed doesn't get called.
Additionally on second run of interstitial i get event InterstitialOnAdClosing but still not "OnClosed".
Is there any problem with my code? Anyone see that kind of problem before?
Screenshoots:
After first interstitial:
After second interstitial:
I think there is no need to define another Co-routine to wait will the ad is read to display, instead try this may fix your issue:
private void InterstitialOnAdLoaded(object sender, EventArgs eventArgs)
{
if (WinzebraAdsConsole.Instance != null) WinzebraAdsConsole.Instance.WriteLine(TagGoogleAds, "Interstitial On Ad Loaded");
if (interstitial.IsLoaded())
{
interstitial.Show();
if (WinzebraAdsConsole.Instance != null) WinzebraAdsConsole.Instance.WriteLine(TagGoogleAds, "Interstitial : SHOW");
}
}
Related
am trying to make streaming video using aforge on visual studio windows forms
in debug mode everything works well but after publishing it the picturebox that is used to show the video still white
Here is the code
if (device != null && cboDevice.Items.Count != 0)
{
if (firstim != null)
{
pictureBox1.Image = firstim;
}
device = new VideoCaptureDevice(filter[cboDevice.SelectedIndex].MonikerString);
device.NewFrame += new NewFrameEventHandler( Device_NewFrame);
device.Start();
private void Form1_Load(object sender, EventArgs e)
{
filter = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach(FilterInfo dev in filter)
cboDevice.Items.Add(dev.Name);
cboDevice.SelectedIndex = 0;
device = new VideoCaptureDevice();
}
private void button4_Click(object sender, EventArgs e)
{
if (device != null && cboDevice.Items.Count != 0)
{
device = new VideoCaptureDevice(filter[cboDevice.SelectedIndex].MonikerString);
device.NewFrame += Device_NewFrame;
device.Start();
}
}
could please help with that. I can not subscribe for event fired by an object from another Task.
Note: If i took the code outside the Task, it works fine. you can see the commented code
private void Form1_Load(object sender, EventArgs e)
{
_machines.Add(new Machine() { Ip = "192.168.1.10", Name = "Machine_01", Status = "Connected" });
dgvMachines.DataSource = _machines;
}
private void startLiveMonitoringToolStripMenuItem_Click(object sender, EventArgs e)
{
//if (_machines.Count <= 0) return;
//_fpMachine = new ZktFingerPrint(_machines[0].Ip, _machines[0].Name);
//_fpMachine.Connect();
//_fpMachine.EnableLiveFingerPrintDetection();
//_fpMachine.NewFingerPrintDetected += FpMachine_NewFingerPrintDetected;
foreach (var machine in _machines)
{
Task.Factory.StartNew(() =>
{
IFingerPrintMachine fpMachine = new ZktFingerPrint(machine.Ip, machine.Name);
fpMachine.Connect();
fpMachine.EnableLiveFingerPrintDetection();
fpMachine.NewFingerPrintDetected += FpMachine_NewFingerPrintDetected;
});
}
}
private void FpMachine_NewFingerPrintDetected(object sender, FingerPrintEventArgs e)
{
var fpr = new FingerPrintRecord(e.FingerPrintDateTime, e.UserId);
dgvMonitor.Rows.Add("Machine_01", fpr.FingerPrintDateTime, fpr.UserSn);
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Scenario_1.
1. The user. Presses the "Start" button;
2. The program. Creates an instance of the user element "ucBackgroundWorker" in "flowLayoutPanel1";
3. The program. Creates a node in the "treeView1";
"Scenario_1" can be repeated an unlimited number of times.
Scenario_2.
There are:
- Several processes are started in "flowLayoutPanel1";
- in "treeView1" there is a tree of processes;
Scenario:
1. The user. Moves the cursor to "treeView1";
2. The program. In "flowLayoutPanel2" it displays the process (instance
"ucBackgroundWorker" ") of the node on which the cursor is located;
I tried to implement this scenario (Scenario_1 + Scenario_2) as I understand it.
I thought that the user element instances can be assigned indexes,
and then, depending on the index, display in "flowLayoutPanel2".
For the test, the button of this script made a button "btShowTheProces"
But the project does not work.
When debugging, I get an error.
Form3.cs
flowLayoutPanel1.Controls.Add (ucBgWorker [i_ucBWrk]);
Error "The object reference does not point to an instance of the object."
ucBgWorker = null;
Your questions
1. How to fix the error?
2. Do I solve my problem correctly?
3. What are the other ways to accomplish this scenario?
For example, that the process was not bound to an index, but to a "string"?
For example, something like this
string i_ucBWrk;
i_ucBWrk = "process_1";
flowLayoutPanel1.Controls.Add (ucBgWorker [i_ucBWrk]);
Form3.cs
namespace rsh
{
public partial class Form3 : Form
{
// ucBackgroundWorker[] ucBgWorker = null;
int i_ucBWrk=0;
private ucBackgroundWorker[] ucBgWorker;
int procNumb;
public Form3()
{
InitializeComponent();
}
// после выбора узла дерева
void treeView1_AfterSelect(object sender, TreeViewCancelEventArgs e)
{
}
private void btnStart_Click(object sender, EventArgs e)
{
i_ucBWrk++;
ucBgWorker[i_ucBWrk] = new ucBackgroundWorker();
// ucBgWorker[i_ucBWrk].Done += new Action<string, EventArgs>(Worker_Done);
// ucBgWorker[i_ucBWrk].Cancel += new Action<string, EventArgs>(Worker_Cancel);
flowLayoutPanel1.Controls.Add(ucBgWorker[i_ucBWrk]);
ucBgWorker[i_ucBWrk].Run(1);
// ucBgWorker.Run(Convert.ToInt32(textBox1.Text));
}
void Worker_Done(string arg, EventArgs evtarg)
{
label1.Text = arg + " Done One";
//System.Threading.Thread.Sleep(1000);
}
void Worker_Cancel(string arg, EventArgs evtarg)
{
label1.Text = arg + " Cancel Click";
//System.Threading.Thread.Sleep(1000);
}
// show the process
private void btShowTheProces_Click(object sender, EventArgs e)
{
procNumb = Convert.ToInt32(numericUpDown1.Value);
flowLayoutPanel2.Controls.Clear();
flowLayoutPanel2.Controls.Add(ucBgWorker[procNumb]);
}
}
}
ucBackgroundWorker.cs
namespace rsh
{
public partial class ucBackgroundWorker : UserControl
{
BackgroundWorker bgWorker = null;
public event Action<string, EventArgs> Done;
public event Action<string, EventArgs> Cancel;
private static bool m_continue = true;
// Уведомляет один или более ожидающих потоков о том, что произошло событие. Этот класс не наследуется.
// https://msdn.microsoft.com/ru-ru/library/system.threading.manualresetevent(v=vs.110).aspx
private ManualResetEvent _resetEvent = new ManualResetEvent(false);
//Semaphore sWaiter = new Semaphore(0, 1);
public ucBackgroundWorker()
{
InitializeComponent();
bgWorker = new BackgroundWorker();
bgWorker.WorkerSupportsCancellation = true;
bgWorker.WorkerReportsProgress = true;
bgWorker.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
bgWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
public void Run(int counter)
{
if (!bgWorker.IsBusy)
{
bgWorker.RunWorkerAsync(counter);
}
_resetEvent.Set();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int input = int.Parse(e.Argument.ToString());
this.BeginInvoke((MethodInvoker)delegate
{
lblStatus.Text = "Running";
});
for (int i = 1; i <= input; i++)
{
_resetEvent.WaitOne();
Thread.Sleep(1000);
(sender as BackgroundWorker).ReportProgress(i*1); // шаг
// (sender as BackgroundWorker).ReportProgress(i * 10);
if ((sender as BackgroundWorker).CancellationPending)
{
this.BeginInvoke((MethodInvoker)delegate
{
lblStatus.Text = "Cancel";
});
e.Cancel = true;
return;
}
}
Thread.Sleep(1000);
}
// This event handler deals with the results of the
// background operation.
// Этот обработчик событий имеет дело с результатами
// фоновая операция.
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// First, handle the case where an exception was thrown.
// Сначала обрабатываем случай, когда было создано исключение.
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else if (e.Cancelled)
{
if (Cancel != null)
Cancel(this.Name, EventArgs.Empty);
}
else
{
this.BeginInvoke((MethodInvoker)delegate
{
lblStatus.Text = "Done";
});
if (Done != null)
Done(this.Name, EventArgs.Empty);
}
_resetEvent.Reset();
}
// This event handler updates the progress bar.
// Этот обработчик событий обновляет индикатор выполнения.
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pBar.Refresh();
pBar.Value = e.ProgressPercentage;
}
// *** *** *** ***
// *** КНОПКИ ***
// *** *** *** ***
// Cancel
private void btnCancel_Click(object sender, EventArgs e)
{
if (bgWorker.IsBusy)
{
bgWorker.CancelAsync();
}
}
// Pause
private void btnPause_Click(object sender, EventArgs e)
{
if (bgWorker.IsBusy)
{
if (btnPause.Text.ToUpper() == "PAUSE")
{
btnPause.Text = "Resume";
m_continue = false;
_resetEvent.Reset();
}
else
if (btnPause.Text.ToUpper() == "RESUME")
{
btnPause.Text = "Pause";
m_continue = true;
_resetEvent.Set();
}
}
}
}
}
project - link
You never initialise the ucBgWorker array.
Change your code to this
private ucBackgroundWorker[] ucBgWorker = new ucBackgroundWorker[10];
The issue with this is that your array is then set to a maximum of 10.
You'd be better off using a List:
private List<ucBackgroundWorker> ucBgWorker = new List<ucBackgroundWorker>();
Add items with:
ucBgWorker.Add(new ucBackgroundWorker());
You can still access items by index:
ucBackgroundWorker item = ucBgWorker[0];
As long as there are items in the list.
I have an application where combox text get populated with data, I have two timer function to read the combox text content, one timer works fine, but the other time always shows combox content is always empty string. I am wondering where things are wrong
private void AddNewDataToSystemButton_Click(object sender, EventArgs e)
{
if (tbAddTrainTrainID.Text != "" && tbAddTrainRegionID.Text != "" && tbAddTrainSegmentID.Text != "")
{
bool isTrainAdded = CommonStore.TrainSimMainDatabase.AddNewTrainInToSystem(Convert.ToInt32(tbAddTrainTrainID.Text),
Convert.ToByte(tbAddTrainRegionID.Text), Convert.ToByte(tbAddTrainSegmentID.Text));
CommonStore.TrainSimMainDatabase.InitializingTrainCollection[Convert.ToInt32(tbAddTrainTrainID.Text)].VehicleList.IsManualTrain = false;
if (isTrainAdded)
{
cbTrainList.Items.Add(tbAddTrainTrainID.Text);
cbRemoveTrainID.Items.Add(tbAddTrainTrainID.Text);
}
else
{
TrainChangeRequestResponse.Text = "Train already exists in the system.";
}
}
}
private void Timer1_Tick(object sender, EventArgs e)
{
if (CommonStore.TrainSimMainDatabase != null)
{
if (CommonStore.TrainSimMainDatabase.InitializingTrainCollection.Count > 0 && cbTrainList.Text != "")
{
// huge code
}
}
}
public void VATCTimer_Tick(object sender, EventArgs e)
{
if (cbTrainList.Text != "")
{
\\ huge code
I have created a virtual keyboard, the keyboard pops up for wpf textbox controls. How can I make the keyboard pops out when clicking on a textbox inside a web page?
the logic for displaying a textbox is given below:
static void TouchScreenKeyboardPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
FrameworkElement host = sender as FrameworkElement;
if (host != null)
{
host.GotFocus += new RoutedEventHandler(OnGotFocus);
host.LostFocus += new RoutedEventHandler(OnLostFocus);
}
}
static void OnGotFocus(object sender, RoutedEventArgs e)
{
Control host = sender as Control;
if (sender == typeof(TextBox))
{
_PreviousTextBoxBackgroundBrush = host.Background;
_PreviousTextBoxBorderBrush = host.BorderBrush;
_PreviousTextBoxBorderThickness = host.BorderThickness;
host.Background = Brushes.Yellow;
host.BorderBrush = Brushes.Red;
host.BorderThickness = new Thickness(4);
}
_CurrentControl = host;
if (_InstanceObject == null)
{
FrameworkElement ct = host;
while (true)
{
if (ct is Window)
{
((Window)ct).LocationChanged += new EventHandler(TouchScreenKeyboard_LocationChanged);
((Window)ct).Activated += new EventHandler(TouchScreenKeyboard_Activated);
((Window)ct).Deactivated += new EventHandler(TouchScreenKeyboard_Deactivated);
break;
}
if(ct.Parent != null)
ct = (FrameworkElement)ct.Parent;
}
_InstanceObject = new TouchScreenKeyboard();
_InstanceObject.AllowsTransparency = true;
_InstanceObject.WindowStyle = WindowStyle.None;
_InstanceObject.ShowInTaskbar = false;
_InstanceObject.ShowInTaskbar = false;
_InstanceObject.Topmost = true;
host.LayoutUpdated += new EventHandler(tb_LayoutUpdated);
}
}
static void TouchScreenKeyboard_Deactivated(object sender, EventArgs e)
{
if (_InstanceObject != null)
{
_InstanceObject.Topmost = false;
}
}
static void TouchScreenKeyboard_Activated(object sender, EventArgs e)
{
if (_InstanceObject != null)
{
_InstanceObject.Topmost = true;
}
}
static void TouchScreenKeyboard_LocationChanged(object sender, EventArgs e)
{
syncchild();
}
static void tb_LayoutUpdated(object sender, EventArgs e)
{
syncchild();
}
static void OnLostFocus(object sender, RoutedEventArgs e)
{
Control host = sender as Control;
host.Background = _PreviousTextBoxBackgroundBrush;
host.BorderBrush = _PreviousTextBoxBorderBrush;
host.BorderThickness = _PreviousTextBoxBorderThickness;
if (_InstanceObject != null)
{
_InstanceObject.Close();
_InstanceObject = null;
}
}
#endregion
}
private static void syncchild()
{
if (_CurrentControl != null && _InstanceObject != null)
{
Point virtualpoint = new Point(0, _CurrentControl.ActualHeight + 3);
Point Actualpoint = _CurrentControl.PointToScreen(virtualpoint);
if (WidthTouchKeyboard + Actualpoint.X > SystemParameters.VirtualScreenWidth)
{
double difference = WidthTouchKeyboard + Actualpoint.X - SystemParameters.VirtualScreenWidth;
_InstanceObject.Left = Actualpoint.X - difference;
}
else if (!(Actualpoint.X > 1))
{
_InstanceObject.Left = 1;
}
else
_InstanceObject.Left = Actualpoint.X;
_InstanceObject.Top = Actualpoint.Y;
_InstanceObject.Show();
}
}
private static void SetKeyInBrowser(string key)
{
var elementName = (((mshtml.HTMLDocument)(dom)).activeElement).id;
if (elementName != null)
{
var existingText = dom.getElementById(elementName).getAttribute("value");
if (existingText == null)
{
existingText = "";
}
//if it's a backspace.
if (isBackspace)
{
existingText = existingText.ToString().Remove(existingText.ToString().Length - 1);
dom.getElementById(elementName).setAttribute("value", existingText.ToString());
}
else if (key.Length != 0)
{
dom.getElementById(elementName).setAttribute("value", existingText.ToString() + key[key.Length - 1]);
}
}
isBackspace = false;
}
You need to use javascript for that. You need to know when that textfield is focused like this:
Check if focus is on a textfield
And then once the focused event is fired on JavaScript you should call your WPF function for showing the keyboard up. Here's useful hints:
How to programmaticaly check if a text input box inside a web page loaded in WPF Browser has focus?