listbox not working in C# - listbox

I would like to add items to list box.
It's completely fine in the button click function.
However, if I put it in other function, it doesn't work.
or in other words, I can see "start" in the box, but not the "mission".
Thanks
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("start");
listBox1.Items.Add("start");
token = textBox1.Text;
shipid = textBox2.Text;
host = textBox3.Text;
shipid = shipid.Replace(",", "%2C");
System.Timers.Timer t = new System.Timers.Timer(5000);
t.Elapsed += new System.Timers.ElapsedEventHandler(Mission3);
t.AutoReset = true;
t.Enabled = true;
}
private void Mission3(object source, System.Timers.ElapsedEventArgs e)
{
progress = action(progress, 0, 0, "0");
listBox1.Items.Add("mission");
}

Related

WebView2 download event is not firing - Windows forms application

I create windows forms application using WebView2 control, in there I add DownloadStarting event for select the downloading path to the user but unfortunately DownloadStarting event not firing.
private async void InitBrowser()
{
var environment = await CoreWebView2Environment.CreateAsync(null, #"C:\Temp", null);
webView.CoreWebView2InitializationCompleted += WebView_CoreWebView2InitializationCompleted;
await webView.EnsureCoreWebView2Async(environment);
webView.NavigationCompleted += WebView_NavigationCompleted;
webView.Source = new Uri("myurl");
}
private void WebView_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
webView.CoreWebView2.DownloadStarting += CoreWebView2_DownloadStarting;
}
private void CoreWebView2_DownloadStarting1(object sender, CoreWebView2DownloadStartingEventArgs e)
{
downloadOperation = e.DownloadOperation;
e.Handled = true;
e.ResultFilePath = Savefile();
}

BackRequested is triggering more than once in UWP app

I have an app in which i mainly have a webview. i am having a problem. i have made the back button to goto previous webpage of webview it works fine and when it has no previous pages it quits with a MessageBox(Popup). The problem is when i navigate another page and press back it recursively triggers back button event and shows the MessageBox
Windows.UI.Core.SystemNavigationManager.GetForCurrentView().BackRequested += (s, e) =>
{
e.Handled = true;
if (Web_view.CanGoBack)
{
Web_view.GoBack();
e.Handled = true;
}
else
{
quit();
e.Handled = true;
}
};
The above is code of my main page
private async void quit()
{
MessageDialog msg = new MessageDialog("Do you really want to quit?", "Quit");
msg.Commands.Add(new UICommand("Yes") { Id = 0 });
msg.Commands.Add(new UICommand("No") { Id = 1 });
var ans = await msg.ShowAsync();
if(ans.Id.Equals(0))
{
//System.Diagnostics.Debug.WriteLine("Exit");
App.Current.Exit();
}
}
this is the code of quit function.
I am navigating to another page from this using code
private void about_Click(object sender, RoutedEventArgs e)
{
Frame.Navigate(typeof(BlankPage1));
}
And the backRequested code of blanckPage1 is
SystemNavigationManager.GetForCurrentView().BackRequested += (s,e)=>
{
e.Handled = true;
// Windows.UI.Core.SystemNavigationManager.GetForCurrentView().BackRequested -= BlankPage1_BackRequested;
//System.Diagnostics.Debug.WriteLine("BackRequested");
if (Frame.CanGoBack)
{
e.Handled = true;
Frame.GoBack();
}
else
{
e.Handled = true;
}
};
To make it more clear for example when i open the app the webview navigates to www.example.com then following the links there i will get to some other page(for example www.example.com/link/firstlink). then i will navigate my frame to blankpage1 and from there i will press back. then insted of coming back to previous page (www.example.com/link/firstlink) it comes to beginning page (www.example.com) and shows the quit popup how can i fix this?
Thank you for all your replay.
Your problem is that you are still keeping the event handler: In your code when navigating back from BlankPage1, both .BackRequested handlers are called. You would need to deregister from .BackRequested on MainPage when leaving it, for example like this:
MainPage:
protected override void OnNavigatedTo(NavigationEventArgs e) {
SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
}
protected override void OnNavigatedFrom(NavigationEventArgs e) {
SystemNavigationManager.GetForCurrentView().BackRequested -= OnBackRequested;
}
private void OnBackRequested(object sender, BackRequestedEventArgs e) {
// Your code to navigate back
if (Web_view.CanGoBack)
{
Web_view.GoBack();
e.Handled = true;
}
else
{
quit();
e.Handled = true;
}
}
And the same on BlankPage1... Though it would be far easier to register to BackRequested in your App.xaml.cs where you would handle your (Window.Current.Content as Frame) for the whole app, something like this. To make it "nice" code also with an interface:
INavigationPage:
public interface INavigationPage {
// When overriding the method returns true or false if the Page handled back request
bool HandleBackRequested();
}
App.xaml.cs:
// ... Code before
protected override void OnLaunched(LaunchActivatedEventArgs e) {
SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
}
private void OnBackRequested(object sender, BackRequestedEventArgs e) {
Frame frame = Window.Current.Content as Frame;
if (frame == null) return;
INavigationPage page = frame.Content as INavigationPage;
if (page == null) return;
// Ask if the page handles the back request
if (page.HandleBackRequested()) {
e.Handled = true;
// If not, go back in frame
} else if (frame.CanGoBack) {
e.Handled = true;
frame.GoBack();
}
}
// ... Code after
MainPage.xaml.cs:
... class MainPage : Page, INavigationPage {
// ... Code before
// Implement the interface handling the backRequest here if possible
public bool HandleBackRequested() {
if (Web_view.CanGoBack) {
Web_view.GoBack();
return true;
}
return false;
}
// ... Code after
}
Then the BlankPage does not require any code and no subscribing to .BackRequested.

Need to print UWP MapControl with route results

I have a MapControl working just creating my route. Now, I just need to figure out a way to print it out. Using the UWP printing sample, I get a black box where the control should be. The map and route are being built, just not rendered correctly in the print preview. I thought I saw a MapControl.Print... but I think that was in the Bing.Maps stuff. Any pointers would be appreciated. Thanks.
Using the UWP printing sample, I get a black box where the control should be.
It seems the MapControl can not be printed.
As a workround, we can use RenderTargetBitmap to get the image from the MapControl. That we can print the image.
Using a RenderTargetBitmap, you can accomplish scenarios such as applying image effects to a visual that originally came from a XAML UI composition, generating thumbnail images of child pages for a navigation system, or enabling the user to save parts of the UI as an image source and then share that image with other apps.
Because RenderTargetBitmap is a subclass of ImageSource, it can be used as the image source for Image elements or an ImageBrush brush.
For more info,see RenderTargetBitmap.
For example:
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(MyMap);
MyImage.Source = renderTargetBitmap;
The printing code:
public sealed partial class MainPage : Page
{
private PrintManager printmgr = PrintManager.GetForCurrentView();
private PrintDocument printDoc = null;
private PrintTask task = null;
public MainPage()
{
this.InitializeComponent();
printmgr.PrintTaskRequested += Printmgr_PrintTaskRequested;
}
private void Printmgr_PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
{
var deferral = args.Request.GetDeferral();
task = args.Request.CreatePrintTask("Print", OnPrintTaskSourceRequrested);
task.Completed += PrintTask_Completed;
deferral.Complete();
}
private void PrintTask_Completed(PrintTask sender, PrintTaskCompletedEventArgs args)
{
//the PrintTask is completed
}
private async void OnPrintTaskSourceRequrested(PrintTaskSourceRequestedArgs args)
{
var def = args.GetDeferral();
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
args.SetSource(printDoc?.DocumentSource);
});
def.Complete();
}
private async void appbar_Printer_Click(object sender, RoutedEventArgs e)
{
if (printDoc != null)
{
printDoc.GetPreviewPage -= OnGetPreviewPage;
printDoc.Paginate -= PrintDic_Paginate;
printDoc.AddPages -= PrintDic_AddPages;
}
this.printDoc = new PrintDocument();
printDoc.GetPreviewPage += OnGetPreviewPage;
printDoc.Paginate += PrintDic_Paginate;
printDoc.AddPages += PrintDic_AddPages;
bool showPrint = await PrintManager.ShowPrintUIAsync();
}
private void PrintDic_AddPages(object sender, AddPagesEventArgs e)
{
printDoc.AddPage(this);
printDoc.AddPagesComplete();
}
private void PrintDic_Paginate(object sender, PaginateEventArgs e)
{
PrintTaskOptions opt = task.Options;
printDoc.SetPreviewPageCount(1, PreviewPageCountType.Final);
}
private void OnGetPreviewPage(object sender, GetPreviewPageEventArgs e)
{
printDoc.SetPreviewPage(e.PageNumber, this);
}
}

How do i allow/deny a key based on how many times it appears on a listbox?

So i got a listbox where i'll have random vowels/cons and i wanna limit what the person can write on the textbox according to these keys i'll have on the listbox. So far i got to allowing only whats on the listbox but you can use it as many times as you want (ex you have ABIIDC on the listbox, you can type aaaaaaabbbbbiiiiiidddddddccc on the texbox), and what i want is for them to be able to use each key the times it apperas on the listbox (in the previous case, a once, b once, i twice, d once, c once).
This is what i have so far:
private bool denykey = false;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
denykey = false;
if (!listBox1.Items.Contains(e.KeyCode))
{
denykey = true;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (denykey == true)
{
e.Handled = true;
}
if(Control.ModifierKeys == Keys.Control)
{
e.Handled = true;
}
}
don't mind the "control" part, it's only to prevent copy and paste
Ok so with help from some friends i was able to get what i wanted, here is what we did:
private bool denykey = false;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
denykey = false;
return;
}
var countText = 0;
foreach (var letter in textBox1.Text)
if (letter.Equals(e.KeyCode.ToString()[0]))
countText = countText + 1;
var countList = 0;
foreach (var letterList in listBox1.Items)
if (letterList.ToString().Equals(e.KeyCode.ToString()))
countList = countList + 1;
denykey = false;
if (countText >= countList)
denykey = true;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (denykey == true)
{
e.Handled = true;
}
if(Control.ModifierKeys == Keys.Control)
e.Handled = true;
}

navigating a image from page to other in mono android

I have an ImageView and Button in an Activity, lets call it A. When clicking on the Button, I start the image gallery, where I select an image and load that into the ImageView.
On the ImageView I subscribe to the Touch events, where I want to launch another Activity, B.
My question is, how can I in Activity B get the image, which was selected in Activity A? How is data passed fomr Activity to another Activity?
Here is my code in Activity A:
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
_imageView = FindViewById<ImageView>(Resource.Id.imageView1);
_imageView.Touch += TouchMeImageViewOnTouch;
Button button = FindViewById<Button>(Resource.Id.button1);
button.Click += ButtonOnClick;
}
private void ButtonOnClick(object sender, EventArgs eventArgs)
{
Intent = new Intent();
Intent.SetType("image/*");
Intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), PickImageId);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
{
Uri uri = data.Data;
_imageView.SetImageURI(uri);
string path = GetPathToImage(uri);
Toast.MakeText(this, path, ToastLength.Long);
}
}
private string GetPathToImage(Uri uri)
{
string path = null;
string[] projection = new[] { Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data };
using (var cursor = ManagedQuery(uri, projection, null, null, null))
{
if (cursor != null)
{
int columnIndex = cursor.GetColumnIndexOrThrow(
Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
cursor.MoveToFirst();
path = cursor.GetString(columnIndex);
}
}
return path;
}
private void TouchMeImageViewOnTouch(object sender, View.TouchEventArgs touchEventArgs)
{
}
In your TouchMeImageViewOnTouch method, you will need to start Activity B. This is done by creating an Intent. This Intent can hold extra stuff the Activity you launch (B), will be able to get hold of.
So I see that you already found out how to get the path to the image, which you simply can pass along to Activity B in the Intent which is done like this:
private void TouchMeImageViewOnTouch(object sender, View.TouchEventArgs touchEventArgs)
{
var intent = new Intent(this, typeof (MainActivity));
intent.PutExtra("imagePath", path);
StartActivity(intent);
}
Then in Activity B you can get the path with:
Intent.GetStringExtra("imagePath");
Then do whatever you want with it.

Resources