I have another WPF Window i've created.. say window2.xaml. I have a button.. and on click i want it to load that window.. i've tried Googling but nothing seems to be working. It just loads a blank page. I know this is really simple, but I really can't find how to do it through my searches.
This is what i have tried:
GameClock temp = new GameClock();
temp.ShowDialog(); //just shows blank window
temp.Show(); //just shows a blank window too
EDIT: I figured out the problem. I took out the initialize component because there an an error. I thought it was something only the main window needed. When I put it back, it works. Thanks, everyone.
try this... u can use like a generic methode
private void button_ItemClick(object sender, ItemClickEventArgs e)
{
try
{
OpenWin("window2", new Uri(#"window2.xaml", UriKind.Relative), "Window2Label");
}
catch (Exception ex)
{
Message.Show(ex);
}
}
public static DocumentPanel OpenWin(string namePainelItem, Uri xamlPath, string caption = "", RoutedEventHandler unloadEvent = null, bool closeOpenWin = false)
{
try
{
if (closeOpenWin)
{
CloseWin(namePainelItem, false);
}
DocumentPanel panel1 = GetWin(namePainelItem);
if (panel1 == null)
{
panel1 = new DocumentPanel();
panel1.Caption = caption;
panel1.Name = namePainelItem;
panel1.Content = xamlPath;
if (unloadEvent != null)
{
panel1.Unloaded += unloadEvent;
}
hdl.dockLayoutManager.DockController.Insert(hdl.documentGroup1, panel1, 1);
hdl.dockLayoutManager.DockController.ActiveItem = panel1;
}
else
{
if (panel1.Visibility != Visibility.Visible)
panel1.Visibility = Visibility.Visible;
if(panel1.IsClosed)
panel1.Closed = false;
hdl.dockLayoutManager.DockController.ActiveItem = panel1;
}
return panel1;
}
catch (Exception ex)
{
Message.Show(ex);
}
return new DocumentPanel();
}
public static void CloseWin(string namePainelItem)
{
try
{
BaseLayoutItem item = hdl.dockLayoutManager.GetItem(namePainelItem);
if (item != null)
{
hdl.documentGroup1.Items.Remove(item);
hdl.dockLayoutManager.DockController.RemovePanel((DocumentPanel)item);
item = null;
}
}
catch (Exception ex)
{
Message.Show(ex);
}
}
You may need to read the XAML file before creating the instance of GameClock. Something like this:
GameClock clock;
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
clock = (GameClock)XamlReader.Load(fs);
JAB
Related
I have converted my old StartActivityForResult code to the new RegisterForActivityResult as StartActivityForResult is depreciated in the android API 29 and higher. My new code works perfectly, except that result in class ActivityResultCallback is always null. I need to be able to know when the user cancels the taking of the picture when they hit the back button, otherwise the app crashes (if a previous picture doesn't already exist) or a previously taken picture is processed again. My code (showing only the relevant code):
public class Photo : AppCompatActivity
{
public ImageView MyImageView;
public ImageButton camerabutton;
public bool PictureTaken = false;
private CurrentSubjectInfo MySubjectInfo;
private ActivityResultCallback _activityResultCallback;
private ActivityResultLauncher _activityResultLauncher;
private Uri uri;
protected override void OnCreate(Bundle bundle)
{
try
{
_activityResultCallback = new ActivityResultCallback();
_activityResultCallback.OnActivityResultCalled += ActivityResultCallback_ActivityResultCalled;
_activityResultLauncher = RegisterForActivityResult(new ActivityResultContracts.TakePicture(), _activityResultCallback);
RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;
base.OnCreate(bundle);
SetContentView(Resource.Layout.Photo);
PictureTaken = false;
MySubjectInfo = new CurrentSubjectInfo("", "", "", "", "");
// retrieve subject information from previous activity
MySubjectInfo = Mybundle.GetParcelable("MySubjectInfo", Java.Lang.Class.FromType(typeof(CurrentSubjectInfo))) as CurrentSubjectInfo;
ImageButton camerabutton = FindViewById<ImageButton>(Resource.Id.button1);
MyImageView = FindViewById<ImageView>(Resource.Id.imageView1);
camerabutton.Click += (sender, evt) =>
{
var cameraispresent = CheckCameraHardware();
if (cameraispresent)
{
try
{
// get directory where pictures are stored
App._dir = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures);
// build file name
MySubjectInfo.Name = MySubjectInfo.Name.Replace(",", "");
MySubjectInfo.Name = MySubjectInfo.Name.Replace(" ", "");
MySubjectInfo.Name = MySubjectInfo.Name.Replace(".", "");
var filename = MySubjectInfo.Name + ".jpg";
App._file = new File(App._dir, String.Format(filename, Guid.NewGuid()));
uri = FileProvider.GetUriForFile(this, this.ApplicationContext.PackageName + ".provider",App._file);
// launch camera activity
_activityResultLauncher.Launch(uri);
}
catch (Exception e)
{
// trap error and log it
};
}
};
}
}
Boolean CheckCameraHardware()
{
Android.Content.PM.PackageManager pm = PackageManager;
if (pm.HasSystemFeature(Android.Content.PM.PackageManager.FeatureCamera))
{
// this device has a camera
return true;
}
else
{
// no camera on this device
return false;
}
}
private void ActivityResultCallback_ActivityResultCalled(object sender, ActivityResult result)
{
// result is always null, so I don't check it
try
{
// Because the resulting bitmap is rotated and too large, I set original orientation and resize
// suffice it to say it works perfectly so I won't post the code here
int height = 260;
int width = 200;
App.bitmap = App._file.Path.LoadAndResizeBitmap(width, height);
Bitmap bitmap = App.bitmap;
var filePath = App._file.AbsolutePath;
// save the resized bitmap, overwriting original file
var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create);
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
stream.Close();
// set the imageview to the resulting bitmap
MyImageView.SetImageBitmap (App.bitmap);
// cleanup
bitmap = null;
App.bitmap = null;
PictureTaken = true;
}
catch (Exception ex)
{
PictureTaken = false;
// trap and log error
}
}
}
This is the ActivityResultCallback class:
public class ActivityResultCallback : Java.Lang.Object, IActivityResultCallback
{
public EventHandler<ActivityResult> OnActivityResultCalled;
public void OnActivityResult(Java.Lang.Object result)
{
ActivityResult activityResult = result as ActivityResult;
OnActivityResultCalled?.Invoke(this, activityResult);
}
}
As stated all this code executes perfectly with no errors except that Java.Lang.Object result is always null. I need to know when the user cancels the camera activity, I would assume that Java.Lang.Object result would indicate cancelled but I get nothing. What am I missing?
Ok, after some playing around I noticed that the parameter Java.Lang.Object result in the ActivityResultCallback class was either true or false depending on what the user did with the camera. So I changed the class to:
public class ActivityResultCallback : Java.Lang.Object, IActivityResultCallback
{
public EventHandler<ActivityResult> OnActivityResultCalled;
public void OnActivityResult(Java.Lang.Object result)
{
ActivityResult activityResult;
if ((bool)result)
{
activityResult = new ActivityResult((int)Result.Ok, null);
} else
{
activityResult = new ActivityResult((int)Result.Canceled, null);
}
OnActivityResultCalled?.Invoke(this, activityResult);
}
}
In the ActivityResultCallback_ActivityResultCalled function, I modified it to this:
private void ActivityResultCallback_ActivityResultCalled(object sender, ActivityResult result)
{
try
{
if (result.ResultCode == (int)Result.Ok)
{
int height = 260;
int width = 200;
App.bitmap = App._file.Path.LoadAndResizeBitmap(width, height);
Bitmap bitmap = App.bitmap;
var filePath = App._file.AbsolutePath;
var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create);
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
stream.Close();
MyImageView.SetImageBitmap(App.bitmap);
bitmap = null;
App.bitmap = null;
PictureTaken = true;
}
}
catch (Exception ex)
{
// trap and log error
}
}
activityResult apparently has, at a minimum, two parameters, the result and data. I already had what I needed for data so I set that to null and cast Result.Ok or Result.Cancelled to int depending on whether result was true or false. I still don't totally understand how to use the new ActivityForResult API, but this works for me and I'm running with it.
IN WPF project, whenever I try to add selected Student in selected university and display it on assoiated table.
Here is image of my table -
https://i.stack.imgur.com/KUHuF.png
I encounter this problem, once I hit update assosiated button.
public System.Data.Linq.Table<Student> Students
{
get
{
return this.GetTable<Student>();
}
}
The above code is in "Dataclasses1.designer.cs" window.
However, upon restarting the program, selected student is sucessfully added to selected university.
Here is my code -
private void UpdateAssociatedStudent_Click(object sender, RoutedEventArgs e)
{
if(ListUniversity.SelectedItem != null || ListStudent.SelectedItem != null)
{
using (dataContext = new DataClasses1DataContext())
{
UniversityManager universityManager = new UniversityManager
{
UniFK = int.Parse(ListUniversity.SelectedValue.ToString()),
StdFK = int.Parse(ListStudent.SelectedValue.ToString())
};
dataContext.UniversityManagers.InsertOnSubmit(universityManager);
dataContext.SubmitChanges();
}
ShowAssociatedStudents();
Sucess.Text = "Student is sucessfully added to University";
}
}
Edit - Adding image for error
https://i.stack.imgur.com/ApPxd.png
I think that you may need to change this line of code:
if(ListUniversity.SelectedItem != null || ListStudent.SelectedItem != null)
to
if(ListUniversity.SelectedItem != null && ListStudent.SelectedItem != null)
I've solved this issue by running try/catch instead of using 'Using' statement. my edited code looks like this.
//Add selected student from selected university in associated student listbox
private void UpdateAssociatedStudent_Click(object sender, RoutedEventArgs e)
{
if(ListUniversity.SelectedItem != null && ListStudent.SelectedItem != null)
{
try
{
uniManager = new UniversityManager()
{
UniFK = Convert.ToInt32(ListUniversity.SelectedValue),
StdFK = Convert.ToInt32(ListStudent.SelectedValue)
//UniFK = int.Parse(ListUniversity.SelectedItem.ToString()),
//StdFK = int.Parse(ListStudent.SelectedItem.ToString())
};
dataContext.UniversityManagers.InsertOnSubmit(uniManager);
dataContext.SubmitChanges();
ShowAssociatedStudents();
}
catch (FileNotFoundException)
{
Console.WriteLine("File Not Found.");
}
catch (OutOfMemoryException)
{
Console.WriteLine("Out of Memory.");
}
catch (IOException)
{
Console.WriteLine("An I/O error has occured.");
}
}
else
{
Failed.Text = "Please select the missing items from either university or student.";
}
}
I created a project in C# windows form application in visual studio 2010 and .net framework version 4.0.
In my project Main form contains another form which name is Communication.
Communication form has five combo box for COM Port settings and Connect button.
When I select Items from Combo box drop down list and click on connect button then text on button shows disconnect. Then I will close Communication form.Comport gets connected.
My main problem is that, when I reopen form for disconnect communication. I want same Items in combo box and text on button shows Disconnect as before.
I don't know how to do this. Please help me to solve this issue. Thanks in advance.
Code for Communication form
public partial class Connect : Form
{
public bool Connect_Status = false;
public Connect()
{
InitializeComponent();
COM_List();
}
private void COM_List()
{
for (int i = 0; i < CommPortManager.Instance.GetCommList().Count; i++)
{
cb_CommPort.Items.Add(CommPortManager.Instance.GetCommList()[i]);
}
}
private void btn_Connect_Click(object sender, EventArgs e)
{
CommPortManager.Instance.PortName = cb_CommPort.Text;
CommPortManager.Instance.BaudRate = cb_BaudRate.Text;
CommPortManager.Instance.Parity = cb_Parity.Text;
CommPortManager.Instance.StopBits = cb_StopBits.Text;
CommPortManager.Instance.DataBits = cb_DataBits.Text;
if ((cb_CommPort.Text == "") || (cb_BaudRate.Text == "") || (cb_Parity.Text == "") || (cb_DataBits.Text == "") || (cb_StopBits.Text == ""))
{
MessageBox.Show("Please select all communication settings and then Save", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
Connect_Status = false;
}
else
{
if (CommPortManager.Instance.COM_Open() == false)
{
MessageBox.Show("Could not open the COM port. Most likely it is already in use, has been removed, or is unavailable.", "TestCertificate", MessageBoxButtons.OK, MessageBoxIcon.Information);
Connect_Status = false;
}
else
{
CommPortManager.Instance.COM_Close();
Connect_Status = true;
btn_Connect.Text = "Disconnect";
}
}
}
private void btn_Close_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
And Code for main form where this communication form open
private void connectToolStripMenuItem_Click(object sender, EventArgs e)
{
Connect connect = new Connect();
connect.ShowDialog();
if (connect.Connect_Status == true)
{
lb_Comm.Text = String.Format("Connected to '{0}'", connect.cb_CommPort.SelectedItem);
}
else
{
CommPortManager.Instance.COM_Close();
lb_Comm.Text = "Not Connected";
}
}
You have to create a Serializable class in which you will be saving the indexes of combo boxes.
[Serializable]
class SaveComboSettings
{
[OptionalField]
public int cmb1SelectedIndex = 0;
[OptionalField]
public int cmb2SelectedIndex = 0;
}
At the time of closing the form, You need to serialize the combo boxes's index in this class's object. Like -
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//Assigning the current selected index of combobox to serialize class.
SaveComboSettings f1 = new SaveComboSettings();
f1.cmb1SelectedIndex = this.comboBox1.SelectedIndex;
f1.cmb2SelectedIndex = this.comboBox2.SelectedIndex;
//Serialize
BinaryFormatter bf = new BinaryFormatter();
FileStream fsout = new FileStream("ComboBoxSettings.binary", FileMode.Create, FileAccess.Write, FileShare.None);
try
{
using (fsout)
{
bf.Serialize(fsout, f1);
}
}
catch (Exception Ex)
{
//Some Exception occured
}
}
When form is loaded back/restart, You need to deserialize the settings and assign the combo box values back -
public Form1()
{
InitializeComponent();
DeserializeFormSettings();
}
public void DeserializeFormSettings()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream fsin;
if(File.Exists("ComboBoxSettings.binary"))
fsin = new FileStream("ComboBoxSettings.binary", FileMode.Open, FileAccess.Read, FileShare.None);
else
return;
try
{
using (fsin)
{
SaveComboSettings f1 = (SaveComboSettings)bf.Deserialize(fsin);
this.comboBox1.SelectedIndex = f1.cmb1SelectedIndex;
this.comboBox2.SelectedIndex = f1.cmb2SelectedIndex;
}
}
catch(Exception Ex)
{
// "An error has occured";
}
}
This example is created with combo box only. You can use the same way for string on button also.
The execs at my company would like a particular custom control of our ui to make a best-effort at preventing screen capture. I implemented a slick solution using SetWindowDisplayAffinity and DWMEnableComposition at the top Window level of our application to prevent screen capture of the entire app but the previously mentioned execs weren't happy with that. They want only the particular UserControl to prevent screen capture, not the entire app.
The custom control is a .NET 2.0 Windows.Forms.UserControl wrapped in a 4.5 WPF WindowsFormsHost contained by a 4.5 WPF Window control.
Before I tell the execs where to go, I want to be certain there isn't a reasonable way to implement this.
So, my question is: How do I implement screen capture prevention of a .NET 2.0 UserControl?
Thanks
i had an idea:
the user click "PrintScreen", a capture from my program is copy to ClipBoard.
So, all what i need it: to catch cliboard an check if he contains an image.
if yes: i delete the image from clipboard.
the code:
//definition a timer
public static Timer getImageTimer = new Timer();
[STAThread]
static void Main()
{
getImageTimer.Interval = 500;
getImageTimer.Tick += GetImageTimer_Tick;
getImageTimer.Start();
......
}
private static void GetImageTimer_Tick(object sender, EventArgs e)
{
if (Clipboard.ContainsImage())//if clipboard contains an image
Clipboard.Clear();//delete
}
*but it avoid any time program is running. (you need to know if your program is foreground, and then check clipboard);
You might be able to capture the key stroke.
Below is a method I used for that, but it had limited success:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if ((m_parent != null) && m_parent.ScreenCapture(ref msg)) {
return true;
} else {
return base.ProcessCmdKey(ref msg, keyData);
}
}
protected override bool ProcessKeyEventArgs(ref Message msg) {
if ((m_parent != null) && m_parent.ScreenCapture(ref msg)) {
return true;
} else {
return base.ProcessKeyEventArgs(ref msg);
}
}
Returning "True" was supposed to tell the system that the PrintScreen routine was handled, but it often still found the data on the clipboard.
What I did instead, as you can see from the call to m_parent.ScreenCapture, was to save the capture to a file, then display it in my own custom image viewer.
If it helps, here is the wrapper I created for the custom image viewer in m_parent.ScreenCapture:
public bool ScreenCapture(ref Message msg) {
var WParam = (Keys)msg.WParam;
if ((WParam == Keys.PrintScreen) || (WParam == (Keys.PrintScreen & Keys.Alt))) {
ScreenCapture(Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
msg = new Message(); // erases the data
return true;
}
return false;
}
public void ScreenCapture(string initialDirectory) {
this.Refresh();
var rect = new Rectangle(Location.X, Location.Y, Size.Width, Size.Height);
var imgFile = Global.ScreenCapture(rect);
//string fullName = null;
string filename = null;
string extension = null;
if ((imgFile != null) && imgFile.Exists) {
filename = Global.GetFilenameWithoutExt(imgFile.FullName);
extension = Path.GetExtension(imgFile.FullName);
} else {
using (var worker = new BackgroundWorker()) {
worker.DoWork += delegate(object sender, DoWorkEventArgs e) {
Thread.Sleep(300);
var bmp = new Bitmap(rect.Width, rect.Height);
using (var g = Graphics.FromImage(bmp)) {
g.CopyFromScreen(Location, Point.Empty, rect.Size); // WinForm Only
}
e.Result = bmp;
};
worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e) {
if (e.Error != null) {
var err = e.Error;
while (err.InnerException != null) {
err = err.InnerException;
}
MessageBox.Show(err.Message, "Screen Capture", MessageBoxButtons.OK, MessageBoxIcon.Stop);
} else if (e.Cancelled) {
} else if (e.Result != null) {
if (e.Result is Bitmap) {
var bitmap = (Bitmap)e.Result;
imgFile = new FileInfo(Global.GetUniqueFilenameWithPath(m_screenShotPath, "Screenshot", ".jpg"));
filename = Global.GetFilenameWithoutExt(imgFile.FullName);
extension = Path.GetExtension(imgFile.FullName);
bitmap.Save(imgFile.FullName, ImageFormat.Jpeg);
}
}
};
worker.RunWorkerAsync();
}
}
if ((imgFile != null) && imgFile.Exists && !String.IsNullOrEmpty(filename) && !String.IsNullOrEmpty(extension)) {
bool ok = false;
using (SaveFileDialog dlg = new SaveFileDialog()) {
dlg.Title = "ACP Image Capture: Image Name, File Format, and Destination";
dlg.FileName = filename;
dlg.InitialDirectory = m_screenShotPath;
dlg.DefaultExt = extension;
dlg.AddExtension = true;
dlg.Filter = "PNG Image|*.png|Jpeg Image (JPG)|*.jpg|GIF Image (GIF)|*.gif|Bitmap (BMP)|*.bmp" +
"|EWM Image|*.emf|TIFF Image|*.tif|Windows Metafile (WMF)|*.wmf|Exchangable image file|*.exif";
dlg.FilterIndex = 0;
if (dlg.ShowDialog(this) == DialogResult.OK) {
imgFile = imgFile.CopyTo(dlg.FileName, true);
m_screenShotPath = imgFile.DirectoryName;
ImageFormat fmtStyle;
switch (dlg.FilterIndex) {
case 2: fmtStyle = ImageFormat.Jpeg; break;
case 3: fmtStyle = ImageFormat.Gif; break;
case 4: fmtStyle = ImageFormat.Bmp; break;
case 5: fmtStyle = ImageFormat.Emf; break;
case 6: fmtStyle = ImageFormat.Tiff; break;
case 7: fmtStyle = ImageFormat.Wmf; break;
case 8: fmtStyle = ImageFormat.Exif; break;
default: fmtStyle = ImageFormat.Png; break;
}
ok = true;
}
}
if (ok) {
string command = string.Format(#"{0}", imgFile.FullName);
try { // try default image viewer
var psi = new ProcessStartInfo(command);
Process.Start(psi);
} catch (Exception) {
try { // try IE
ProcessStartInfo psi = new ProcessStartInfo("iexplore.exe", command);
Process.Start(psi);
} catch (Exception) { }
}
}
}
}
I wrote that years ago, and I don't work there now. The source code is still in my Cloud drive so that I can leverage skills I learned once (and forgot).
That code isn't meant to get you completely done, but just to show you a way of doing it. If you need any help with something, let me know.
Not a silver bullet, but could form part of a strategy...
If you were worried about the windows snipping tool or other known snipping tools, you could subscribe to Windows events to capture a notification of when SnippingTool.exe was launched and then hide your application until it was closed:
var applicationStartWatcher = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"));
applicationStartWatcher.EventArrived += (sender, args) =>
{
if (args.NewEvent.Properties["ProcessName"].Value.ToString().StartsWith("SnippingTool"))
{
Dispatcher.Invoke(() => this.Visibility = Visibility.Hidden);
}
};
applicationStartWatcher.Start();
var applicationCloseWatcher = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"));
applicationCloseWatcher.EventArrived += (sender, args) =>
{
if (args.NewEvent.Properties["ProcessName"].Value.ToString().StartsWith("SnippingTool"))
{
Dispatcher.Invoke(() =>
{
this.Visibility = Visibility.Visible;
this.Activate();
});
}
};
applicationCloseWatcher.Start();
You will probably need to be running as an administrator for this code to work.
ManagementEventWatcher is in the System.Management assembly.
This coupled with some strategy for handling the print screen key: for example something like this may at least make it difficult to screen capture.
I've got a custom control that I'm trying to print. I've tried changing the margin's on my window to "indent" my control, but it still cuts off the left and top. I've also tried the following in my print method:
private void bttnPrint_Click(object sender, RoutedEventArgs e)
{
UserControl hddc = HDDC;
var printDlg = new PrintDialog
{PrintTicket = {PageOrientation = PageOrientation.Landscape, PageBorderless = PageBorderless.Unknown}};
//printDlg.PrintTicket.PageMediaSize.PageMediaSizeName = PageMediaSizeName.NorthAmerica11x17;
if (printDlg.ShowDialog() == true)
{
printDlg.PrintVisual(hddc, "HDDC Report");
}
else
{
MessageBox.Show("Print Canceled");
}
}
Still, no joy. I've got the feeling there's a silly setting I'm missing, but I just can't seem to find it. Why is my print cutting off on the top and left?
public void Printing() {
try {
streamToPrint = new StreamReader (filePath);
try {
PrintDocument prd = new PrintDocument();
prd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
prd.PrinterSettings.PrinterName = printer;
// Set the page orientation to landscape.
prd.DefaultPageSettings.Landscape = true;
prd.Print();
}
finally {
streamToPrint.Close() ;
}
}
catch(Exception ex) {
MessageBox.Show(ex.Message);
}
}
Namespace: System.Drawing.Printing
or maybe this link can help u
Page truncate in right side for landscape orientation with trimmargins using PdfSharp