- 自定义
- 属性
控制台程序属性输出类型可以选择Windows应用程序,就会去掉控制台
依赖的dll:
PersentationCore WPF的核心类库
PersentationFramework封装了与WPF控件相关类型的类库
System.Xaml XAML解析的类库
WindowBase Window窗体相关的类库
- 简单创建
[STAThread]
static void Main(string[] args)
{
Window mainWindow = new Window();
mainWindow.Title = "WPF应用";
//Application类型用于创建一个消息循环
Application app = new Application();
app.Run(mainWindow);
}
- APP使用
[STAThread]
static void Main(string[] args)
{
App app = new App();
app.Run();
}
public class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow mainWindow = new MainWindow(); //窗口可以创建类,也可以用创建的wpf窗体(控制台不能创建窗体可以创建UserControl1进行改造)
mainWindow.Show();
}
}
public class MainWindow : Window
{
public MainWindow()
{
this.Title = "MainWindow";
this.MouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(MainWindow_MouseLeftButtonDown);
}
void MainWindow_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
MessageBox.Show(e.GetPosition(this).ToString(), this.Title);
}
}
- 结构
Properties中包含版本信息,资源等的属性,可以进行修改。
引用目录下包含using引入的命名空间
App.xaml包含应用程序的信息
Application标签最后一个属性StartupUri="MainWindow.xaml"
指明了应用程序一开始使用的界面(MainWindow.xaml就是可视化的界面,标签Window内的Class="WpfApplication1.MainWindow"指明了界面名)
App.xaml.cs文件(可以右键菜单查看代码进入,也可以展开App.xaml层级,点击进入)是主程序定义。
MainWindow.xaml是界面,可以直接拖入控件,设置控件属性等。
对应的XMAL为:
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
此处为界面布局,如:
<Button Content="Button" Height="58" HorizontalAlignment="Left" Margin="60,72,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click"
/>
</Grid>
</Window>
MainWindow.xaml.cs文件(可以右键菜单查看代码进入,也可以展开MainWindow.xaml层级,点击进入)是界面对应的响应函数及程序。该程序中定义的响应函数与界面中控件是可以剥离的。
如Click="button1_Click"生成了代码:
private void button1_Click(object sender, RoutedEventArgs e){}
如果Click="button1_Click"移动到别的控件,则该函数会变成其他控件的响应函数。如果删除,则该函数就不会被调用。
- 布局
Grid相当于默认的布局控件。
拖入相应的布局控件,将需要被布局的控件放入布局控件,则这些控件就可以整体被布局控件固定位置。
布局控件包括:Canvas,DockPanel,Grid,StackPanel,WrapPanel。
- 属性设置
选中xaml标签或者点击可视化界面中的窗体,可以在属性标签中设置窗体个各种属性
- 全屏
WindowStyle="None" WindowState="Maximized"
- 顶层窗口
Topmost="True"
- COM组件使用
右键解决方案增加 用户控件(非wpf那个)UserControl1
工具栏选择项增加WMP控件,将控件拖入UserControl1的窗口
UserControl1的cs文件中加入接口函数
public void play(String mediaPathName)
{
this.axWindowsMediaPlayer1.URL = mediaPathName;
}
调用:
xaml中拖入 WindowsFormsHost控件
标签加入Name属性为host1
UserControl1 f = new UserControl1();
host1.Child = f;
- 新建窗口
添加窗口(WPF),假设名称为Window1.xaml
Window1 w = new Window1 ();
w.Show();
- 屏幕大小
double height = SystemParameters.PrimaryScreenHeight;
double width = SystemParameters.PrimaryScreenWidth;
- 控件大小/位置
设置左上角位置
**.Margin = new Thickness(x,y,0,0);
**.Width = width;
**.button1.Height = height;
标签HorizontalAlignment="Left"可以自动设置在水平方向贴在最左边
- 去掉控件滚动条
控件的xaml属性中:
ScrollViewer.VerticalScrollBarVisibility="Hidden"
- 定时器
using System.Windows.Threading;
DispatcherTimer m_timer = new DispatcherTimer();
m_timer.Interval = TimeSpan.FromMilliseconds(1000);
m_timer.Tick += new EventHandler(m_timer_Tick);
m_timer.Start();
- 消息处理
键盘消息
if (e.Key == Key.Up)
Key.OemPlus【+键】
Key.OemMinus【-键】
Key.Return【回车】
可以使用断点调试查看e的值得到键盘码
- 控件
- 线程访问控件
控件.Dispatcher.Invoke(() => { 访问控件 });
老版本Invoke使用:
delegate void FunCallBack(string s,int num);
void Fun(string s1, string s2)
{ textBox1.Text= s1+ s2;}
线程中调用:
Fun ff = new Fun(fun);
textBox1.Dispatcher.Invoke(ff, new object[] { "aa", "bb" });
- 颜色
*.Fill = Brushes.Red;
- 文本类型
CtlName为控件名
string ss= this.CtlName.Text; //控件上的文字获取,下拉框,列表控件,静态动态文本等
//下拉框,列表控件添加和选择列
CtlName.Items.Add("item1");
CtlName.SelectedIndex = 0;
- CheckBox
IsChecked 设置/获取勾选状态
- mediaElement
<MediaElement Name="mediaElement1" Stretch="Fill" LoadedBehavior="Manual" />
删除标签中的margin,可以实现填满整个程序
Stretch="Uniform"可以让mediaElement按比例拉伸
打开文件
this.mediaElement1.Source = new Uri("d:\\1.avi");
//可以用File.Exists("d:\\1.avi");验证地址合法性
播放
this.mediaElement1.Play();
暂停
this.mediaElement1.Pause();
停止事件
属性:MediaEnded="mediaElement1_MediaEnded"
音量
this.mediaElement1.Volume += 10;
媒体长度
TimeSpan span = this.mediaElement1.NaturalDuration.TimeSpan;
string s = string.Format("{0},{1}", span.Minutes, span.Seconds);
当前位置
TimeSpan span = this.mediaElement1.Position;
快进
mediaElement1.Position = mediaElement1.Position + TimeSpan.FromSeconds(10);
设置播放位置
TimeSpan span = new TimeSpan(0, 0, 3);//设置为第3秒
this.mediaElement1.Position = span;
- 接收/截获消息
using System.Windows.Interop;
///添加函数
IntPtr hwnd = new WindowInteropHelper(this).Handle;
HwndSource.FromHwnd(hwnd).AddHook(new HwndSourceHook(fun));
private IntPtr fun(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{// uint l = (uint)lParam;可以将lParam转成数字
if (msg == 0x0400+1){ }
return IntPtr.Zero;
}
- 命令行参数
App.xaml中加入属性Startup="Application_Startup"
在App.xaml.cs生成的函数中
private void Application_Startup(object sender, StartupEventArgs e)
{
if (e.Args.Length == 0)
return;
foreach (string arg in e.Args){}
}
- 动画
using System.Windows.Media.Animation;
/////////////////设置控件在1s内从不透明变成半透明
Storyboard story = new Storyboard();
DoubleAnimation animation = new DoubleAnimation();
//form和to是指代属性变化前后的值
animation.From = 1;
animation.To = 0.5;
animation.Duration = TimeSpan.FromMilliseconds(1000);
Storyboard.SetTarget(animation, this.button1);
//单一属性名可以通过控件的属性列表查找
Storyboard.SetTargetProperty(animation, new PropertyPath("Opacity"));
story.Children.Add(animation);
story.Begin();
- 透明背景
Background="Transparent"
using System.Windows.Interop;
using System.Runtime.InteropServices;
添加引用System.Drawing
============类内函数
void Transparent(double Width, double Height)
{
try
{
IntPtr mainWindowPtr = new WindowInteropHelper(this).Handle;
HwndSource mainWindowSrc = HwndSource.FromHwnd(mainWindowPtr);
mainWindowSrc.CompositionTarget.BackgroundColor = Color.FromArgb(0, 0, 0, 0);
System.Drawing.Graphics desktop = System.Drawing.Graphics.FromHwnd(mainWindowPtr);
float DesktopDpiX = desktop.DpiX;
float DesktopDpiY = desktop.DpiY;
NonClientRegionAPI.MARGINS margins = new NonClientRegionAPI.MARGINS();
margins.cxLeftWidth = Convert.ToInt32(Width * (DesktopDpiX / 96));
margins.cxRightWidth = Convert.ToInt32(Width * (DesktopDpiX / 96));
margins.cyTopHeight = Convert.ToInt32(Height * (DesktopDpiX / 96));
margins.cyBottomHeight = Convert.ToInt32(Height * (DesktopDpiX / 96));
int hr = NonClientRegionAPI.DwmExtendFrameIntoClientArea(mainWindowSrc.Handle, ref margins);
}
catch (DllNotFoundException)
{
Application.Current.MainWindow.Background = Brushes.White;
}
}
=========命名空间内增加类
class NonClientRegionAPI
{
[StructLayout(LayoutKind.Sequential)]
public struct MARGINS
{
public int cxLeftWidth;
public int cxRightWidth;
public int cyTopHeight;
public int cyBottomHeight;
};
[DllImport("DwmApi.dll")]
public static extern int DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS pMarInset);
}
===========使用
Transparent(this.Width, this.Height);
- 右键菜单
控件带context属性
<ListBox.ContextMenu>
<ContextMenu Name="cm" StaysOpen="true">
<MenuItem Header="选择文件夹"/>
<MenuItem Header="一级菜单">
<MenuItem Header="二级菜单"/>
</MenuItem>
</ContextMenu>
</ListBox.ContextMenu>